From 8d0fedcf2321977fc424e90b405f17b2b2fae74a Mon Sep 17 00:00:00 2001 From: jacqueskingram Date: Fri, 7 Mar 2025 08:39:24 -0500 Subject: [PATCH] game history added --- game_history.txt | 2 ++ rock-paper-scissors.py | 40 ++++++++++++++++++++++++++++++++++------ 2 files changed, 36 insertions(+), 6 deletions(-) create mode 100644 game_history.txt diff --git a/game_history.txt b/game_history.txt new file mode 100644 index 0000000..8923b5f --- /dev/null +++ b/game_history.txt @@ -0,0 +1,2 @@ +Round,User Choice,Computer Choice,Result,User Score,Computer Score,User Win Percentage,Computer Win Percentage +1,,,Win,1,0,100.00%,0.00% diff --git a/rock-paper-scissors.py b/rock-paper-scissors.py index 1f84e96..46d2b88 100644 --- a/rock-paper-scissors.py +++ b/rock-paper-scissors.py @@ -1,4 +1,5 @@ import random +import os def play_round(): choices = ["rock", "paper", "scissors"] @@ -28,6 +29,36 @@ def play_round(): print("You lose!") return -1 +def save_game_history(user_score, computer_score, result): + filename = "game_history.txt" + mode = "a" if os.path.exists(filename) else "w" # Append if file exists, create otherwise + + with open(filename, mode) as f: + if mode == "w": + f.write("Round,User Choice,Computer Choice,Result,User Score,Computer Score,User Win Percentage,Computer Win Percentage\n") + + user_choice_save = "" + computer_choice_save = "" + result_string = "" + + if result == 1: + result_string = "Win" + elif result == -1: + result_string = "Lose" + else: + result_string = "Tie" + + if mode == "a": + user_choice_save = input("Enter rock, paper, or scissors: ").lower() + computer_choice_save = random.choice(["rock", "paper", "scissors"]) + + total_rounds = user_score + computer_score + user_win_percentage = (user_score / total_rounds) * 100 if total_rounds > 0 else 0 + computer_win_percentage = (computer_score / total_rounds) * 100 if total_rounds > 0 else 0 + + f.write(f"{total_rounds},{user_choice_save},{computer_choice_save},{result_string},{user_score},{computer_score},{user_win_percentage:.2f}%,{computer_win_percentage:.2f}%\n") + print(f"Game history saved to {filename}") + def main(): user_score = 0 computer_score = 0 @@ -40,15 +71,12 @@ def main(): user_score += 1 elif result == -1: computer_score += 1 - - print(f"Your score: {user_score}, Computer score: {computer_score}") - + + save_game_history(user_score, computer_score, result) + play_again = input("Play again? (yes/no): ").lower() if play_again != "yes": break - print("Thanks for playing!") - print(f"Final score. Your score: {user_score}, Computer score: {computer_score}") - if __name__ == "__main__": main()