用Python设计一个用圆形,三角形,正方形代表石头剪刀布,点击左上角的图案代表自己的选择,与电脑的随机选择进行比较
时间: 2024-09-23 07:02:24 浏览: 32
为了实现这个简单的石头剪刀布游戏,你可以使用Python的Tkinter库来创建图形用户界面(GUI),同时结合random模块生成电脑的选择。以下是一个简化的代码示例:
```python
import tkinter as tk
import random
class Game:
def __init__(self, master):
self.master = master
self.master.title("Rock, Paper, Scissors")
# 创建三个按钮,分别表示石头、剪刀、布
self.button_rocks = tk.Button(master, text="Rock", command=self.choose_rock)
self.button_paper = tk.Button(master, text="Paper", command=self.choose_paper)
self.button_scissors = tk.Button(master, text="Scissors", command=self.choose_scissors)
# 将它们放置在左上角并设置宽度
self.button_rocks.pack(side=tk.LEFT, padx=10)
self.button_paper.pack(side=tk.LEFT, padx=10)
self.button_scissors.pack(side=tk.LEFT, padx=10)
def choose_rock(self):
self.user_choice = "rock"
def choose_paper(self):
self.user_choice = "paper"
def choose_scissors(self):
self.user_choice = "scissors"
def start_game(self):
options = ["rock", "paper", "scissors"]
computer_choice = random.choice(options)
print(f"Your choice: {self.user_choice}")
print(f"Computer's choice: {computer_choice}")
if self.user_choice == computer_choice:
result = "It's a tie!"
elif (self.user_choice == "rock" and computer_choice == "scissors") or \
(self.user_choice == "paper" and computer_choice == "rock") or \
(self.user_choice == "scissors" and computer_choice == "paper"):
result = "You win!"
else:
result = "Computer wins!"
tk.Label(master, text=result).pack()
# 创建主窗口
root = tk.Tk()
game = Game(root)
game.start_game() # 开始游戏
root.mainloop()
```
在这个代码中,我们首先定义了一个Game类,包含了用户的三种选择以及开始游戏的方法。然后在主循环中创建了一个Tk窗口,并实例化了Game类。当用户点击按钮时,他们的选择会被存储,然后电脑随机选择一个选项,之后会显示结果。
运行这段代码后,你会看到一个带有三个石头、剪刀、布按钮的窗口,每次点击都会启动一轮游戏。
阅读全文