Python石头剪刀布游戏:重试函数新值获取与分数持久化问题
Hey there! Let's work through the two issues in your RPS game step by step:
1. Why Scores Only Update Once (And How to Fix It)
The core problem here is that your compwin and userwin variables are defined inside the rps() function. Every time you call rps() (like when you retry), these variables get reset to 0. To keep track of scores across rounds, we need to move them to the global scope so their values persist between function calls.
2. Properly Restarting with New Values
Right now, your retry() function calls rps() directly, which triggers a full reset of the game state (including scores). Instead, we should have retry() return a boolean to tell the main game loop whether to run another round, and generate a new computer choice each round instead of once per rps() call.
Fixed Full Code
import random # Initialize scores globally so they persist across rounds compwin = 0 userwin = 0 picks = ['rock', 'paper', 'scissors'] def retry(): while True: replay = input("Want to try again? ").lower() if replay not in ["y", "n", "yes", "no"]: print("Please enter Yes or No.") elif replay in ["n", "no"]: print("Thanks for playing.\nBye now!") return False elif replay in ["y", "yes"]: print("Let's try again!") return True def rps(): global compwin, userwin # Declare we're modifying the global score variables while True: # Generate a new computer choice EVERY round computer = random.choice(picks) user = input("Choose: Rock, Paper, Scissors: \n").lower() if user not in picks: print("Please choose a valid option.") continue # Skip to next iteration to let user re-enter a valid choice if user == computer: print("It's a draw.") elif ((user == 'rock' and computer == 'paper') or (user == 'paper' and computer == 'scissors') or (user == 'scissors' and computer == 'rock')): print("Computer won!") compwin += 1 print(f"Computer won: {compwin} games") else: print('You won!') userwin += 1 print(f"User won: {userwin} games") # Check if user wants to continue - exit loop if not if not retry(): break rps()
Key Changes Explained
- Global Score Tracking:
compwinanduserwinlive outside therps()function, so their values don't reset between rounds. Theglobalkeyword lets us modify these variables inside the game function. - Per-Round Computer Choice: Moving
computer = random.choice(picks)inside the main loop ensures we get a fresh random selection every round, not just once when the game starts. - Retry Logic Overhaul:
retry()now returnsTrue/Falseinstead of callingrps()directly. This lets the main game loop control whether to run another round, avoiding unnecessary resets. - Better Input Handling: Added
continueafter invalid input so the game doesn't attempt to judge a result with an invalid choice. - Readable Output: Used f-strings for score printing to make the code cleaner and easier to read.
内容的提问来源于stack exchange,提问作者Hellboy

