diff --git a/mymath.py b/mymath.py new file mode 100644 index 0000000..0b1b06b --- /dev/null +++ b/mymath.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +""" +石头剪刀布游戏 +玩家与电脑对决,记录胜负平局次数 +""" + +import random +import sys + +def get_computer_choice(): + """随机返回电脑的选择""" + choices = ['rock', 'paper', 'scissors'] + return random.choice(choices) + +def get_player_choice(): + """获取玩家的选择""" + while True: + print("\n请选择: (1)石头 (2)剪刀 (3)布 (q)退出") + choice = input("你的选择: ").strip().lower() + + if choice == 'q': + return None + elif choice == '1' or choice == 'rock': + return 'rock' + elif choice == '2' or choice == 'scissors': + return 'scissors' + elif choice == '3' or choice == 'paper': + return 'paper' + else: + print("无效的选择,请重试!") + +def determine_winner(player, computer): + """判断胜负""" + if player == computer: + return 'draw' + + winning_combinations = { + 'rock': 'scissors', # 石头赢剪刀 + 'scissors': 'paper', # 剪刀赢布 + 'paper': 'rock' # 布赢石头 + } + + if winning_combinations[player] == computer: + return 'player' + else: + return 'computer' + +def play_game(): + """主游戏循环""" + print("=" * 40) + print("欢迎来到石头剪刀布游戏!") + print("=" * 40) + + stats = {'player': 0, 'computer': 0, 'draw': 0} + + while True: + player_choice = get_player_choice() + if player_choice is None: + break + + computer_choice = get_computer_choice() + print(f"\n你的选择: {player_choice}") + print(f"电脑的选择: {computer_choice}") + + winner = determine_winner(player_choice, computer_choice) + + if winner == 'player': + print("🎉 你赢了!") + stats['player'] += 1 + elif winner == 'computer': + print("💻 电脑赢了!") + stats['computer'] += 1 + else: + print("🤝 平局!") + stats['draw'] += 1 + + print(f"\n当前战绩: 你 {stats['player']} 胜, 电脑 {stats['computer']} 胜, 平局 {stats['draw']}") + + print("\n" + "=" * 40) + print("游戏结束! 最终战绩:") + print(f"你赢了 {stats['player']} 次") + print(f"电脑赢了 {stats['computer']} 次") + print(f"平局 {stats['draw']} 次") + print("=" * 40) + + return stats + +def test_game(): + """测试游戏逻辑""" + print("正在测试游戏逻辑...") + + # 测试胜负判断 + test_cases = [ + ('rock', 'scissors', 'player'), + ('rock', 'paper', 'computer'), + ('rock', 'rock', 'draw'), + ('scissors', 'paper', 'player'), + ('scissors', 'rock', 'computer'), + ('scissors', 'scissors', 'draw'), + ('paper', 'rock', 'player'), + ('paper', 'scissors', 'computer'), + ('paper', 'paper', 'draw'), + ] + + passed = 0 + for player, computer, expected in test_cases: + result = determine_winner(player, computer) + if result == expected: + passed += 1 + else: + print(f"测试失败: {player} vs {computer}, 预期 {expected}, 得到 {result}") + + print(f"测试完成: {passed}/{len(test_cases)} 通过") + return passed == len(test_cases) + +if __name__ == "__main__": + # 运行测试 + if len(sys.argv) > 1 and sys.argv[1] == '--test': + if test_game(): + print("所有测试通过!") + sys.exit(0) + else: + print("测试失败!") + sys.exit(1) + else: + # 运行游戏 + play_game() \ No newline at end of file