大家好!欢迎来到奥饼饼智慧谷 🎮。今天我们来做一个经典又好玩的游戏——石头剪刀布!和电脑对战,看看谁更厉害!
🎯 功能介绍
这个石头剪刀布游戏会有这些功能:
💡 游戏小贴士
仔细观察电脑的出拳规律,找到取胜秘诀!
🎮 开始写代码
以下是完整的石头剪刀布游戏代码:
import random import json import os from datetime import datetime DATA_FILE = "rps_stats.json" CHOICES = ["石头", "剪刀", "布"] EMOJIS = {"石头": "🪨", "剪刀": "✂️", "布": "📄"} def load_data(): """加载游戏数据""" if os.path.exists(DATA_FILE): with open(DATA_FILE, 'r', encoding='utf-8') as f: return json.load(f) return { "wins": 0, "losses": 0, "draws": 0, "history": [], "current_streak": 0, "best_streak": 0 } def save_data(data): """保存游戏数据""" with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) def get_computer_choice(): """电脑随机选择""" return random.choice(CHOICES) def determine_winner(player, computer): """判断胜负""" if player == computer: return "平局" if (player == "石头" and computer == "剪刀") or \ (player == "剪刀" and computer == "布") or \ (player == "布" and computer == "石头"): return "胜利" return "失败" def play_game(): """玩一局游戏""" data = load_data() print("\n" + "="*40) print(" 🎮 石头剪刀布! 🎮") print("="*40) print("\n请选择:") for i, choice in enumerate(CHOICES, 1): print(f"{i}. {EMOJIS[choice]} {choice}") while True: choice_input = input("\n请输入选项 (1-3) 或 q 退出: ").strip().lower() if choice_input == 'q': return None try: index = int(choice_input) - 1 if 0 <= index < len(CHOICES): player_choice = CHOICES[index] break print("❌ 请输入 1-3 的数字!") except ValueError: print("❌ 请输入有效的数字!") computer_choice = get_computer_choice() result = determine_winner(player_choice, computer_choice) print("\n" + "-"*40) print(f"你: {EMOJIS[player_choice]} {player_choice}") print(f"电脑: {EMOJIS[computer_choice]} {computer_choice}") print(f"结果: {result}!") print("-"*40) if result == "胜利": data["wins"] += 1 data["current_streak"] += 1 if data["current_streak"] > data["best_streak"]: data["best_streak"] = data["current_streak"] print("🎉 新纪录!太棒了!") else: print("🎉 你赢了!") elif result == "失败": data["losses"] += 1 data["current_streak"] = 0 print("😢 你输了...") else: data["draws"] += 1 print("🤝 平局!") game_record = { "player": player_choice, "computer": computer_choice, "result": result, "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S") } data["history"].append(game_record) save_data(data) return result def view_stats(): """查看游戏统计""" data = load_data() total = data["wins"] + data["losses"] + data["draws"] print("\n" + "="*50) print(" 📊 游戏统计") print("="*50) print(f"🎮 总游戏数: {total}") print(f"🎉 胜利: {data['wins']}") print(f"😢 失败: {data['losses']}") print(f"🤝 平局: {data['draws']}") if total > 0: win_rate = (data["wins"] / total) * 100 print(f"📈 胜率: {win_rate:.1f}%") print(f"🔥 当前连胜: {data['current_streak']}") print(f"🏆 最高连胜: {data['best_streak']}") print("="*50) def view_history(): """查看游戏历史""" data = load_data() if not data["history"]: print("\n📭 还没有游戏记录") return print("\n" + "="*70) print(" 📜 游戏历史") print("="*70) print(f"{'序号':<8} {'时间':<20} {'你':<10} {'电脑':<10} {'结果':<10}") print("-"*70) recent_history = data["history"][-15:] for i, record in enumerate(recent_history, 1): player_emoji = EMOJIS[record["player"]] computer_emoji = EMOJIS[record["computer"]] print(f"{i:<8} {record['time']:<20} {player_emoji} {record['player']:<8} {computer_emoji} {record['computer']:<8} {record['result']:<10}") print("="*70) if len(data["history"]) > 15: print(f"... 还有 {len(data['history']) - 15} 条记录") def main(): print("="*40) print(" 🎮 欢迎来到石头剪刀布! 🎮") print("="*40) while True: print("\n" + "-"*40) print("1. 开始游戏") print("2. 查看统计") print("3. 查看历史") print("4. 退出") print("-"*40) choice = input("\n请选择 (1-4): ").strip() if choice == "1": while True: result = play_game() if result is None: break again = input("\n再玩一局? (y/n): ").strip().lower() if again != 'y': break elif choice == "2": view_stats() elif choice == "3": view_history() elif choice == "4": data = load_data() print(f"\n👋 再见! 你总共玩了 {data['wins'] + data['losses'] + data['draws']} 局!") print("继续加油!") break else: print("❌ 请选择 1-4!") if __name__ == "__main__": main()
游戏不仅能带来快乐,还能锻炼思维!在石头剪刀布中,观察和策略都很重要!
🚀 运行试试吧!
保存为 `rps.py` 然后运行:
python rps.py
开始和电脑对战吧!看看谁能赢得更多!
✨ 进阶玩法
想让这个游戏更有趣?试试这些改进:
🎁 挑战建议
试试连续赢10局,看看你能不能打破最高连胜纪录!
📚 知识要点
通过这个项目,我们学到了:
今天的石头剪刀布游戏就到这里了!快去和电脑对战,看看你能不能成为常胜将军!🎮
👋 感谢阅读 | 奥饼饼智慧谷
每天一个有趣的编程小项目,让学习变成乐趣!
💡 点赞 + 在看 + 分享,让更多人一起享受编程的快乐!