井字棋开发问题:嵌套if语句中无法递增for循环
Hey, I see the core issue here! In Python, when you use a for i in range(1,10) loop, the variable i pulls its value directly from the pre-generated range sequence each iteration. Manually incrementing i += 1 inside your nested if/elif blocks doesn't actually change the loop's next step—on the next iteration, it'll just grab the next number from the range regardless of your manual change. That's why your turn progression isn't working as expected.
A Better Approach: Use a Turn Counter with a While Loop
Instead of trying to force a for loop to do something it's not designed for, use a separate counter variable to track turns. This gives you full control over when the turn advances (only after a valid move is made), and cleans up your repetitive code at the same time.
Here's a refactored version of your code:
# Initialize turn counter: 1 = X's turn (odd), 2 = O's turn (even) turn = 1 # Run until all 9 spots are filled or a winner is found while turn <= 9: # Convert click coordinates to board row and column row = None col = None # Determine which row the click falls into if 100 <= click[1] <= 250: row = 0 elif 250 < click[1] <= 550: row = 1 elif 550 < click[1] <= 700: row = 2 # Determine which column the click falls into if 100 <= click[0] <= 250: col = 0 elif 250 < click[0] <= 550: col = 1 elif 550 < click[0] <= 700: col = 2 # Only process valid, empty spots if row is not None and col is not None and current_game[row][col] is None: # Assign X or O based on turn current_game[row][col] = "X" if turn % 2 == 1 else "O" # Advance turn only after a successful move turn += 1 # If click is invalid (outside board or on filled spot), wait for next input
Key Improvements:
- Controlled Turn Progression: The
turnvariable only increments when a valid move is made, so players can't skip turns accidentally. - Cleaner Code: We separated coordinate checking into row/col logic, eliminating all that repetitive if/elif duplication from your original code.
- Prevent Overwrites: Added a check to ensure we only place a mark on an empty spot—your original code would let players overwrite existing moves!
内容的提问来源于stack exchange,提问作者mob

