赞
踩
使用Python实现一个简单的石头剪刀布游戏,让玩家可以与计算机进行对战,在弹窗显示对战结果 。
石头、剪刀和布分别代表不同的手势,其胜负规则如下:
石头战胜剪刀:石头获胜。
剪刀战胜布:剪刀获胜。
布战胜石头:布获胜。
代码如下(示例):
import tkinter as tk
import random
代码如下(示例):
# 根据规则判断胜负
def determine_winner(player_choice, computer_choice):
if player_choice == computer_choice:
return "平局"
elif (player_choice == "石头" and computer_choice == "剪刀") or \
(player_choice == "剪刀" and computer_choice == "布") or \
(player_choice == "布" and computer_choice == "石头"):
return "您赢了!"
else:
return "计算机赢了!"
代码如下(示例):
# 玩家选择手势
def player_choice_click(choice):
computer_choices = ["石头", "剪刀", "布"]
computer_choice = random.choice(computer_choices)
result = determine_winner(choice, computer_choice)
result_text = f"您选择了:{choice}\n计算机选择了:{computer_choice}\n结果:{result}"
result_label.config(text=result_text)
代码如下(示例):
# 创建窗口
root = tk.Tk()
root.title("石头剪刀布游戏")
root.geometry("300x200")
# 创建按钮
rock_button = tk.Button(root, text="石头", command=lambda: player_choice_click("石头"))
rock_button.pack()
scissors_button = tk.Button(root, text="剪刀", command=lambda: player_choice_click("剪刀"))
scissors_button.pack()
paper_button = tk.Button(root, text="布", command=lambda: player_choice_click("布"))
paper_button.pack()
代码如下(示例):
# 显示结果
result_label = tk.Label(root, text="")
result_label.pack()
root.mainloop()
以上就是今天要讲的内容。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。