ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2021-09-12 12:58:17  阅读:254  来源: 互联网

标签:matrix Python self value range 小游戏 2048 col row


针对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、主函数

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

标签:matrix,Python,self,value,range,小游戏,2048,col,row
来源: https://blog.csdn.net/CharlesChan_1998/article/details/120249371

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有