使用tkinter实现猜拳游戏
时间: 2023-08-28 20:04:46 浏览: 137
用python的tkinter制作的猜拳游戏
以下是使用Tkinter实现猜拳游戏的样例代码:
```python
import random
import tkinter as tk
# 定义游戏规则和对应的手势
game_rules = {
'rock': {'rock': 0, 'paper': -1, 'scissors': 1},
'paper': {'rock': 1, 'paper': 0, 'scissors': -1},
'scissors': {'rock': -1, 'paper': 1, 'scissors': 0}
}
gestures = ['rock', 'paper', 'scissors']
# 定义游戏状态
player_score = 0
computer_score = 0
game_round = 0
# 定义游戏函数
def play_game(player_gesture):
global player_score, computer_score, game_round
computer_gesture = random.choice(gestures)
result = game_rules[player_gesture][computer_gesture]
game_round += 1
if result > 0:
player_score += 1
result_text.set('You win!')
elif result < 0:
computer_score += 1
result_text.set('You lose!')
else:
result_text.set('Tie!')
update_scores()
# 定义更新分数和回合数的函数
def update_scores():
player_score_text.set('Player: {}'.format(player_score))
computer_score_text.set('Computer: {}'.format(computer_score))
round_text.set('Round: {}'.format(game_round))
# 创建主窗口和控件
root = tk.Tk()
root.title('Rock Paper Scissors')
player_score_text = tk.StringVar()
player_score_text.set('Player: 0')
player_score_label = tk.Label(root, textvariable=player_score_text)
player_score_label.pack()
computer_score_text = tk.StringVar()
computer_score_text.set('Computer: 0')
computer_score_label = tk.Label(root, textvariable=computer_score_text)
computer_score_label.pack()
round_text = tk.StringVar()
round_text.set('Round: 0')
round_label = tk.Label(root, textvariable=round_text)
round_label.pack()
result_text = tk.StringVar()
result_text.set('Make your choice!')
result_label = tk.Label(root, textvariable=result_text)
result_label.pack()
rock_button = tk.Button(root, text='Rock', command=lambda: play_game('rock'))
rock_button.pack(side='left')
paper_button = tk.Button(root, text='Paper', command=lambda: play_game('paper'))
paper_button.pack(side='left')
scissors_button = tk.Button(root, text='Scissors', command=lambda: play_game('scissors'))
scissors_button.pack(side='left')
update_scores()
root.mainloop()
```
运行该程序,即可看到猜拳游戏界面,玩家可以通过点击按钮来进行游戏,程序会自动计算比分并显示游戏结果。
阅读全文