搜尋
首頁後端開發Python教學使用graphics.py实现2048小游戏

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("", 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)             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,'当前分数:')

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

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python vs. C:了解關鍵差異Python vs. C:了解關鍵差異Apr 21, 2025 am 12:18 AM

Python和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

Python vs.C:您的項目選擇哪種語言?Python vs.C:您的項目選擇哪種語言?Apr 21, 2025 am 12:17 AM

選擇Python還是C 取決於項目需求:1)如果需要快速開發、數據處理和原型設計,選擇Python;2)如果需要高性能、低延遲和接近硬件的控制,選擇C 。

達到python目標:每天2小時的力量達到python目標:每天2小時的力量Apr 20, 2025 am 12:21 AM

通過每天投入2小時的Python學習,可以有效提升編程技能。 1.學習新知識:閱讀文檔或觀看教程。 2.實踐:編寫代碼和完成練習。 3.複習:鞏固所學內容。 4.項目實踐:應用所學於實際項目中。這樣的結構化學習計劃能幫助你係統掌握Python並實現職業目標。

最大化2小時:有效的Python學習策略最大化2小時:有效的Python學習策略Apr 20, 2025 am 12:20 AM

在兩小時內高效學習Python的方法包括:1.回顧基礎知識,確保熟悉Python的安裝和基本語法;2.理解Python的核心概念,如變量、列表、函數等;3.通過使用示例掌握基本和高級用法;4.學習常見錯誤與調試技巧;5.應用性能優化與最佳實踐,如使用列表推導式和遵循PEP8風格指南。

在Python和C之間進行選擇:適合您的語言在Python和C之間進行選擇:適合您的語言Apr 20, 2025 am 12:20 AM

Python適合初學者和數據科學,C 適用於系統編程和遊戲開發。 1.Python簡潔易用,適用於數據科學和Web開發。 2.C 提供高性能和控制力,適用於遊戲開發和系統編程。選擇應基於項目需求和個人興趣。

Python與C:編程語言的比較分析Python與C:編程語言的比較分析Apr 20, 2025 am 12:14 AM

Python更適合數據科學和快速開發,C 更適合高性能和系統編程。 1.Python語法簡潔,易於學習,適用於數據處理和科學計算。 2.C 語法複雜,但性能優越,常用於遊戲開發和系統編程。

每天2小時:Python學習的潛力每天2小時:Python學習的潛力Apr 20, 2025 am 12:14 AM

每天投入兩小時學習Python是可行的。 1.學習新知識:用一小時學習新概念,如列表和字典。 2.實踐和練習:用一小時進行編程練習,如編寫小程序。通過合理規劃和堅持不懈,你可以在短時間內掌握Python的核心概念。

Python與C:學習曲線和易用性Python與C:學習曲線和易用性Apr 19, 2025 am 12:20 AM

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),