1、过年的时候在手机上下载了2048玩了几天,心血来潮决定用py写一个,刚开始的时候想用QT实现,发现依赖有点大。正好看到graphics.py是基于tkinter做的封装就拿来练手,并借用了CSDN一位朋友封装的model.py(2048逻辑部分)
2、由于是练手的所以不免有写的不好的地方请大家喷的轻点。
先看看演示图片

附上源码:
2048主程
#-*-coding:utf-8-*-
#python3.3.5
from graphics import*
from tkinter.messagebox import askquestion
from tkinter.messagebox import showinfo
import time,random,model,configparser
import GUI_2048 as g
class Application():
'''
初始化应用程序
'''
def __init__(self):
self.matrix = model.init()
self.win = g.init()
self.create_r_2048(self.win)
self.show_matrix(self.matrix)
self.win.master.bind("<Key>", self.bind_key)
while 1:
update()
'''
创建网格上的16个方格、最佳成绩、当前分数
'''
def create_r_2048(self,win):
p = Point(10, 190)
n = 4
self.rt = [0 for row in range(n*n)]
for i in range(n):
for a in range(n):
_p = Point(p.x + 60*i, p.y + 60*a)
self.rt[i+4*a] = g.rectangle_2048(win,_p)
#最佳成绩
self.zjcj = g._text(win,Point(135, 60 + 30),Point(135 + 115, 60 + 30 + 30),self.getMaxScore())
#当前分数
self.dqjf = g._text(win,Point(135, 120 + 30),Point(135 + 115, 120 + 30 + 30),'0')
'''
从配置文件中获取最佳成绩
'''
def getMaxScore(self):
config = configparser.ConfigParser()
config.read('config.ini')
maxScore = config.get("Score", "maxScore")
return maxScore
'''
把最佳成绩写入配置文件
'''
def setMaxScore(self,score):
config = configparser.ConfigParser()
config.optionxform = str
config.read('config.ini')
config.set("Score", "maxScore",str(score))
config.write(open("config.ini", "w"))
'''
初始化数据和界面,在游戏结束后调用
'''
def my_init(self):
maxScore = self.getMaxScore()
if int(maxScore) < model.getScore():
self.setMaxScore(model.getScore())
self.zjcj.setText(model.getScore())
matrix = model.init()
self.dqjf.setText(model.getScore())
return matrix
'''
绑定键盘事件 捕获上下左右和Q键
'''
def bind_key(self, event):
'''
key event
'''
if model.is_over(self.matrix):
if askquestion("GAME OVER","GAME OVER!\nDo you want to init it?") == 'yes':
self.matrix = self.my_init()
self.show_matrix(self.matrix)
return
else:
self.win.close()
else:
if event.keysym.lower() == "q":
self.win.close()
elif event.keysym == "Left":
self.matrix = model.move_left(self.matrix)
elif event.keysym == "Right":
self.matrix = model.move_right(self.matrix)
elif event.keysym == "Up":
self.matrix = model.move_up(self.matrix)
elif event.keysym == "Down":
self.matrix = model.move_down(self.matrix)
if event.keysym in ["q", "Left", "Right", "Up", "Down"]:
try:
self.matrix = model.insert(self.matrix)
self.dqjf.setText(model.getScore())
self.show_matrix(self.matrix)
except:
&

