使用tkinter实现猜拳游戏
时间: 2023-08-27 11:06:54 浏览: 73
以下是使用tkinter实现猜拳游戏的示例代码:
```python
import tkinter as tk
import random
# 定义常量
ROCK = 0
PAPER = 1
SCISSORS = 2
CHOICES = [ROCK, PAPER, SCISSORS]
CHOICE_NAMES = {ROCK: '石头', PAPER: '剪刀', SCISSORS: '布'}
WIN_RULES = {ROCK: SCISSORS, PAPER: ROCK, SCISSORS: PAPER}
# 定义主窗口
class MainWindow(tk.Tk):
def __init__(self):
super().__init__()
self.title('猜拳游戏')
# 创建控件
self.result_label = tk.Label(self, text='请出拳')
self.rock_button = tk.Button(self, text='石头', command=lambda: self.play(ROCK))
self.paper_button = tk.Button(self, text='剪刀', command=lambda: self.play(PAPER))
self.scissors_button = tk.Button(self, text='布', command=lambda: self.play(SCISSORS))
# 布局控件
self.result_label.pack(pady=10)
self.rock_button.pack(side=tk.LEFT, padx=10)
self.paper_button.pack(side=tk.LEFT, padx=10)
self.scissors_button.pack(side=tk.LEFT, padx=10)
# 玩家出拳并计算结果
def play(self, player_choice):
computer_choice = random.choice(CHOICES)
result = '平局'
if WIN_RULES[player_choice] == computer_choice:
result = '恭喜你获胜!'
elif WIN_RULES[computer_choice] == player_choice:
result = '很遗憾你输了。'
self.result_label.config(text=f'你出了{CHOICE_NAMES[player_choice]},电脑出了{CHOICE_NAMES[computer_choice]},{result}')
# 启动程序
if __name__ == '__main__':
app = MainWindow()
app.mainloop()
```
运行以上代码,将会弹出一个窗口,点击对应的按钮出拳,程序会随机出拳并计算结果,最终在窗口中显示结果。
阅读全文