用python写一个剪刀石头布小游戏需要gui界面
时间: 2023-11-28 22:03:59 浏览: 108
好的,可以使用 Python 的 tkinter 模块来实现图形界面。下面是一个简单的剪刀石头布小游戏的代码:
```python
import random
import tkinter as tk
# 定义游戏规则
RULES = {
'剪刀': '布',
'石头': '剪刀',
'布': '石头'
}
# 定义游戏结果
RESULTS = {
'胜利': '恭喜你,你赢了!',
'失败': '很遗憾,你输了!',
'平局': '平局,再来一局!'
}
class Game:
def __init__(self):
# 创建主窗口
self.window = tk.Tk()
self.window.title('剪刀石头布')
self.window.geometry('300x150')
# 创建控件
self.label = tk.Label(self.window, text='请选择:')
self.button_scissors = tk.Button(self.window, text='剪刀', command=lambda: self.play('剪刀'))
self.button_rock = tk.Button(self.window, text='石头', command=lambda: self.play('石头'))
self.button_paper = tk.Button(self.window, text='布', command=lambda: self.play('布'))
self.result = tk.Label(self.window, text='')
# 布局控件
self.label.pack()
self.button_scissors.pack(side=tk.LEFT, padx=10)
self.button_rock.pack(side=tk.LEFT, padx=10)
self.button_paper.pack(side=tk.LEFT, padx=10)
self.result.pack()
# 运行主循环
self.window.mainloop()
def play(self, player):
# 随机选择电脑出拳
computer = random.choice(['剪刀', '石头', '布'])
# 判断胜负
if RULES[player] == computer:
result_text = RESULTS['胜利']
elif RULES[computer] == player:
result_text = RESULTS['失败']
else:
result_text = RESULTS['平局']
# 显示游戏结果
self.result.config(text=f'你选择了{player},电脑选择了{computer},{result_text}')
# 运行游戏
game = Game()
```
在这个代码中,我们使用 tkinter 创建了一个窗口,并添加了三个按钮和一个标签,用于显示游戏结果。当玩家点击按钮时,会调用 `play` 方法来进行游戏,并将结果显示在标签上。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)