python基于tkinter制作圖形界面的2048游戲
前提條件如下:
1. Python2. Tkinter
創(chuàng)建main.py代碼:
from tkinter import *from tkinter import messageboximport randomclass 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()解釋:
我們在代碼中定義了兩個(gè)類:
1.Board:變量:
Bg_color:這是一個(gè)字典,用于存儲(chǔ)每個(gè)單元格的背景色。 Color:這是一個(gè)字典,用于存儲(chǔ)每個(gè)單元的前景色。 Window:它是tkinter的主要窗口。 gameArea:這是一個(gè)tkinter框架小部件。 gridCell:這是一個(gè)4×4整數(shù)矩陣,存儲(chǔ)所有單元格的實(shí)際整數(shù)值。 Board:這是tkinter標(biāo)簽小部件的4×4網(wǎng)格,它在tkinter窗口上顯示單元格的值。它還用于根據(jù)其gridCell值配置該單元格的背景和前景。 Score:它存儲(chǔ)玩家的當(dāng)前分?jǐn)?shù)。其余只是標(biāo)志變量。
功能:
__init __(self):這是構(gòu)造函數(shù)。它使用適當(dāng)?shù)哪J(rèn)值初始化所有變量,例如gridCell的默認(rèn)值為“ 0”,移動(dòng),合并的默認(rèn)值為False,等等。 Reverse:反轉(zhuǎn)gridCell矩陣。 Transpose:它使用zip函數(shù)并進(jìn)行g(shù)ridCell矩陣的轉(zhuǎn)置。 CompressGrid:它將所有非空單元格向左移動(dòng),因此可以輕松完成合并。 mergeGrid:如果兩個(gè)相鄰單元格具有相同的gridCell值,則將它們的gridCell值相加。 Random_cell:首先將所有空單元格存儲(chǔ)在列表中,然后從創(chuàng)建的列表中選擇一個(gè)隨機(jī)單元格并使其gridCell值2 Can_merge:返回一個(gè)布爾值,表示我們可以合并任意兩個(gè)單元格。當(dāng)且僅當(dāng)兩個(gè)單元格具有相同的gridCell值時(shí),我們才可以合并它們。 paintGrid:將前景和背景色分配給4×4網(wǎng)格中與其gridCell值相對應(yīng)的每個(gè)單元。2.game:此類沒有很多變量,只有一些布爾變量指示游戲狀態(tài)。
功能:
__init __(self):這是構(gòu)造函數(shù)。它使用適當(dāng)?shù)哪J(rèn)值初始化所有變量。 開始:調(diào)用random_cell兩次,將’2’賦給兩個(gè)隨機(jī)單元格的gridCell值,然后繪制網(wǎng)格,然后,調(diào)用link_keys鏈接上,下,左和右鍵。 Link_keys:首先,它檢查游戲是贏還是輸,如果是,則不執(zhí)行任何操作執(zhí)行return語句。否則,它將繼續(xù)執(zhí)行。方法:
對于左滑動(dòng),我們將先壓縮然后合并gridCell矩陣,然后如果compress或merge為true(指示矩陣的值受前兩個(gè)函數(shù)影響),那么我們需要再次壓縮網(wǎng)格。 對于上移,我們將進(jìn)行移調(diào),然后向左輕掃,然后再次進(jìn)行移調(diào)以返回原始順序。 向下移動(dòng)與向上移動(dòng)相同,但是我們需要反轉(zhuǎn)矩陣。 同樣,向右與向左+向后移動(dòng)相同。 每次操作后,我們需要檢查游戲狀態(tài),如果所有單元都被占用,我們甚至不能合并任何兩個(gè)單元,即沒有動(dòng)作可以改變矩陣的狀態(tài),則游戲結(jié)束了。如果任何一個(gè)單元格值都達(dá)到2048,則玩家將獲勝,并且屏幕上會(huì)閃爍一個(gè)消息框,宣布獲勝者。
總結(jié)我們已經(jīng)成功地用python開發(fā)了流行的2048游戲。開發(fā)游戲而不是玩別人的游戲非常有趣,現(xiàn)在我們將玩自己開發(fā)的游戲。
以上就是python基于tkinter制作圖形界面的2048游戲的詳細(xì)內(nèi)容,更多關(guān)于python 圖形界面2048游戲的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. PHP循環(huán)與分支知識點(diǎn)梳理2. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)3. 前端從瀏覽器的渲染到性能優(yōu)化4. ASP基礎(chǔ)入門第三篇(ASP腳本基礎(chǔ))5. css代碼優(yōu)化的12個(gè)技巧6. ASP實(shí)現(xiàn)加法驗(yàn)證碼7. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁8. 讀大數(shù)據(jù)量的XML文件的讀取問題9. 利用CSS3新特性創(chuàng)建透明邊框三角10. 解析原生JS getComputedStyle
