You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
2.6 KiB
82 lines
2.6 KiB
import random |
|
import os |
|
|
|
def play_round(): |
|
choices = ["rock", "paper", "scissors"] |
|
computer_choice = random.choice(choices) |
|
|
|
while True: |
|
user_choice = input("Enter rock, paper, or scissors: ").lower() |
|
if user_choice in choices: |
|
break |
|
else: |
|
print("Invalid choice. Please enter rock, paper, or scissors.") |
|
|
|
print(f"You chose: {user_choice}") |
|
print(f"Computer chose: {computer_choice}") |
|
|
|
if user_choice == computer_choice: |
|
print("It's a tie!") |
|
return 0 |
|
elif ( |
|
(user_choice == "rock" and computer_choice == "scissors") |
|
or (user_choice == "paper" and computer_choice == "rock") |
|
or (user_choice == "scissors" and computer_choice == "paper") |
|
): |
|
print("You win!") |
|
return 1 |
|
else: |
|
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 |
|
|
|
print("Welcome to Rock, Paper, Scissors!") |
|
|
|
while True: |
|
result = play_round() |
|
if result == 1: |
|
user_score += 1 |
|
elif result == -1: |
|
computer_score += 1 |
|
|
|
save_game_history(user_score, computer_score, result) |
|
|
|
play_again = input("Play again? (yes/no): ").lower() |
|
if play_again != "yes": |
|
break |
|
|
|
if __name__ == "__main__": |
|
main()
|
|
|