import tkinter as tk
from tkinter import messagebox, ttk
import random
import sys
from typing import Tuple
class RockPaperScissorsGame:
"""石头剪刀布游戏类"""
def __init__(self, root: tk.Tk):
"""初始化游戏"""
self.root = root
self.root.title("石头剪刀布游戏")
self.root.geometry("600x450")
self.root.resizable(False, False)
# 确保中文显示正常
self.configure_fonts()
# 游戏数据
self.choices = ["石头", "剪刀", "布"]
self.user_score = 0
self.computer_score = 0
self.rounds_played = 0
# 创建UI
self.create_widgets()
def configure_fonts(self) -> None:
"""配置字体以确保中文显示正常"""
if sys.platform.startswith('win'):
self.default_font = ('SimHei', 12)
self.title_font = ('SimHei', 18, 'bold')
elif sys.platform.startswith('darwin'):
self.default_font = ('Heiti TC', 12)
self.title_font = ('Heiti TC', 18, 'bold')
else: # Linux 和其他系统
self.default_font = ('WenQuanYi Micro Hei', 12)
self.title_font = ('WenQuanYi Micro Hei', 18, 'bold')
def create_widgets(self) -> None:
"""创建游戏界面组件"""
# 标题
title_label = tk.Label(
self.root,
text="石头剪刀布游戏",
font=self.title_font,
pady=20
)
title_label.pack()
# 游戏区域框架
game_frame = tk.Frame(self.root)
game_frame.pack(pady=20)
# 用户选择区域
user_frame = tk.LabelFrame(game_frame, text="你的选择", font=self.default_font)
user_frame.grid(row=0, column=0, padx=20, pady=10)
self.user_choice_var = tk.StringVar()
self.user_choice_var.set("")
for i, choice in enumerate(self.choices):
choice_btn = tk.Radiobutton(
user_frame,
text=choice,
variable=self.user_choice_var,
value=choice,
font=self.default_font,
indicatoron=0,
width=10,
height=2
)
choice_btn.grid(row=i, column=0, padx=10, pady=5)
# 结果显示区域
result_frame = tk.LabelFrame(game_frame, text="游戏结果", font=self.default_font)
result_frame.grid(row=0, column=1, padx=20, pady=10)
self.result_var = tk.StringVar()
self.result_var.set("请做出你的选择...")
result_label = tk.Label(
result_frame,
textvariable=self.result_var,
font=self.default_font,
wraplength=200,
justify=tk.CENTER,
width=20,
height=5
)
result_label.pack(padx=10, pady=10)
# 计算机选择显示
self.computer_choice_var = tk.StringVar()
self.computer_choice_var.set("")
computer_choice_label = tk.Label(
result_frame,
textvariable=self.computer_choice_var,
font=self.default_font
)
computer_choice_label.pack(pady=5)
# 按钮区域
button_frame = tk.Frame(self.root)
button_frame.pack(pady=10)
play_btn = tk.Button(
button_frame,
text="开始游戏",
command=self.play_game,
font=self.default_font,
width=15,
height=1
)
play_btn.pack(side=tk.LEFT, padx=10)
reset_btn = tk.Button(
button_frame,
text="重置游戏",
command=self.reset_game,
font=self.default_font,
width=15,
height=1
)
reset_btn.pack(side=tk.LEFT, padx=10)
# 得分区域
score_frame = tk.LabelFrame(self.root, text="得分情况", font=self.default_font)
score_frame.pack(fill=tk.X, padx=20, pady=10)
score_info = tk.Frame(score_frame)
score_info.pack(fill=tk.X, padx=10, pady=5)
self.user_score_var = tk.StringVar()
self.user_score_var.set(f"你: {self.user_score}")
self.computer_score_var = tk.StringVar()
self.computer_score_var.set(f"计算机: {self.computer_score}")
self.rounds_var = tk.StringVar()
self.rounds_var.set(f"总局数: {self.rounds_played}")
user_score_label = tk.Label(
score_info,
textvariable=self.user_score_var,
font=self.default_font
)
user_score_label.pack(side=tk.LEFT, padx=20)
computer_score_label = tk.Label(
score_info,
textvariable=self.computer_score_var,
font=self.default_font
)
computer_score_label.pack(side=tk.LEFT, padx=20)
rounds_label = tk.Label(
score_info,
textvariable=self.rounds_var,
font=self.default_font
)
rounds_label.pack(side=tk.LEFT, padx=20)
# 状态栏
self.status_var = tk.StringVar()
self.status_var.set("欢迎玩石头剪刀布游戏!")
status_bar = tk.Label(
self.root,
textvariable=self.status_var,
bd=1,
relief=tk.SUNKEN,
anchor=tk.W,
font=self.default_font
)
status_bar.pack(side=tk.BOTTOM, fill=tk.X)
def determine_winner(self, user_choice: str, computer_choice: str) -> Tuple[str, int]:
"""确定游戏胜负
Args:
user_choice: 用户选择
computer_choice: 计算机选择
Returns:
结果信息和得分(1表示用户赢,-1表示计算机赢,0表示平局)
"""
if user_choice == computer_choice:
return "平局!", 0
elif (
(user_choice == "石头" and computer_choice == "剪刀") or
(user_choice == "剪刀" and computer_choice == "布") or
(user_choice == "布" and computer_choice == "石头")
):
return "你赢了!", 1
else:
return "计算机赢了!", -1
def play_game(self) -> None:
"""处理游戏逻辑"""
user_choice = self.user_choice_var.get()
if not user_choice:
messagebox.showwarning("警告", "请先选择石头、剪刀或布!")
return
# 计算机随机选择
computer_choice = random.choice(self.choices)
self.computer_choice_var.set(f"计算机选择了: {computer_choice}")
# 确定胜负
result, score = self.determine_winner(user_choice, computer_choice)
self.result_var.set(f"你选择了: {user_choice}
{result}")
# 更新得分
self.rounds_played += 1
if score == 1:
self.user_score += 1
self.status_var.set("你赢得了这一轮!")
elif score == -1:
self.computer_score += 1
self.status_var.set("计算机赢得了这一轮!")
else:
self.status_var.set("这一轮是平局!")
# 更新得分显示
self.user_score_var.set(f"你: {self.user_score}")
self.computer_score_var.set(f"计算机: {self.computer_score}")
self.rounds_var.set(f"总局数: {self.rounds_played}")
def reset_game(self) -> None:
"""重置游戏"""
if messagebox.askyesno("确认", "确定要重置游戏吗?当前得分将被清零。"):
self.user_score = 0
self.computer_score = 0
self.rounds_played = 0
self.user_score_var.set(f"你: {self.user_score}")
self.computer_score_var.set(f"计算机: {self.computer_score}")
self.rounds_var.set(f"总局数: {self.rounds_played}")
self.user_choice_var.set("")
self.result_var.set("请做出你的选择...")
self.computer_choice_var.set("")
self.status_var.set("游戏已重置!")
if __name__ == "__main__":
root = tk.Tk()
game = RockPaperScissorsGame(root)
root.mainloop()
© 版权声明
文章版权归作者所有,未经允许请勿转载。如内容涉嫌侵权,请在本页底部进入<联系我们>进行举报投诉!
THE END
暂无评论内容