python制作图形界面的2048游戏, 基于tkinter


Posted in Python onApril 06, 2021

2048游戏输出

python制作图形界面的2048游戏, 基于tkinter

项目先决条件

前提条件如下:

1. Python
2. Tkinter

创建main.py

代码:

from tkinter import *
from tkinter import messagebox
import random

class Board:
 bg_color={

 '2': '#eee4da',
 '4': '#ede0c8',
 '8': '#edc850',
 '16': '#edc53f',
 '32': '#f67c5f',
 '64': '#f65e3b',
 '128': '#edcf72',
 '256': '#edcc61',
 '512': '#f2b179',
 '1024': '#f59563',
 '2048': '#edc22e',
 }
 color={
  '2': '#776e65',
 '4': '#f9f6f2',
 '8': '#f9f6f2',
 '16': '#f9f6f2',
 '32': '#f9f6f2',
 '64': '#f9f6f2',
 '128': '#f9f6f2',
 '256': '#f9f6f2',
 '512': '#776e65',
 '1024': '#f9f6f2',
 '2048': '#f9f6f2',
 }

 def __init__(self):
 self.window=Tk()
 self.window.title('ProjectGurukul 2048 Game')
 self.gameArea=Frame(self.window,bg= 'azure3')
 self.board=[]
 self.gridCell=[[0]*4 for i in range(4)]
 self.compress=False
 self.merge=False
 self.moved=False
 self.score=0

 for i in range(4):
  rows=[]
  for j in range(4):
  l=Label(self.gameArea,text='',bg='azure4',
  font=('arial',22,'bold'),width=4,height=2)
  l.grid(row=i,column=j,padx=7,pady=7)

  rows.append(l)
  self.board.append(rows)
 self.gameArea.grid()

 def reverse(self):
 for ind in range(4):
  i=0
  j=3
  while(i<j):
  self.gridCell[ind][i],self.gridCell[ind][j]=self.gridCell[ind][j],self.gridCell[ind][i]
  i+=1
  j-=1

 def transpose(self):
 self.gridCell=[list(t)for t in zip(*self.gridCell)]

 def compressGrid(self):
 self.compress=False
 temp=[[0] *4 for i in range(4)]
 for i in range(4):
  cnt=0
  for j in range(4):
  if self.gridCell[i][j]!=0:
   temp[i][cnt]=self.gridCell[i][j]
   if cnt!=j:
   self.compress=True
   cnt+=1
 self.gridCell=temp

 def mergeGrid(self):
 self.merge=False
 for i in range(4):
  for j in range(4 - 1):
  if self.gridCell[i][j] == self.gridCell[i][j + 1] and self.gridCell[i][j] != 0:
   self.gridCell[i][j] *= 2
   self.gridCell[i][j + 1] = 0
   self.score += self.gridCell[i][j]
   self.merge = True

 def random_cell(self):
 cells=[]
 for i in range(4):
  for j in range(4):
  if self.gridCell[i][j] == 0:
   cells.append((i, j))
 curr=random.choice(cells)
 i=curr[0]
 j=curr[1]
 self.gridCell[i][j]=2
 
 def can_merge(self):
 for i in range(4):
  for j in range(3):
  if self.gridCell[i][j] == self.gridCell[i][j+1]:
   return True
 
 for i in range(3):
  for j in range(4):
  if self.gridCell[i+1][j] == self.gridCell[i][j]:
   return True
 return False

 def paintGrid(self):
 for i in range(4):
  for j in range(4):
  if self.gridCell[i][j]==0:
   self.board[i][j].config(text='',bg='azure4')
  else:
   self.board[i][j].config(text=str(self.gridCell[i][j]),
   bg=self.bg_color.get(str(self.gridCell[i][j])),
   fg=self.color.get(str(self.gridCell[i][j])))


class Game:
 def __init__(self,gamepanel):
 self.gamepanel=gamepanel
 self.end=False
 self.won=False

 def start(self):
 self.gamepanel.random_cell()
 self.gamepanel.random_cell()
 self.gamepanel.paintGrid()
 self.gamepanel.window.bind('<Key>', self.link_keys)
 self.gamepanel.window.mainloop()
 
 def link_keys(self,event):
 if self.end or self.won:
  return

 self.gamepanel.compress = False
 self.gamepanel.merge = False
 self.gamepanel.moved = False

 presed_key=event.keysym

 if presed_key=='Up':
  self.gamepanel.transpose()
  self.gamepanel.compressGrid()
  self.gamepanel.mergeGrid()
  self.gamepanel.moved = self.gamepanel.compress or self.gamepanel.merge
  self.gamepanel.compressGrid()
  self.gamepanel.transpose()

 elif presed_key=='Down':
  self.gamepanel.transpose()
  self.gamepanel.reverse()
  self.gamepanel.compressGrid()
  self.gamepanel.mergeGrid()
  self.gamepanel.moved = self.gamepanel.compress or self.gamepanel.merge
  self.gamepanel.compressGrid()
  self.gamepanel.reverse()
  self.gamepanel.transpose()

 elif presed_key=='Left':
  self.gamepanel.compressGrid()
  self.gamepanel.mergeGrid()
  self.gamepanel.moved = self.gamepanel.compress or self.gamepanel.merge
  self.gamepanel.compressGrid()

 elif presed_key=='Right':
  self.gamepanel.reverse()
  self.gamepanel.compressGrid()
  self.gamepanel.mergeGrid()
  self.gamepanel.moved = self.gamepanel.compress or self.gamepanel.merge
  self.gamepanel.compressGrid()
  self.gamepanel.reverse()
 else:
  pass

 self.gamepanel.paintGrid()
 print(self.gamepanel.score)

 flag=0
 for i in range(4):
  for j in range(4):
  if(self.gamepanel.gridCell[i][j]==2048):
   flag=1
   break

 if(flag==1): #found 2048
  self.won=True
  messagebox.showinfo('2048', message='You Wonnn!!')
  print("won")
  return

 for i in range(4):
  for j in range(4):
  if self.gamepanel.gridCell[i][j]==0:
   flag=1
   break

 if not (flag or self.gamepanel.can_merge()):
  self.end=True
  messagebox.showinfo('2048','Game Over!!!')
  print("Over")

 if self.gamepanel.moved:
  self.gamepanel.random_cell()
 
 self.gamepanel.paintGrid()
 

gamepanel =Board()
game2048 = Game( gamepanel)
game2048.start()

解释:

我们在代码中定义了两个类:

1.Board:

变量:

  • Bg_color:这是一个字典,用于存储每个单元格的背景色。
  • Color:这是一个字典,用于存储每个单元的前景色。
  • Window:它是tkinter的主要窗口。
  • gameArea:这是一个tkinter框架小部件。
  • gridCell:这是一个4×4整数矩阵,存储所有单元格的实际整数值。
  • Board:这是tkinter标签小部件的4×4网格,它在tkinter窗口上显示单元格的值。它还用于根据其gridCell值配置该单元格的背景和前景。
  • Score:它存储玩家的当前分数。

其余只是标志变量。

功能:

  • __init __(self):这是构造函数。它使用适当的默认值初始化所有变量,例如gridCell的默认值为“ 0”,移动,合并的默认值为False,等等。
  • Reverse:反转gridCell矩阵。
  • Transpose:它使用zip函数并进行gridCell矩阵的转置。
  • CompressGrid:它将所有非空单元格向左移动,因此可以轻松完成合并。
  • mergeGrid:如果两个相邻单元格具有相同的gridCell值,则将它们的gridCell值相加。
  • Random_cell:首先将所有空单元格存储在列表中,然后从创建的列表中选择一个随机单元格并使其gridCell值2
  • Can_merge:返回一个布尔值,表示我们可以合并任意两个单元格。当且仅当两个单元格具有相同的gridCell值时,我们才可以合并它们。
  • paintGrid:将前景和背景色分配给4×4网格中与其gridCell值相对应的每个单元。

2.game:

此类没有很多变量,只有一些布尔变量指示游戏状态。

功能:

  • __init __(self):这是构造函数。它使用适当的默认值初始化所有变量。
  • 开始:调用random_cell两次,将'2'赋给两个随机单元格的gridCell值,然后绘制网格,然后,调用link_keys链接上,下,左和右键。
  • Link_keys:首先,它检查游戏是赢还是输,如果是,则不执行任何操作执行return语句。否则,它将继续执行。

方法:

  • 对于左滑动,我们将先压缩然后合并gridCell矩阵,然后如果compress或merge为true(指示矩阵的值受前两个函数影响),那么我们需要再次压缩网格。
  • 对于上移,我们将进行移调,然后向左轻扫,然后再次进行移调以返回原始顺序。
  • 向下移动与向上移动相同,但是我们需要反转矩阵。
  • 同样,向右与向左+向后移动相同。
  • 每次操作后,我们需要检查游戏状态,如果所有单元都被占用,我们甚至不能合并任何两个单元,即没有动作可以改变矩阵的状态,则游戏结束了。

如果任何一个单元格值都达到2048,则玩家将获胜,并且屏幕上会闪烁一个消息框,宣布获胜者。

总结

我们已经成功地用python开发了流行的2048游戏。开发游戏而不是玩别人的游戏非常有趣,现在我们将玩自己开发的游戏。

以上就是python基于tkinter制作图形界面的2048游戏的详细内容,更多关于python 图形界面2048游戏的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
使用Python开发windows GUI程序入门实例
Oct 23 Python
在Python中封装GObject模块进行图形化程序编程的教程
Apr 14 Python
一步步解析Python斗牛游戏的概率
Feb 12 Python
全面了解Python的getattr(),setattr(),delattr(),hasattr()
Jun 14 Python
python学习笔记--将python源文件打包成exe文件(pyinstaller)
May 26 Python
scrapy-redis源码分析之发送POST请求详解
May 15 Python
opencv设置采集视频分辨率方式
Dec 10 Python
Python实现动态循环输出文字功能
May 07 Python
python爬虫使用正则爬取网站的实现
Aug 03 Python
Python urlopen()参数代码示例解析
Dec 10 Python
python中的列表和元组区别分析
Dec 30 Python
Python实现生活常识解答机器人
Jun 28 Python
python第三方网页解析器 lxml 扩展库与 xpath 的使用方法
Apr 06 #Python
python删除csv文件的行列
Apr 06 #Python
python使用pygame创建精灵Sprite
python 逐步回归算法
python 通过使用Yolact训练数据集
python生成随机数、随机字符、随机字符串
Apr 06 #Python
Django项目配置Memcached和Redis, 缓存选择哪个更有优势
Apr 06 #Python
You might like
php计算一个文件大小的方法
2015/03/30 PHP
Laravel数据库读写分离配置的方法
2019/10/13 PHP
JS 用6N±1法求素数 实例教程
2009/10/20 Javascript
非阻塞动态加载javascript广告实现代码
2010/11/17 Javascript
提交按钮的name='submit'引起的js失效问题及原因
2015/02/25 Javascript
js时钟翻牌效果实现代码分享
2020/07/31 Javascript
基于Jquery插件Uploadify实现实时显示进度条上传图片
2020/03/26 Javascript
小程序:授权、登录、session_key、unionId的详解
2019/05/15 Javascript
基于javascript实现贪吃蛇经典小游戏
2020/04/10 Javascript
浅谈使用nodejs搭建web服务器的过程
2020/07/20 NodeJs
简洁的十分钟Python入门教程
2015/04/03 Python
python读写ini配置文件方法实例分析
2015/06/30 Python
python2.7 mayavi 安装图文教程(推荐)
2017/06/22 Python
详解python基础之while循环及if判断
2017/08/24 Python
复化梯形求积分实例——用Python进行数值计算
2019/11/20 Python
代码总结Python2 和 Python3 字符串的区别
2020/01/28 Python
使用 Python 读取电子表格中的数据实例详解
2020/04/17 Python
Python urllib2运行过程原理解析
2020/06/04 Python
Python偏函数Partial function使用方法实例详解
2020/06/17 Python
Python通过getattr函数获取对象的属性值
2020/10/16 Python
在HTML5 Canvas中放入图片和保存为图片的方法
2014/05/03 HTML / CSS
friso美素佳儿官方海外旗舰店:荷兰原产原罐
2017/07/03 全球购物
德国领先的大尺码和超大尺码男装在线零售商:Bigtex
2019/06/22 全球购物
纽约和芝加哥当天送花:Ode à la Rose
2019/07/05 全球购物
Yahoo-PHP面试题3
2012/01/14 面试题
C#面试题
2016/05/06 面试题
婚礼主持词
2014/03/13 职场文书
大学生简历求职信
2014/06/24 职场文书
学习“七一”讲话精神体会
2014/07/08 职场文书
2014离婚协议书范文两篇
2014/09/15 职场文书
医院护士工作检讨书
2014/10/26 职场文书
2015年林业工作总结
2015/05/14 职场文书
教务处教学工作总结
2015/08/10 职场文书
体育部部长竞选稿
2015/11/21 职场文书
再见,2019我们不负使命;你好,2020我们砥砺前行
2020/01/03 职场文书
Python数据可视化之绘制柱状图和条形图
2021/05/25 Python