Python教程

Python | 实现在Pycharm IDE环境下的2048小游戏

本文主要是介绍Python | 实现在Pycharm IDE环境下的2048小游戏,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

针对2048,笔者根据自身仅会的一些python库和代码基础编写了一个2048的雏形,由于暂时没有对python GUI的相关实操经验,因此输出结果与操作仅在Pycharm的run结果中呈现,具体实现效果如下:

 具体代码内容如下:

import numpy as np
import random


class Game:
    def __init__(self):
        self.row = 4
        self.col = 4
        self.status_matrix = np.zeros((self.row, self.col))
        self.value_matrix = np.zeros((self.row, self.col))
        self.response = 0
        self.alive = True
        self.score = 0

    def give_intro(self):
        print('*This is an initial version of 2048 by Python*')
        print("*Use wasd to move the cubes*")
        print('*Author: Yu*')
        print('*Date: 2021.08.01*\n')

    def get_response(self):
        print('*'*40)
        self.response = input('The next step / quit: ')
        print('*'*40)

    def display_score(self):
        self.score = int(self.value_matrix.sum())
        print('The Score is: ', self.score)

    def get_maximum(self):
        max = 0
        for i in range(self.row):
            for j in range(self.col):
                if self.value_matrix[i,j] > max:
                    max = self.value_matrix[i,j]
        return max

    def print_color(self, color, content):
        start_line = '\033[1;' + color + 'm '
        end_line = '\033[0m'
        return start_line + content + end_line

    def judge_full(self):
        count_empty = 0
        for i in range(self.row):
            for j in range(self.col):
                if self.value_matrix[i,j] == 0:
                    count_empty += 1
        return count_empty

    def judge_failure(self):
        judge1 = self.get_maximum() < 2048 and self.judge_full() == 0
        judge2 = 0
        for i in range(self.row):
            for j in range(self.col):
                try:
                    if self.value_matrix[i,j] == self.value_matrix[i-1,j]:
                        judge2 += 1
                except IndexError:
                    pass
                try:
                    if self.value_matrix[i,j] == self.value_matrix[i+1,j]:
                        judge2 += 1
                except IndexError:
                    pass
                try:
                    if self.value_matrix[i,j] == self.value_matrix[i,j-1]:
                        judge2 += 1
                except IndexError:
                    pass
                try:
                    if self.value_matrix[i,j] == self.value_matrix[i,j+1]:
                        judge2 += 1
                except IndexError:
                    pass
        if judge1 and (judge2 == 0):
            self.alive = False

    def update_status_matrix(self):
        for i in range(self.row):
            for j in range(self.col):
                if self.value_matrix[i,j] == 0:
                    self.status_matrix[i,j] = 0
                else:
                    self.status_matrix[i,j] = 1

    def go_to_right(self):
        for i in range(self.row):
            for _ in range(self.col - 1):
                for j in range(self.col - 1, 0, -1):
                    if self.value_matrix[i, j] == 0:
                        self.value_matrix[i, j], self.value_matrix[i, j - 1] = self.value_matrix[i, j - 1], \
                                                                               self.value_matrix[i, j]
            for j in range(self.col-1, 0, -1):
                if self.value_matrix[i, j] == self.value_matrix[i, j - 1]:
                    self.value_matrix[i, j] += self.value_matrix[i, j - 1]
                    self.value_matrix[i, j - 1] = 0
            for _ in range(self.col - 1):
                for j in range(self.col - 1, 0, -1):
                    if self.value_matrix[i, j] == 0:
                        self.value_matrix[i, j], self.value_matrix[i, j - 1] = self.value_matrix[i, j - 1], \
                                                                               self.value_matrix[i, j]
    def go_to_bottom(self):
        for j in range(self.col):
            for _ in range(self.col - 1):
                for i in range(self.row - 1, 0, -1):
                    if self.value_matrix[i, j] == 0:
                        self.value_matrix[i - 1, j], self.value_matrix[i, j] = self.value_matrix[i, j], \
                                                                               self.value_matrix[i - 1, j]
            for i in range(self.row-1, 0, -1):
                if self.value_matrix[i, j] == self.value_matrix[i - 1, j]:
                    self.value_matrix[i, j] += self.value_matrix[i - 1, j]
                    self.value_matrix[i - 1, j] = 0
            for _ in range(self.col - 1):
                for i in range(self.row - 1, 0, -1):
                    if self.value_matrix[i, j] == 0:
                        self.value_matrix[i - 1, j], self.value_matrix[i, j] = self.value_matrix[i, j], \
                                                                               self.value_matrix[i - 1, j]
    def go_to_left(self):
        for i in range(self.row):
            for _ in range(self.col - 1):
                for j in range(self.col-1):
                    if self.value_matrix[i,j] == 0:
                        self.value_matrix[i, j], self.value_matrix[i, j + 1] = self.value_matrix[i, j + 1], \
                                                                               self.value_matrix[i, j]
            for j in range(self.col-1):
                if self.value_matrix[i, j] == self.value_matrix[i, j + 1]:
                    self.value_matrix[i, j] += self.value_matrix[i, j + 1]
                    self.value_matrix[i, j + 1] = 0
            for _ in range(self.col - 1):
                for j in range(self.col-1):
                    if self.value_matrix[i,j] == 0:
                        self.value_matrix[i, j], self.value_matrix[i, j + 1] = self.value_matrix[i, j + 1], \
                                                                               self.value_matrix[i, j]
    def go_to_top(self):
        for j in range(self.col):
            for _ in range(self.row - 1):
                for i in range(self.row-1):
                    if self.value_matrix[i, j] == 0:
                        self.value_matrix[i + 1, j], self.value_matrix[i, j] = self.value_matrix[i, j], \
                                                                               self.value_matrix[i + 1, j]
            for i in range(self.row-1):
                if self.value_matrix[i, j] == self.value_matrix[i + 1, j]:
                    self.value_matrix[i, j] += self.value_matrix[i + 1, j]
                    self.value_matrix[i + 1, j] = 0
            for _ in range(self.row - 1):
                for i in range(self.row-1):
                    if self.value_matrix[i, j] == 0:
                        self.value_matrix[i + 1, j], self.value_matrix[i, j] = self.value_matrix[i, j], \
                                                                               self.value_matrix[i + 1, j]
    def update_random(self):
        count = 0
        left_places = []
        for i in range(self.row):
            for j in range(self.col):
                if self.status_matrix[i,j] == 0:
                    left_places.append(count)
                count += 1
        try:
            random_place = random.choice(left_places)
            count = 0
            for i in range(self.row):
                for j in range(self.col):
                    if count == random_place:
                        self.value_matrix[i,j] = 2
                    count += 1
        except:
            pass

    def display_matrix(self):
        for i in range(self.row):
            print('| \t', end='')
            temp_all = ''
            for j in range(self.col):
                number = int(self.value_matrix[i,j])
                if number == 0:
                    temp_len = ' \t| '
                    temp = ' \t| '
                else:
                    temp_len = str(number) + '\t| '
                    temp = self.print_color('31',str(number)) + '\t| '
                temp_all += temp_len
                print(temp,end='\t')
            print('\n','-'*2*len(temp_all))

    def execute(self):
        flag = True
        self.update_random()
        self.display_score()
        self.display_matrix()
        while self.alive:
            self.get_response()
            if self.response == 'w':
                self.go_to_top()
            elif self.response == 'd':
                self.go_to_right()
            elif self.response == 'a':
                self.go_to_left()
            elif self.response == 's':
                self.go_to_bottom()
            elif self.response == 'quit':
                break
            else:
                print('Wrong Order!!!')
                continue
            self.update_random()
            self.display_score()
            self.display_matrix()
            self.update_status_matrix()
            self.judge_failure()
            if self.value_matrix.max() >= 2048 and flag == True:
                flag = False
                hint = input('You have win! Continue?(n to exit)')
                if hint == 'y':
                    pass
                elif hint == 'n':
                    break
        if self.response == 'quit':
            print('Quit!')
        else:
            print('Failure!')

    def run(self):
        self.give_intro()
        try:
            self.execute()
        except KeyboardInterrupt:
            print('\n\nGame Over!')


if __name__ == '__main__':
    game = Game()
    game.run()

对于各个方法的具体说明:

1、__init__方法:初始化行列数、用户分数、显示数组、状态数组、总分等

2、give_intro方法:给出关于游戏的相关介绍

3、get_response方法:接收每次用户的输入内容,wasd分别对应上左下右四种操作,输入quit会直接退出游戏

4、display_score方法:每次用户输入后,返回当前的总得分

5、get_maximum方法:返回当前显示数组中的最大值,判断用户是否达到了2048的目标

6、print_color方法:设置在pycharm中显示的颜色

7、judge_full方法:判断当前显示数组是否已经全部非空

8、judge_failure方法:判断当前是否达到游戏失败的结果

9、update_status_matrix方法:更新当前的状态数组

10、go_to_XX方法:执行对于用户上下左右的操作反馈的计算

11、update_random方法:每次在一个随机位置产生一个新的数“2”

12、display_matrix方法:在IDE中打印2048的显示数组

13、execute方法:对上面所有方法的执行、执行顺序的封装

14、run方法:对于整个类的操作执行

15、主函数

由于笔者技艺不精,因此在代码中有大量的冗余与暴力计算的内容,这些都是可以在日后加以改进的,如有错误或修改建议敬请评论说明,谢谢!

这篇关于Python | 实现在Pycharm IDE环境下的2048小游戏的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!