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

2048游戏输出

项目先决条件

前提条件如下:

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游戏的资料请关注我们其它相关文章!

(0)

相关推荐

  • Python爬虫+Tkinter制作一个翻译软件的示例

    今天咱们用Python爬虫和Tkinter界面来做一个翻译软件. 一.运行效果 软件实现功能:当我们输入英文或中文时,程序即可打印出来对应的译文,如图: 二.实现方法 1. 爬虫部分 实现一键翻译最简单的方式就是爬虫,我们只需将要翻译的内容传入,然后将翻译的结果爬取下来呈现给用户即可.在本文中,我们选择的网站是有道翻译. 下图这个界面,你在左边输入文字,那么浏览器会把你输入的信息传输给服务器.再在右侧返回对应翻译结果.这就是一个典型的Post操作. 由于之前我们的爬取都是采用的Get方式来获取数

  • Python tkinter实现日期选择器

    如何利用Python的tkinter模块实现日期选择器,根据我在网上的搜索情况,这一块一直是一个盲点.虽然也有接近的答案,并没有真正实用的,我经过几天的探索,终于摸索出一套可用的,分享给大家. 首先,定义一个类,叫Calendar,这个是搬运来的. # -*- coding: utf-8 -*- import calendar import tkinter as tk import tkinter.font as tkFont from tkinter import ttk datetime =

  • Python爬虫+tkinter界面实现历史天气查询的思路详解

    今天给大家分享用Python 爬虫+tkinter界面来实现历史天气查询. 一.实现效果 运行效果 运行效果如下: 二.基本思路 导入用到的库 import requests from lxml import etree import re import tkinter as tk from PIL import Image, ImageTk from xpinyin import Pinyin 1. 爬虫部分 目标url:https://lishi.tianqi.com/ 该网站提供了全国34

  • python基于tkinter制作无损音乐下载工具(附源码)

    继续写GUI,本次依然使用Tkinter设计一款图形界面,使用Tkinter做一款音乐下载软件,听起来听平常的,但是我这款软件能够下载 无损音乐下载软件,听起来不错吧,Let`s go! 一.准备工作 python Tkinter 二.预览 1.搜索 2.下载 3.结果 无损音乐就这样下载完了. 三.详细设计 这里仅展示我设计的整体思路. 四.源代码 4.1 Music_Search-v1.0.py from tkinter import * from tkinter import ttk fr

  • python使用tkinter实现屏幕中间倒计时

    本文实例为大家分享了python实现屏幕中间倒计时的具体代码,供大家参考,具体内容如下 先看下效果图: 代码: import time from tkinter import Tk,Label class TimeShow():#实现倒计时 def __init__(self,time_show=5): self.timeShowWin=Tk() self.timeShowWin.overrideredirect(True) self.timeShowWin.attributes('-alpha

  • Python使用tkinter实现小时钟效果

    本文实例为大家分享了Python使用tkinter实现小时钟效果的具体代码,供大家参考,具体内容如下 自己又调试了一下,分享一下 # coding:utf-8 from tkinter import * import math,time def points(): for i in range(1,13): x = 200 + 130*math.sin(2*math.pi*i/12) y = 200 - 130*math.cos(2*math.pi*i/12) canvas.create_tex

  • 使用python tkinter开发一个爬取B站直播弹幕工具的实现代码

    项目地址 https://github.com/jonssonyan... 开发工具 python 3.7.9 pycharm 2019.3.5 代码 import threading import time import tkinter.simpledialog from tkinter import END, simpledialog, messagebox import requests class Danmu(): def __init__(self, room_id): # 弹幕url

  • Python使用tkinter制作在线翻译软件

    tkinter的功能是如此强大,竟然还能做翻译软件.当然是在线的,我发现有一个quicktranslate模块,可以提供在线翻译功能,相当于提供了一个翻译的接口,利用它就可以制作在线翻译软件了.下面是代码,分享给大家. 注意要首先 pip install quicktranslate #-*- coding:utf-8 -*- import tkinter as tk #使用Tkinter前需要先导入 from tkinter import messagebox,ttk import datet

  • python tkinter模块的简单使用

    由于一些小原因,被迫开始了tkinter一次实战演练.在此做一些记录,总结以及给自己留一些轮子哈哈哈哈哈哈 tkinter 是 Python 的一个GUI库,本次实战完全使用tkinter,不牵扯任何其他第三方库的使用. 1.任务要求 画一个具有上传病患信息以及图片功能的用户界面 2.简单设计 由于时间紧迫且只要求可视化,背后没有必要太过精细,所以简单设计思路是,利用下拉列表实现病患信息的填写,用text显示选择图片的路径. 表面上的组件包括:两个Button:选择目录 SELECT THE D

  • python tkinter实现下载进度条及抖音视频去水印原理

    tkinter下载进度条 利用python爬取网站数据进行下载时,显示下载进度 # 设置下载进度条 tk.Label(window, text='下载进度:').place(x=40, y=80) canvas = tk.Canvas(window, width=600, height=16, bg="white") canvas.place(x=20, y=90) # 下载按钮函数 def usr_download(): response = session.get(url_str,

随机推荐