计算机视觉技术 C语言 主从复制 状态模式 后台管理模板 photoshop视频教程全集下载 java设计模式视频 art神经网络 oracle删除字段sql oracle添加索引 vim跳到文件末尾 input边框颜色 idea全局替换 java取绝对值 phpstorm插件 mysqlinsert python编程工具 python怎么下载 java发邮件 java安装环境 java数组添加 java实现栈 java8函数式编程 shell脚本参数 java游戏制作 网站数据分析工具 js闭包的理解 winhex教程 c4d挤压怎么用 羽化快捷键 hdcp是什么 金水疑云 例外被抛出且未被接住 videoview ass转srt android计算器 ps描边怎么用 例程 cad圆形变成多边形 彩虹魔药
当前位置: 首页 > 学习教程  > python

python制作2048游戏

2021/2/6 22:26:38 文章标签: 测试文章如有侵权请发送至邮箱809451989@qq.com投诉后文章立即删除

2048前言开始献上代码代码剖析项目github作者前言 开始 献上代码 from tkinter.messagebox import * from pygame.locals import * from random import * import tkinter as tk import pygame base tk.Tk() base.geometry(0x0) base.resizable(False,False) pygame.init() …

2048

  • 前言
  • 开始
      • 献上代码
      • 代码剖析
      • 项目github
            • 作者

前言

开始

献上代码

from tkinter.messagebox import *
from pygame.locals import *
from random import *
import tkinter as tk
import pygame
base = tk.Tk()
base.geometry('0x0')
base.resizable(False,False)
pygame.init()
def show2048(surf,vals):
    font = pygame.font.Font('songti SC.TTF',100)
    for i in range(len(vals)):
        for j in range(len(vals[i])):
            if (vals[i][j] == None):
                t = font.render(' ', True, (0,0,0), (255,255,255))
            else:
                t = font.render(str(vals[i][j]), True, (0,0,0),(255,255,255))
                t = pygame.transform.scale(t, (100,100))
                surf.blit(t,(100 * i,100 * j))
def gen_val(vals):
    x = randint(0, 3)
    y = randint(0, 3)
    while(vals[x][y] != None):
        x = randint(0,3)
        y = randint(0,3)
    vals[x][y] = choice((2,4))
def c2r(vals):
    return [[vals[j][i] for j in range(len(vals[i]))] for i in range(len(vals))]
def main():
    scr = pygame.display.set_mode((400,400))
    vals = [[None for j in range(4)] for i in range(4)]
    gen_val(vals)
    while(1):
        pygame.display.update()
        scr.fill((255,255,255))
        show2048(scr,vals)
        if(2048 in [vals[i // 4][i % 4] for i in range(16)]):
            return True
        if(None not in [vals[i // 4][i % 4] for i in range(16)]):
            pygame.display.update()
            return False
        for ev in pygame.event.get():
            if(ev.type == QUIT):
                exit()
            elif(ev.type == KEYDOWN):
                if(ev.key == K_DOWN):
                    for i in range(len(vals)):
                        while(None in vals[i]):
                            vals[i].remove(None)
                        for j in range(len(vals[i])):
                            if(j + 1 >= len(vals[i])):
                                break
                            if(vals[i][j + 1] == vals[i][j]):
                                vals[i][j + 1] *= 2
                                vals[i].pop(j)
                        while(len(vals[i]) < 4):
                            vals[i] = [None] + vals[i]
                    gen_val(vals)
                elif(ev.key == K_UP):
                    for i in range(len(vals)):
                        while (None in vals[i]):
                            vals[i].remove(None)
                        for j in range(1,len(vals[i])):
                            if (j >= len(vals[i])):
                                break
                            if (vals[i][j - 1] == vals[i][j]):
                                vals[i][j - 1] *= 2
                                vals[i].pop(j)
                        while (len(vals[i]) < 4):
                            vals[i] = vals[i] + [None]
                    gen_val(vals)
                elif(ev.key == K_LEFT):
                    a = c2r(vals)
                    for i in range(len(a)):
                        while (None in a[i]):
                            a[i].remove(None)
                        for j in range(1, len(a[i])):
                            if (j >= len(a[i])):
                                break
                            if (a[i][j - 1] == a[i][j]):
                                a[i][j - 1] *= 2
                                a[i].pop(j)
                        while (len(a[i]) < 4):
                            a[i] = a[i] + [None]
                    vals = c2r(a)
                    gen_val(vals)
                elif(ev.key == K_RIGHT):
                    a = c2r(vals)
                    for i in range(len(a)):
                        while (None in a[i]):
                            a[i].remove(None)
                        for j in range(len(a[i])):
                            if (j + 1 >= len(a[i])):
                                break
                            if (a[i][j + 1] == a[i][j]):
                                a[i][j + 1] *= 2
                                a[i].pop(j)
                        while (len(a[i]) < 4):
                            a[i] = [None] + a[i]
                    vals = c2r(a)
                    gen_val(vals)
if(__name__ == '__main__'):
    if(main()):
        showinfo('Congratulations!', 'Congratulations!You\'done it!')
    else:
        showinfo('Failed...', 'You are failed')

代码剖析

from tkinter.messagebox import *
from pygame.locals import *
from random import *
import tkinter as tk
import pygame
base = tk.Tk()
base.geometry('0x0')
base.resizable(False,False)
pygame.init()

导入库并初始化

def show2048(surf,vals):
    font = pygame.font.Font('songti SC.TTF',100)
    for i in range(len(vals)):
        for j in range(len(vals[i])):
            if (vals[i][j] == None):
                t = font.render(' ', True, (0,0,0), (255,255,255))
            else:
                t = font.render(str(vals[i][j]), True, (0,0,0),(255,255,255))
                t = pygame.transform.scale(t, (100,100))
                surf.blit(t,(100 * i,100 * j))

加载2048

def gen_val(vals):
    x = randint(0, 3)
    y = randint(0, 3)
    while(vals[x][y] != None):
        x = randint(0,3)
        y = randint(0,3)
    vals[x][y] = choice((2,4))

在空白位置里随机选一个填成2/4

def c2r(vals):
    return [[vals[j][i] for j in range(len(vals[i]))] for i in range(len(vals))]

将一个矩阵行变列

def main():
    scr = pygame.display.set_mode((400,400))
    vals = [[None for j in range(4)] for i in range(4)]
    gen_val(vals)
    while(1):
        pygame.display.update()
        scr.fill((255,255,255))
        show2048(scr,vals)
        if(2048 in [vals[i // 4][i % 4] for i in range(16)]):
            return True
        if(None not in [vals[i // 4][i % 4] for i in range(16)]):
            pygame.display.update()
            return False
        for ev in pygame.event.get():
            if(ev.type == QUIT):
                exit()
            elif(ev.type == KEYDOWN):
                if(ev.key == K_DOWN):
                    for i in range(len(vals)):
                        while(None in vals[i]):
                            vals[i].remove(None)
                        for j in range(len(vals[i])):
                            if(j + 1 >= len(vals[i])):
                                break
                            if(vals[i][j + 1] == vals[i][j]):
                                vals[i][j + 1] *= 2
                                vals[i].pop(j)
                        while(len(vals[i]) < 4):
                            vals[i] = [None] + vals[i]
                    gen_val(vals)
                elif(ev.key == K_UP):
                    for i in range(len(vals)):
                        while (None in vals[i]):
                            vals[i].remove(None)
                        for j in range(1,len(vals[i])):
                            if (j >= len(vals[i])):
                                break
                            if (vals[i][j - 1] == vals[i][j]):
                                vals[i][j - 1] *= 2
                                vals[i].pop(j)
                        while (len(vals[i]) < 4):
                            vals[i] = vals[i] + [None]
                    gen_val(vals)
                elif(ev.key == K_LEFT):
                    a = c2r(vals)
                    for i in range(len(a)):
                        while (None in a[i]):
                            a[i].remove(None)
                        for j in range(1, len(a[i])):
                            if (j >= len(a[i])):
                                break
                            if (a[i][j - 1] == a[i][j]):
                                a[i][j - 1] *= 2
                                a[i].pop(j)
                        while (len(a[i]) < 4):
                            a[i] = a[i] + [None]
                    vals = c2r(a)
                    gen_val(vals)
                elif(ev.key == K_RIGHT):
                    a = c2r(vals)
                    for i in range(len(a)):
                        while (None in a[i]):
                            a[i].remove(None)
                        for j in range(len(a[i])):
                            if (j + 1 >= len(a[i])):
                                break
                            if (a[i][j + 1] == a[i][j]):
                                a[i][j + 1] *= 2
                                a[i].pop(j)
                        while (len(a[i]) < 4):
                            a[i] = [None] + a[i]
                    vals = c2r(a)
                    gen_val(vals)

这里分开剖析

def main():
    scr = pygame.display.set_mode((400,400))
    vals = [[None for j in range(4)] for i in range(4)]
    gen_val(vals)

初始化变量

  • 窗口对象
  • 棋盘
    并在棋盘中生成一个值
    while(1):
        pygame.display.update()
        scr.fill((255,255,255))
        show2048(scr,vals)
        if(2048 in [vals[i // 4][i % 4] for i in range(16)]):
            return True
        if(None not in [vals[i // 4][i % 4] for i in range(16)]):
            pygame.display.update()
            return False

加载2048并处理如下事件 ↓ \downarrow

  • 如果棋盘里有2048,则游戏胜利
  • 如果棋盘里没有空格,则游戏失败
        for ev in pygame.event.get():
            if(ev.type == QUIT):
                exit()
            elif(ev.type == KEYDOWN):
                if(ev.key == K_DOWN):
                    for i in range(len(vals)):
                        while(None in vals[i]):
                            vals[i].remove(None)
                        for j in range(len(vals[i])):
                            if(j + 1 >= len(vals[i])):
                                break
                            if(vals[i][j + 1] == vals[i][j]):
                                vals[i][j + 1] *= 2
                                vals[i].pop(j)
                        while(len(vals[i]) < 4):
                            vals[i] = [None] + vals[i]
                    gen_val(vals)
                elif(ev.key == K_UP):
                    for i in range(len(vals)):
                        while (None in vals[i]):
                            vals[i].remove(None)
                        for j in range(1,len(vals[i])):
                            if (j >= len(vals[i])):
                                break
                            if (vals[i][j - 1] == vals[i][j]):
                                vals[i][j - 1] *= 2
                                vals[i].pop(j)
                        while (len(vals[i]) < 4):
                            vals[i] = vals[i] + [None]
                    gen_val(vals)
                elif(ev.key == K_LEFT):
                    a = c2r(vals)
                    for i in range(len(a)):
                        while (None in a[i]):
                            a[i].remove(None)
                        for j in range(1, len(a[i])):
                            if (j >= len(a[i])):
                                break
                            if (a[i][j - 1] == a[i][j]):
                                a[i][j - 1] *= 2
                                a[i].pop(j)
                        while (len(a[i]) < 4):
                            a[i] = a[i] + [None]
                    vals = c2r(a)
                    gen_val(vals)
                elif(ev.key == K_RIGHT):
                    a = c2r(vals)
                    for i in range(len(a)):
                        while (None in a[i]):
                            a[i].remove(None)
                        for j in range(len(a[i])):
                            if (j + 1 >= len(a[i])):
                                break
                            if (a[i][j + 1] == a[i][j]):
                                a[i][j + 1] *= 2
                                a[i].pop(j)
                        while (len(a[i]) < 4):
                            a[i] = [None] + a[i]
                    vals = c2r(a)
                    gen_val(vals)

处理事件 ↓ \downarrow

  • 按下(x)退出游戏
  • 按下上箭头整体向上对齐
  • 按下下箭头整体向下对齐
  • 按下左箭头整体向左对齐
  • 按下右箭头整体向右对齐

向下对齐就是把空的位置去掉后进行数的合并,之后补齐。向上对齐同理
向左对齐就是行变列后向上对齐(可以自己画一下图)
向右对齐就是行变列后向下对齐(可以自己画一下图)

if(__name__ == '__main__'):
    if(main()):
        showinfo('Congratulations!', 'Congratulations!You\'done it!')
    else:
        showinfo('Failed...', 'You are failed')

运行并提示输赢

项目github

github传送门


作者

hit-road

拜拜,下课!
回到顶部


本文链接: http://www.dtmao.cc/news_show_2000102.shtml

附件下载

相关教程

    暂无相关的数据...

共有条评论 网友评论

验证码: 看不清楚?