帮我写一个小猿口算PK的代码
时间: 2024-10-14 07:00:18 浏览: 49
小猿口算PK的代码通常涉及到简单的用户界面交互,下面是一个简单的Python示例,使用tkinter库模拟两个玩家轮流输入数字进行加减运算:
```python
import tkinter as tk
def calculate(num1, num2, operator):
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
else:
return "错误的操作符"
return result
class MathGame:
def __init__(self, root):
self.root = root
self.player1_score = 0
self.player2_score = 0
# 创建操作按钮和文本框
self.btn1 = tk.Button(root, text="玩家1+")
self.btn1.bind("<Button-1>", lambda event: self.check_answer("player1", "+"))
self.btn2 = tk.Button(root, text="玩家1-")
self.btn2.bind("<Button-1>", lambda event: self.check_answer("player1", "-"))
self.btn1.grid(row=0, column=0)
self.btn2.grid(row=0, column=1)
self.btn3 = tk.Button(root, text="玩家2+")
self.btn3.bind("<Button-1>", lambda event: self.check_answer("player2", "+"))
self.btn4 = tk.Button(root, text="玩家2-")
self.btn4.bind("<Button-1>", lambda event: self.check_answer("player2", "-"))
self.btn3.grid(row=1, column=0)
self.btn4.grid(row=1, column=1)
self.score_label = tk.Label(root, text="")
self.score_label.grid(row=2, columnspan=2)
def check_answer(self, player, operator):
try:
num1 = int(self.entry.get())
num2 = int(self.entry.get())
result = calculate(num1, num2, operator)
print(f"{player} 的结果: {result}")
# 更新得分并清空输入框
if result % 2 == 0:
self.update_score(player, 1)
else:
self.update_score(player, -1)
self.entry.delete(0, tk.END)
except ValueError:
print("请输入数字!")
def update_score(self, player, score):
self.player1_score += score if player == 'player1' else -score
self.player2_score += score if player == 'player2' else -score
self.score_label.config(text=f"玩家1: {self.player1_score}, 玩家2: {self.player2_score}")
# 主函数
if __name__ == "__main__":
root = tk.Tk()
app = MathGame(root)
root.mainloop()
阅读全文