Files

221 lines
6.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
剪子包袱锤游戏(石头剪刀布)
经典的石头剪刀布游戏,支持人机对战
"""
import random
import sys
from enum import Enum
class Move(Enum):
"""手势枚举"""
ROCK = "石头"
PAPER = "包袱"
SCISSORS = "剪子"
class RockPaperScissorsGame:
"""剪子包袱锤游戏类"""
def __init__(self):
"""初始化游戏"""
self.player_name = ""
self.player_wins = 0
self.computer_wins = 0
self.draws = 0
self.total_games = 0
# 手势克制关系
self.beats = {
Move.ROCK: Move.SCISSORS, # 石头赢剪子
Move.PAPER: Move.ROCK, # 包袱赢石头
Move.SCISSORS: Move.PAPER # 剪子赢包袱
}
def display_title(self):
"""显示游戏标题"""
print("\n" + "=" * 60)
print("✊ 剪子包袱锤 ✌️")
print("=" * 60)
print("\n游戏规则:")
print(" - 石头赢剪子")
print(" - 包袱赢石头")
print(" - 剪子赢包袱")
print(" - 相同手势为平局")
print("=" * 60)
def get_player_name(self):
"""获取玩家名字"""
self.player_name = input("\n请输入你的名字:").strip()
if not self.player_name:
self.player_name = "玩家"
print(f"\n你好,{self.player_name}!让我们开始游戏吧!\n")
def get_player_move(self):
"""
获取玩家手势
Returns:
玩家选择的手势
"""
while True:
print("\n请选择手势:")
print(" 1. 石头 (r/1)")
print(" 2. 包袱 (p/2)")
print(" 3. 剪子 (s/3)")
choice = input("\n你的选择:").strip().lower()
if choice in ['r', '1', '石头', 'rock']:
return Move.ROCK
elif choice in ['p', '2', '包袱', 'paper']:
return Move.PAPER
elif choice in ['s', '3', '剪子', 'scissors']:
return Move.SCISSORS
else:
print("❌ 请输入有效的选择(1/2/3 或 r/p/s 或 石头/包袱/剪子)!")
def get_computer_move(self):
"""
获取电脑手势
Returns:
电脑随机选择的手势
"""
return random.choice(list(Move))
def determine_winner(self, player_move, computer_move):
"""
判断胜负
Args:
player_move: 玩家手势
computer_move: 电脑手势
Returns:
'player' 玩家赢,'computer' 电脑赢,'draw' 平局
"""
if player_move == computer_move:
return 'draw'
elif self.beats[player_move] == computer_move:
return 'player'
else:
return 'computer'
def play_round(self):
"""玩一轮游戏"""
print("\n" + "-" * 60)
print(f"第 {self.total_games + 1} 局")
print("-" * 60)
# 获取玩家选择
player_move = self.get_player_move()
# 电脑随机选择
print("\n🤖 电脑正在思考...")
import time
time.sleep(0.5)
computer_move = self.get_computer_move()
# 显示双方选择
print(f"\n👤 {self.player_name}: {player_move.value}")
print(f"🤖 电脑:{computer_move.value}")
# 判断胜负
result = self.determine_winner(player_move, computer_move)
if result == 'player':
print(f"\n✅ {self.player_name} 赢了!{player_move.value} 赢 {computer_move.value}")
self.player_wins += 1
elif result == 'computer':
print(f"\n❌ 电脑赢了!{computer_move.value} 赢 {player_move.value}")
self.computer_wins += 1
else:
print(f"\n🤝 平局!双方都是 {player_move.value}")
self.draws += 1
self.total_games += 1
# 显示统计
print(f"\n📊 统计:{self.player_name} {self.player_wins} 胜 / 电脑 {self.computer_wins} 胜 / 平局 {self.draws} 场")
def check_continue(self):
"""
检查是否继续游戏
Returns:
True 表示继续,False 表示结束
"""
while True:
choice = input("\n是否继续游戏?(y/n): ").strip().lower()
if choice in ['y', 'yes', '是']:
return True
elif choice in ['n', 'no', '否']:
return False
else:
print("请输入 'y' 或 'n'!")
def show_final_stats(self):
"""显示最终统计"""
print("\n" + "=" * 60)
print(f"🎮 {self.player_name} 的最终统计")
print("=" * 60)
print(f" 总游戏局数:{self.total_games}")
print(f" {self.player_name} 胜利:{self.player_wins} 场")
print(f" 电脑胜利:{self.computer_wins} 场")
print(f" 平局:{self.draws} 场")
if self.total_games > 0:
win_rate = self.player_wins / self.total_games * 100
print(f" 胜率:{win_rate:.1f}%")
# 表现评价
if self.player_wins > self.computer_wins:
print(f"\n🏆 恭喜!{self.player_name} 获胜!")
elif self.player_wins < self.computer_wins:
print(f"\n💪 电脑获胜,{self.player_name} 再接再厉!")
else:
print(f"\n👍 势均力敌,打成平手!")
print("=" * 60)
def run(self):
"""运行游戏主流程"""
try:
# 显示标题
self.display_title()
# 获取玩家名字
self.get_player_name()
# 游戏主循环
while True:
# 玩一轮
self.play_round()
# 检查是否继续
if not self.check_continue():
break
# 显示最终统计
self.show_final_stats()
print("\n感谢游玩!再见!👋\n")
except KeyboardInterrupt:
print("\n\n游戏被中断!再见!👋\n")
if self.total_games > 0:
self.show_final_stats()
def main():
"""主函数"""
game = RockPaperScissorsGame()
game.run()
if __name__ == "__main__":
main()