Tkinter模块GUI界面化编程实战(三)——2048小游戏(含详解及完整源码、完整程序下载链接)

简介: Tkinter模块GUI界面化编程实战(三)——2048小游戏(含详解及完整源码、完整程序下载链接)

【前两期我都用了ttkbootstrap模块进行了界面美化,但总用别人写好的模块去美化GUI界面让我觉得心里不舒服,而且这个模块要自己pip安装,很麻烦,后续我就不用了】

Tkinter模块编写一个2048小游戏

【先来看看效果图】

【要注意哦,鼠标移到这个按钮上,按钮会变颜色哦(事件绑定)】

【再来看看源代码】

【这个可以直接复制代码并运行,没有需pip的模块】

from tkinter import *
from random import *
from tkinter.messagebox import *
game = Tk()#基本框架
game.title('Game-2048')
game.geometry('305x205+500+250')
game.resizable(0,0)
def base():
    numdict = {1:{},2:{},3:{},4:{}}
    for key in numdict.keys():numdict[key] = {1:'',2:'',3:'',4:''}
    while 1:
        x1,x2,y1,y2 = randint(1,4),randint(1,4),randint(1,4),randint(1,4)
        if x1 != x2 or y1 !=y2:numdict[x1][y1],numdict[x2][y2] = 2,2;break
    frame  = Frame(game,bg='#BBADA0').place(width=205,height=205)
    frame2 = Frame(game,bg='orange' ).place(width=100,height=205,x=205)
    frame3 = Frame(frame2,bg='#FAF8EF' ).place(x=210,y=5,width=90,height=195)
    (score := StringVar()).set('Score\n\n0');(score_value := StringVar()).set('0')
    Label(frame3,textvariable=score,font=('consolas',15),bg='yellow').place(x=215,y=10,width=80,height=100)
    helpbutton = Button(frame2,text='Help',font=('consolas',15),bd=0,bg='lightgreen',command=lambda: gamehelp());helpbutton.place(x=215,y=160,width=80,height=30)
    playbutton = Button(frame2,text='Play',font=('consolas',15),bd=0,bg='lightgreen',command=lambda:gamestart());playbutton.place(x=215,y=120,width=80,height=30)
    n14 = StringVar();n24 = StringVar();n34 = StringVar();n44 = StringVar()
    n13 = StringVar();n23 = StringVar();n33 = StringVar();n43 = StringVar()
    n12 = StringVar();n22 = StringVar();n32 = StringVar();n42 = StringVar()
    n11 = StringVar();n21 = StringVar();n31 = StringVar();n41 = StringVar()
    for sy in [5,55,105,155]:#放置格子
        for sx,i in zip([5,55,105,155],[n14,n24,n34,n44,n13,n23,n33,n43,n12,n22,n32,n42,n11,n21,n31,n41][4*(sy-5)//50:4*(sy+45)//50]):
            Label(frame,bg='#CDC1B4',textvariable=i,font=('consolas',15)).place(width=45,height=45,y=sy,x=sx)
    def initialization():#初始化
        for x in range(1,5):
            for y,i in zip(range(1,5),[n11,n12,n13,n14,n21,n22,n23,n24,n31,n32,n33,n34,n41,n42,n43,n44][4*(x-1):4*x]):i.set(numdict[x][y])
    def gamewin():#游戏胜利
        for value in numdict.values():
            if 2048 in value:
                frame_win = Frame(game,bg='yellow').place(width=305,height=205)
                Label(frame_win,text='You Win!',font=('consolas',30),fg='red',bg='yellow').place(width=305,height=60)
                Button(frame_win,bd=0,bg='lightgreen',font=('consolas',15),text='Again!',command=lambda:base()).place(width=80,height=30,y=150,x=45)
                Button(frame_win,bd=0,bg='lightgreen',font=('consolas',15),text='Quit!',command=lambda:quit()).place(width=80,height=30,y=150,x=180)
                Label(frame,font=('consolas',15),text='You have got to\n2048!',bg='yellow').place(width=205,height=60,y=60,x=50)
        game.after(100,gamewin)
    def gameover():#游戏结束
        frame_over = Frame(game,bg='yellow').place(width=305,height=205)
        Label(frame_over,text='Game Over!',font=('consolas',30),fg='red',bg='yellow').place(width=305,height=60)
        Button(frame_over,bd=0,bg='lightgreen',font=('consolas',15),text='Again!',command=lambda:base()).place(width=80,height=30,y=150,x=45)
        Button(frame_over,bd=0,bg='lightgreen',font=('consolas',15),text='Quit!',command=lambda:quit()).place(width=80,height=30,y=150,x=180)
        Label(frame,font=('consolas',50),textvariable=score_value,bg='yellow').place(width=205,height=60,y=60,x=50)
    def move(way,count=0):#操作函数
        if way in ['w','s','a','d']:#判断是否为正确的操作
            if way == 'w':
                for x in range(1,5):
                    numdict[x][5] = 0
                    for y in range(1,5):
                        if numdict[x][y] == numdict[x][y+1] and numdict[x][y] != '':numdict[x][y] = '';numdict[x][y+1] *= 2
                        elif numdict[x][y] != '' and numdict[x][y+1] == '':numdict[x][y],numdict[x][y+1]=numdict[x][y+1],numdict[x][y]
                    del numdict[x][5]
            if way == 's':
                for x in range(1,5):
                    numdict[x][0] = 0
                    for y in range(4,0,-1):
                        if numdict[x][y] == numdict[x][y-1] and numdict[x][y] != '':numdict[x][y] = '';numdict[x][y-1] *= 2
                        elif numdict[x][y] != '' and numdict[x][y-1] == '':numdict[x][y],numdict[x][y-1]=numdict[x][y-1],numdict[x][y]
                    del numdict[x][0]
            if way == 'd':
                numdict[5] = {1:0,2:0,3:0,4:0}
                for y in range(1,5):
                    for x in range(1,5):
                        if numdict[x][y] == numdict[x+1][y] and numdict[x][y] != '':numdict[x][y] = '';numdict[x+1][y] *= 2
                        elif numdict[x][y] != '' and numdict[x+1][y] == '':numdict[x][y],numdict[x+1][y]=numdict[x+1][y],numdict[x][y]
                del numdict[5]
            if way == 'a':
                numdict[0] = {1:0,2:0,3:0,4:0}
                for y in range(1,5):
                    for x in range(4,0,-1):
                        if numdict[x][y] == numdict[x-1][y] and numdict[x][y] != '':numdict[x][y] = '';numdict[x-1][y] *= 2
                        elif numdict[x][y] != '' and numdict[x-1][y] == '':numdict[x][y],numdict[x-1][y]=numdict[x-1][y],numdict[x][y]
                del numdict[0]
            for x in range(1,5):
                for y,i in zip(range(1,5),[n11,n12,n13,n14,n21,n22,n23,n24,n31,n32,n33,n34,n41,n42,n43,n44][4*(x-1):4*x]):
                    i.set(numdict[x][y])
                    if numdict[x][y] == '':count = 1
            if count == 0:gameover();return None#决定是否结束游戏
            while 1:#随机再产生一个数
                x,y = randint(1,4),randint(1,4)
                if numdict[x][y] == '':numdict[x][y] = choice([2,4]);break
            [n11,n12,n13,n14,n21,n22,n23,n24,n31,n32,n33,n34,n41,n42,n43,n44][4*x+y-5].set(numdict[x][y])
    def gamehelp():showinfo(title='Help of 2048',message='Press "w" to up!\nPress "s"  to down!\nPress "d" to right!\nPress "a"  to left!')#游戏帮助
    def scorevalue(value=0):#计分板
        for x in range(1,5):
            for y in range(1,5):
                if numdict[x][y] != '':value += numdict[x][y]
        score.set('Score\n\n%s'%value);score_value.set(str(value));game.after(10,scorevalue)
    def gamestart():#游戏开始
        game.bind_all('<Any-KeyPress>',lambda event:move(event.char))#键盘关联
        initialization()#初始化
        scorevalue()#开始计分
        gamewin()#检测胜利
    def enter(event):event.widget['bg']='springgreen'
    def leave(event):event.widget['bg']='lightgreen'
    for i in [helpbutton,playbutton]:
        i.bind('<Enter>',lambda event:enter(event));i.bind('<Leave>',lambda event:leave(event))
base()
game.mainloop()

说明一下,这个2048的游戏规则可能和我们平时玩的不太一样,因为博主在编写这个之前并没有充分地了解游戏规则(ToT),游戏规则就是(你玩了就知道了),用‘w’、‘s’、‘a’、‘d’几个键去控制,祝你好运!

目录
相关文章
|
网络架构 数据格式
网络通信原理系统的认知(NEBASE第十四课)(二)
网络通信原理系统的认知(NEBASE第十四课)(二)
437 0
|
调度
Magisk模块:Uperf调度模式切换器
Magisk模块:Uperf调度模式切换器
2629 0
|
10月前
|
存储 算法
基于HMM隐马尔可夫模型的金融数据预测算法matlab仿真
本项目基于HMM模型实现金融数据预测,包括模型训练与预测两部分。在MATLAB2022A上运行,通过计算状态转移和观测概率预测未来值,并绘制了预测值、真实值及预测误差的对比图。HMM模型适用于金融市场的时间序列分析,能够有效捕捉隐藏状态及其转换规律,为金融预测提供有力工具。
|
11月前
|
数据采集 Java 测试技术
精准测试如何落地
在快速迭代的软件开发环境中,精准测试作为一种高效、针对性的测试方法,正逐步成为企业的首选。本文探讨了精准测试的落地方法、对质量指标的影响、数据统计与跟踪度量、提高投入产出收益率的策略及卡点数据的具体内容。通过优化测试用例、代码关联、技术融合及流程优化,精准测试能够显著提升软件质量和测试效率。
|
前端开发 JavaScript 搜索推荐
React 中服务端渲染和客户端渲染的区别
【8月更文挑战第31天】
281 0
|
Prometheus 监控 Cloud Native
实时计算 Flink版产品使用合集之将CURRENT_TIMESTAMP转换为长整型的数据(即毫秒数)如何解决
实时计算Flink版作为一种强大的流处理和批处理统一的计算框架,广泛应用于各种需要实时数据处理和分析的场景。实时计算Flink版通常结合SQL接口、DataStream API、以及与上下游数据源和存储系统的丰富连接器,提供了一套全面的解决方案,以应对各种实时计算需求。其低延迟、高吞吐、容错性强的特点,使其成为众多企业和组织实时数据处理首选的技术平台。以下是实时计算Flink版的一些典型使用合集。
203 3
|
前端开发 索引 Python
Tkinter模块GUI图形化编程实战(八)——中国象棋(含超详解及完整源码、完整程序免费下载链接)
Tkinter模块GUI图形化编程实战(八)——中国象棋(含超详解及完整源码、完整程序免费下载链接)
377 0
|
小程序 Python
Tkinter模块GUI界面化编程实战(四)——随机点名小程序(含详解及完整源码、完整程序下载链接)
Tkinter模块GUI界面化编程实战(四)——随机点名小程序(含详解及完整源码、完整程序下载链接)
399 0
Tkinter模块GUI界面化编程实战(四)——随机点名小程序(含详解及完整源码、完整程序下载链接)
|
前端开发 Python
Tkinter模块GUI界面化编程实战(六)——超级游戏盒子(含超详解及完整源码、完整程序免费下载链接)
Tkinter模块GUI界面化编程实战(六)——超级游戏盒子(含超详解及完整源码、完整程序免费下载链接)
450 0
|
Python 容器
Python Tkinter教程(一)——tkinter编程基本步骤、窗口基本属性及Toplevel控件的使用
Python Tkinter教程(一)——tkinter编程基本步骤、窗口基本属性及Toplevel控件的使用
483 1