Python和tkinter實現的字母記憶配對游戲
因為這個小游戲用到了tkinter,先簡要介紹一下它。tkinter是Python的標準GUI(圖形用戶界面)庫,它提供了一種簡單而強大的方式來創建圖形界面應用程序。它提供了創建基本圖形界面所需的所有工具,同時保持了相對簡單的學習曲線。tkinter是Python的內置庫,無需額外安裝。
messagebox是tkinter中用于創建各種類型的消息對話框的模塊,需要注意的是messagebox是tkinter的一個子模塊。為了正確使用messagebox,你需要從tkinter中單獨導入它。
這個小游戲具有重新開始和難度設置功能。
“游戲”菜單,包含“新游戲”選項,點擊它或完成一局游戲后,會自動開始新游戲。
“難度”菜單,難度設置,包含簡單、中等和困難三個選項。
簡單難度: 4x2 網格,8個方塊
中等難度: 4x3 網格,12個方塊
困難難度: 4x4 網格,16個方塊
運行界面:
現在Python和tkinter實現字母記憶配對游戲源碼,先看使用面向過程風格的版本源碼:
import tkinter as tk
import tkinter.messagebox
import randomdef setup_menu(root, difficulty, new_game_func):"""設置游戲菜單"""menubar = tk.Menu(root)root.config(menu=menubar)# 創建"游戲"菜單game_menu = tk.Menu(menubar, tearoff=0)menubar.add_cascade(label="游戲", menu=game_menu)game_menu.add_command(label="新游戲", command=new_game_func)# 創建"難度"菜單difficulty_menu = tk.Menu(menubar, tearoff=0)menubar.add_cascade(label="難度", menu=difficulty_menu)difficulty_menu.add_radiobutton(label="簡單", variable=difficulty, value="簡單", command=new_game_func)difficulty_menu.add_radiobutton(label="中等", variable=difficulty, value="中等", command=new_game_func)difficulty_menu.add_radiobutton(label="困難", variable=difficulty, value="困難", command=new_game_func)def create_button(frame, row, col, on_click_func):"""創建游戲按鈕"""button = tk.Button(frame, text='', width=10, height=5, command=lambda: on_click_func(row, col))button.grid(row=row, column=col, padx=5, pady=5)return buttondef new_game():"""開始新游戲"""global matches_found, first_click, buttons, symbolsmatches_found = 0first_click = None# 清除舊的游戲布局for widget in frame.winfo_children():widget.destroy()buttons = []# 根據難度設置游戲布局和符號if difficulty.get() == "簡單":rows, cols = 4, 2symbols = ['A', 'B', 'C', 'D'] * 2elif difficulty.get() == "中等":rows, cols = 4, 3symbols = ['A', 'B', 'C', 'D', 'E', 'F'] * 2else: # 困難rows, cols = 4, 4symbols = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] * 2random.shuffle(symbols)# 創建游戲按鈕for i in range(rows):for j in range(cols):button = create_button(frame, i, j, on_click)buttons.append(button)def on_click(row, col):"""處理按鈕點擊事件"""global first_click, matches_foundindex = row * len(frame.grid_slaves()) // 4 + colbutton = buttons[index]if button['text'] == '':button['text'] = symbols[index]if first_click is None:first_click = (index, button)else:if symbols[index] == first_click[1]['text']:matches_found += 1if matches_found == len(symbols) // 2:tk.messagebox.showinfo("恭喜", "你贏了!")new_game()else:# 如果不匹配,0.5秒后隱藏按鈕root.after(500, hide_buttons, index, first_click[0])first_click = Nonedef hide_buttons(index1, index2):"""隱藏不匹配的按鈕"""buttons[index1]['text'] = ''buttons[index2]['text'] = ''# 主程序
root = tk.Tk()
root.title("字母記憶配對游戲")
root.geometry("400x450") # 設置窗口的寬度為400像素,高度為450像素difficulty = tk.StringVar()
difficulty.set("簡單") # 默認難度為簡單frame = tk.Frame(root)
frame.pack()setup_menu(root, difficulty, new_game)# 初始化游戲變量
matches_found = 0
first_click = None
buttons = []
symbols = []new_game() # 開始第一局游戲root.mainloop() # 啟動主事件循環
上面是使用面向過程風格的版本,下面改寫為使用面向對象風格的版本,源碼如下:
import tkinter as tk
import tkinter.messagebox
import randomclass MemoryGame:def __init__(self, master):self.master = masterself.master.title("字母記憶配對游戲")self.master.geometry("400x450") #設置了窗體的寬度為400像素,高度為450像素self.buttons = []self.first_click = Noneself.matches_found = 0self.difficulty = tk.StringVar()self.difficulty.set("簡單")self.setup_menu()self.setup_game()def setup_menu(self):menubar = tk.Menu(self.master)self.master.config(menu=menubar)game_menu = tk.Menu(menubar, tearoff=0)menubar.add_cascade(label="游戲", menu=game_menu)game_menu.add_command(label="新游戲", command=self.new_game)difficulty_menu = tk.Menu(menubar, tearoff=0)menubar.add_cascade(label="難度", menu=difficulty_menu)difficulty_menu.add_radiobutton(label="簡單", variable=self.difficulty, value="簡單", command=self.new_game)difficulty_menu.add_radiobutton(label="中等", variable=self.difficulty, value="中等", command=self.new_game)difficulty_menu.add_radiobutton(label="困難", variable=self.difficulty, value="困難", command=self.new_game)def setup_game(self):self.frame = tk.Frame(self.master)self.frame.pack()self.new_game()def new_game(self):self.matches_found = 0self.first_click = Nonefor widget in self.frame.winfo_children():widget.destroy()self.buttons = []if self.difficulty.get() == "簡單":rows, cols = 4, 2symbols = ['A', 'B', 'C', 'D'] * 2elif self.difficulty.get() == "中等":rows, cols = 4, 3symbols = ['A', 'B', 'C', 'D', 'E', 'F'] * 2else: # 困難rows, cols = 4, 4symbols = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] * 2random.shuffle(symbols)for i in range(rows):for j in range(cols):button = tk.Button(self.frame, text='', width=10, height=5, command=lambda x=i, y=j: self.on_click(x, y))button.grid(row=i, column=j, padx=5, pady=5)self.buttons.append(button)self.symbols = symbolsdef on_click(self, row, col):index = row * len(self.frame.grid_slaves()) // 4 + colbutton = self.buttons[index]if button['text'] == '':button['text'] = self.symbols[index]if self.first_click is None:self.first_click = (index, button)else:if self.symbols[index] == self.first_click[1]['text']:self.matches_found += 1if self.matches_found == len(self.symbols) // 2:tk.messagebox.showinfo("恭喜", "你贏了!")self.new_game()else:# 如果不匹配,0.5秒后隱藏按鈕self.master.after(500, self.hide_buttons, index, self.first_click[0])self.first_click = Nonedef hide_buttons(self, index1, index2):self.buttons[index1]['text'] = ''self.buttons[index2]['text'] = ''root = tk.Tk()
game = MemoryGame(root)
root.mainloop()