使用graphics.py实现2048小游戏


Posted in Python onMarch 10, 2015

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

先看看演示图片

使用graphics.py实现2048小游戏

附上源码:

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:

                    pass

        if model.is_win(self.matrix):

            if askquestion("WIN","You win the game!\nDo you want to init it?") == 'yes':

                self.matrix = self.my_init() 

                self.show_matrix(self.matrix)

                return

            else:

                self.win.close() 

    '''

    从二维数组中获取结果数据并展示在16方格中

    '''

    def show_matrix(self, matrix): 

        for i in range(16):

            num = matrix[i//4][i%4]

            print(num)

            if num == 0:

                num = ''

            self.rectangle_2048(i,num)

    '''

    对16个方格做颜色和数字变更

    '''

    def rectangle_2048(self,i,num): 

        c = color_rgb(200, 190, 180)

        if num == 2:

            c = color_rgb(240, 230, 220)

        elif num == 4:

            c = color_rgb(240, 220, 200) 

        elif num == 8:

            c = color_rgb(240, 180, 120)  

        elif num == 16:

            c = color_rgb(240, 140, 90)  

        elif num == 32:

            c = color_rgb(240, 120, 90)  

        elif num == 64:

            c = color_rgb(240, 90, 60)  

        elif num == 128:

            c = color_rgb(240, 90, 50)   

        elif num == 256:

            c = color_rgb(240, 200, 70) 

        elif num == 512:

            c = color_rgb(240, 200, 70)  

        elif num == 1024:

            c = color_rgb(0, 130, 0)  

        elif num == 2048:

            c = color_rgb(0, 130, 0)

        '''

        循环设置颜色和数字

        '''

        self.rt[i][0].setFill(c)

        self.rt[i][1].setText(num)

#main

Application()

2048gui部分
#-*-coding:utf-8-*-

#python3.3.5

from graphics import*

#初始化并构建2048界面

def init():

    win = GraphWin("2048", 260, 450)

    win.master.geometry('+400+150')  #屏幕位置

    c = color_rgb(206, 194, 180) 

    win.setBackground(c)

    hint(win)

    _title(win)

    _grid(win)

    maxScore(win)

    curScore(win) 

    return win 

#2048方格

def rectangle_2048(win, p1 = Point(10, 10),txt='',c = color_rgb(206, 194, 180)): 

    p2 = Point(p1.x + 60, p1.y + 60)

    r = _rectangle(win,p1,p2,c)

    t = _text(win,p1,p2,txt)

    return r,t

#挂牌

def hint(win,p1 = Point(10, 10)): 

    p2 = Point(p1.x + 240, p1.y + 40)

    c = color_rgb(187, 173, 164)

    _rectangle(win,p1,p2,c)

    t = _text(win,p1,p2,'真英雄 挑战2048~') 

    t.setTextColor(color_rgb(238, 231, 221))

    return t

#标题logo

def _title(win,p1 = Point(10, 60)): 

    p2 = Point(p1.x + 120, p1.y + 120)

    c = color_rgb(228, 184, 0)

    _rectangle(win,p1,p2,c)

    t = Text(Point((p2.x + p1.x) / 2, (p2.y + p1.y) / 2), '2048')

    t.setSize(35)

    t.setStyle('bold')

    t.setTextColor('white')

    t.draw(win)

#画正方形

def _rectangle(win,p1,p2,c):

    r = Rectangle(p1, p2) 

    r.setFill(c) 

    r.setOutline(color_rgb(198, 186, 174))

    r.draw(win)

    return r

#写文字    

def _text(win,p1,p2,txt):

    t = Text(Point((p2.x + p1.x) / 2, (p2.y + p1.y) / 2), txt)

    t.draw(win)

    return t

#网格

def _grid(win,p1 = Point(10, 190)):

    #上面 

    p_u_1 = Point(p1.x + 60, p1.y) 

    p_u_2 = Point(p1.x + 120, p1.y)

    p_u_3 = Point(p1.x + 180, p1.y)

    p_u_4 = Point(p1.x + 240, p1.y)

    #左面

    p_l_1 = Point(p1.x, p1.y + 60) 

    p_l_2 = Point(p1.x, p1.y + 120)

    p_l_3 = Point(p1.x , p1.y + 180)

    p_l_4 = Point(p1.x , p1.y + 240)

    #右面

    p_r_1 = Point(p1.x + 240, p1.y + 60)

    p_r_2 = Point(p1.x + 240, p1.y + 120)

    p_r_3 = Point(p1.x + 240, p1.y + 180)

    p_r_4 = Point(p1.x + 240, p1.y + 240)

    #下面

    p_d_1 = Point(p1.x + 60 , p1.y + 240)

    p_d_2 = Point(p1.x + 120 , p1.y + 240)

    p_d_3 = Point(p1.x + 180 , p1.y + 240)

    p_d_4 = Point(p1.x + 240 , p1.y + 240)

    c = color_rgb(198, 186, 174) 

    #画横线

    l_W_1 = Line(p1, p_u_4)

    l_W_2 = Line(p_l_1, p_r_1)

    l_W_3 = Line(p_l_2, p_r_2)

    l_W_4 = Line(p_l_3, p_r_3)

    l_W_5 = Line(p_l_4, p_r_4)

    l_W_1.setFill(c)

    l_W_2.setFill(c)

    l_W_3.setFill(c)

    l_W_4.setFill(c)

    l_W_5.setFill(c)

    l_W_1.draw(win)

    l_W_2.draw(win)

    l_W_3.draw(win)

    l_W_4.draw(win)

    l_W_5.draw(win)

    #画竖线

    l_H_1 = Line(p1, p_l_4)

    l_H_2 = Line(p_u_1, p_d_1)

    l_H_3 = Line(p_u_2, p_d_2)

    l_H_4 = Line(p_u_3, p_d_3)

    l_H_5 = Line(p_u_4, p_d_4)

    l_H_1.setFill(c)

    l_H_2.setFill(c)

    l_H_3.setFill(c)

    l_H_4.setFill(c)

    l_H_5.setFill(c)

    l_H_1.draw(win)

    l_H_2.draw(win)

    l_H_3.draw(win)

    l_H_4.draw(win)

    l_H_5.draw(win)

#最佳成绩

def maxScore(win,p1 = Point(135, 60)): 

    p2 = Point(p1.x + 115, p1.y + 30)

    c = color_rgb(187, 173, 164)

    _rectangle(win,p1,p2,c)

    _text(win,p1,p2,'最佳成绩:')

#当前分数

def curScore(win,p1 = Point(135, 120)): 

    p2 = Point(p1.x + 115, p1.y + 30)

    c = color_rgb(187, 173, 164)

    _rectangle(win,p1,p2,c)

    _text(win,p1,p2,'当前分数:')

以上就是本文的全部内容了,希望大家能够喜欢。

Python 相关文章推荐
Python脚本判断 Linux 是否运行在虚拟机上
Apr 25 Python
浅析Python 中整型对象存储的位置
May 16 Python
python3如何将docx转换成pdf文件
Mar 23 Python
Python3.6.0+opencv3.3.0人脸检测示例
May 25 Python
Python基于pyCUDA实现GPU加速并行计算功能入门教程
Jun 19 Python
python爬虫 模拟登录人人网过程解析
Jul 31 Python
python读写csv文件的方法
Aug 13 Python
使用opencv将视频帧转成图片输出
Dec 10 Python
通过 Python 和 OpenCV 实现目标数量监控
Jan 05 Python
使用pygame实现垃圾分类小游戏功能(已获校级二等奖)
Jul 23 Python
Python基础学习之奇异的GUI对话框
May 27 Python
Python测试框架pytest高阶用法全面详解
Jun 01 Python
Python实现去除代码前行号的方法
Mar 10 #Python
Linux下使用python调用top命令获得CPU利用率
Mar 10 #Python
Python获取DLL和EXE文件版本号的方法
Mar 10 #Python
Python接收Gmail新邮件并发送到gtalk的方法
Mar 10 #Python
Python创建xml的方法
Mar 10 #Python
Python实现生成简单的Makefile文件代码示例
Mar 10 #Python
Python和GO语言实现的消息摘要算法示例
Mar 10 #Python
You might like
php基础知识:类与对象(2) 自动加载对象
2006/12/13 PHP
PHP初学者最感迷茫的问题小结
2010/03/27 PHP
第三章 php操作符与控制结构代码
2011/12/30 PHP
基于Zookeeper的使用详解
2013/05/02 PHP
基于Discuz security.inc.php代码的深入分析
2013/06/03 PHP
PHP编程计算文件或数组中单词出现频率的方法
2017/05/22 PHP
Laravel 中创建 Zip 压缩文件并提供下载的实现方法
2019/04/02 PHP
[原创]PHP global全局变量经典应用与注意事项分析【附$GLOBALS用法对比】
2019/07/12 PHP
用js得到网页中所有的div的id
2020/10/19 Javascript
setTimeout和setInterval的浏览器兼容性分析
2007/02/27 Javascript
Extjs中DisplayField的日期或者数字格式化扩展
2010/09/03 Javascript
JS实现转动随机数抽奖特效代码
2020/04/16 Javascript
详谈angularjs中路由页面强制更新的问题
2017/04/24 Javascript
js禁止表单重复提交
2017/08/29 Javascript
Iview Table组件中各种组件扩展的使用
2018/10/20 Javascript
vue-cli项目使用mock数据的方法(借助express)
2019/04/15 Javascript
微信小程序用户授权,以及判断登录是否过期的方法
2019/05/10 Javascript
原生JS无缝滑动轮播图
2019/10/22 Javascript
node.js基于dgram数据报模块创建UDP服务器和客户端操作示例
2020/02/12 Javascript
在nodejs中创建child process的方法
2021/01/26 NodeJs
Python随机生成均匀分布在三角形内或者任意多边形内的点
2017/12/14 Python
python抓取京东小米8手机配置信息
2018/11/13 Python
详解Python locals()的陷阱
2019/03/26 Python
python实现接口并发测试脚本
2019/06/25 Python
Python中私有属性的定义方式
2020/03/05 Python
Python3内置函数chr和ord实现进制转换
2020/06/05 Python
Python使用文件操作实现一个XX信息管理系统的示例
2020/07/02 Python
python使用隐式循环快速求和的实现示例
2020/09/11 Python
HTML5拖拽API经典实例详解
2018/04/20 HTML / CSS
解决python 输出到csv 出现多空行的情况
2021/03/24 Python
给校长的建议书
2014/03/12 职场文书
班级文化标语
2014/06/23 职场文书
颐和园的导游词
2015/01/30 职场文书
PHP连接MSSQL数据库案例,PHPWAMP多个PHP版本连接SQL Server数据库
2021/04/16 PHP
CSS3中Animation实现简单的手指点击动画的示例
2021/07/15 HTML / CSS
Python函数对象与闭包函数
2022/04/13 Python