如何用Python實現網紅兒童計算器游戲
作者:華安9527
要使用圖形用戶界面(GUI)實現這個“兒童計算器”游戲,我們可以使用Python中的Tkinter庫,它是Python的標準GUI庫,非常適合創建簡單的桌面應用程序。
要使用圖形用戶界面(GUI)實現這個“兒童計算器”游戲,我們可以使用Python中的Tkinter庫,它是Python的標準GUI庫,非常適合創建簡單的桌面應用程序。
import tkinter as tk
from tkinter import messagebox
import random
class CalculatorGame(tk.Tk):
def __init__(self):
super().__init__()
self.title("兒童計算器游戲")
self.geometry("400x250")
self.operation_var = tk.StringVar(value="+")
self.create_widgets()
self.set_new_question() # 確保在UI構建完成后設置第一次題目
def set_new_question(self):
op = self.operation_var.get()
self.num1 = random.randint(1, 10)
if op in ['+', '-']:
self.num2 = random.randint(1, 10)
elif op == '*':
self.num2 = random.randint(1, 10)
else: # 除法
self.num2 = random.choice([i for i in range(1, self.num1 + 1) if self.num1 % i == 0])
self.correct_answer = self.calculate_correct_answer(op)
self.update_question_label()
def calculate_correct_answer(self, op):
if op == '+':
return self.num1 + self.num2
elif op == '-':
return self.num1 - self.num2
elif op == '*':
return self.num1 * self.num2
else: # 除法
return self.num1 // self.num2
def update_question_label(self):
self.question_label.config(text=f"{self.num1} {self.operation_var.get()} {self.num2} = ?")
def create_widgets(self):
self.question_label = tk.Label(self, text="", font=("Arial", 16))
self.question_label.pack(pady=20)
self.operation_var.trace('w', lambda *args: self.set_new_question())
self.operation_menu = tk.OptionMenu(self, self.operation_var, "+", "-", "*", "/")
self.operation_menu.pack(pady=10)
self.answer_entry = tk.Entry(self)
self.answer_entry.pack(pady=10)
self.submit_button = tk.Button(self, text="提交答案", command=self.check_answer)
self.submit_button.pack(pady=10)
def check_answer(self):
user_answer = self.answer_entry.get()
try:
user_answer = int(user_answer)
if user_answer == self.correct_answer:
messagebox.showinfo("正確", "恭喜你,答對了!")
else:
feedback_msg = f"很遺憾,答錯了。正確答案是{self.correct_answer}。"
messagebox.showerror("錯誤", feedback_msg)
except ValueError:
messagebox.showerror("錯誤", "請輸入一個有效的數字。")
finally:
self.answer_entry.delete(0, tk.END)
self.set_new_question()
if __name__ == "__main__":
app = CalculatorGame()
app.mainloop()
實現邏輯:
導入庫
import tkinter as tk
from tkinter import messagebox
import random
tkinter 是 Python 的標準 GUI 庫,用于創建圖形用戶界面。
messagebox 是 tkinter 的一個子模塊,用于彈出消息對話框,比如錯誤、警告或確認信息。
random 庫用于生成隨機數,以便在游戲里隨機選擇數學運算的數值。
類定義:CalculatorGame 繼承自 tk.Tk
class CalculatorGame(tk.Tk):
定義了一個名為 CalculatorGame 的類,繼承自 tkinter 的 Tk 類,意味著它將是一個具有圖形界面的應用程序。
初始化方法:init
def __init__(self):
super().__init__()
self.title("兒童計算器游戲")
self.geometry("400x250")
self.operation_var = tk.StringVar(value="+")
self.create_widgets()
self.set_new_question()
調用父類的初始化方法,設置窗口標題和大小。
定義一個 StringVar 變量 operation_var 來存儲當前選擇的運算符,默認為 "+"。
調用 create_widgets 方法來構建 UI 界面。
調用 set_new_question 方法來初始化第一道題目。
set_new_question 方法
def set_new_question(self):
# 根據運算符生成隨機數并計算正確答案,更新題目顯示
這個方法根據當前選擇的運算符生成兩個隨機數(確保除法時能整除),計算出正確答案,并調用 update_question_label 更新顯示的題目。
calculate_correct_answer 方法
def calculate_correct_answer(self, op):
# 計算當前題目答案
根據運算符計算并返回當前題目的正確答案。
update_question_label 方法
def update_question_label(self):
# 更新題目標簽的文本內容
更新顯示題目和數值的標簽,使其反映出當前的數學問題。
create_widgets 方法
def create_widgets(self):
# 創建所有UI組件
構建游戲的UI元素,包括:
問題標簽 (question_label) 顯示當前的數學問題。
運算符選擇菜單 (operation_menu) 允許用戶選擇運算類型。
輸入框 (answer_entry) 供用戶輸入答案。
提交按鈕 (submit_button) 用戶點擊提交答案。
check_answer 方法
def check_answer(self):
# 檢查用戶輸入的答案并給出反饋
處理用戶提交的答案:
嘗試將輸入轉換為整數并比較與正確答案。
顯示正確的消息框或錯誤提示,并在任何情況下清空輸入框準備下一次輸入。
提交答案后,立即生成新題目。
主程序執行
if __name__ == "__main__":
app = CalculatorGame()
app.mainloop()
當腳本直接運行時,創建 CalculatorGame 類的實例,并啟動 Tkinter 的事件循環,即顯示圖形界面并等待用戶交互。
責任編輯:華軒
來源:
測試開發學習交流