如何在Python中检测上下箭头按键输入并处理HiLo游戏逻辑?
Hey there! Let's get those arrow keys working smoothly for your HiLo game. I noticed you already imported pygame—perfect, since it’s a reliable cross-platform way to handle keyboard events, and we can leverage that to fix your input issue. Let’s walk through the problems in your current code and build a working solution step by step.
First, let’s spot the key issues in your existing code:
- Syntax errors: Lines like
if and y > xare missing the actual key press check (you need to verify if the user pressed UP or DOWN first). - Unused
getch(): You callgetch()but don’t save or check its return value to identify which key was pressed. - Incorrect exit:
exitis a function, so you need to call it asexit()to terminate the program properly. - Redundant code: You repeat the same logic for generating new numbers and printing messages across all four conditionals—we can simplify this a lot.
Here’s the fixed version using pygame for arrow key handling:
import random import pygame # Initialize pygame (required to capture keyboard events) pygame.init() # Create a minimal window (can be minimized; pygame needs a window to listen for events) screen = pygame.display.set_mode((100, 100)) pygame.display.set_caption("HiLo Game") name = input("Please enter your name: ") print(f"Welcome {name}") print(f"Okay {name}. We will now play a game called high or low. In order to play this game you have to be 18 or older") age = int(input("Please enter your age: ")) if age < 18: print("You are not old enough to play.") pygame.quit() exit() else: print(f"OK! You are {age}. You can play") x = random.randint(1, 9) y = random.randint(1, 9) print(f"Your first number is {x}.") counter = 0 truecounter = 0 falsecounter = 0 while counter < 10: # Adjusted to run exactly 10 rounds print("Press UP for high and DOWN for low.") # Wait for a valid arrow key press user_choice = None while user_choice is None: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: user_choice = "high" elif event.key == pygame.K_DOWN: user_choice = "low" # Check if the user's choice matches the actual number relationship correct = False if (user_choice == "high" and y > x) or (user_choice == "low" and y < x): correct = True truecounter += 1 print(f"Your answer is correct! The other number was {y}") else: falsecounter += 1 print(f"Ooops! You guessed wrong. The number was {y}") # Prepare for the next round x = random.randint(1, 9) y = random.randint(1, 9) print(f"Let's see if you can do it again. The number is {x}") counter += 1 # Clean up pygame and show final results pygame.quit() print(f"Congrats! You got {truecounter} out of 10!")
Key improvements explained:
- Pygame event handling: We use
pygame.event.get()to listen forKEYDOWNevents, which reliably detects UP (K_UP) and DOWN (K_DOWN) arrow keys across Windows, Mac, and Linux. - Simplified logic: Instead of four separate conditionals, we check if the user’s choice matches the actual number relationship in one line, then handle correct/incorrect outcomes once.
- Proper cleanup: We call
pygame.quit()before exiting to free up system resources, and useexit()correctly to terminate the program. - Exact 10 rounds: Changed the loop condition to
counter <10so the game runs exactly 10 times (your original<=10would have run 11 rounds).
Alternative for Windows-only using msvcrt:
If you prefer to stick with msvcrt instead of pygame, here’s how to detect arrow keys (note this only works on Windows):
import random from msvcrt import getch name = input("Please enter your name: ") print(f"Welcome {name}") print(f"Okay {name}. We will now play a game called high or low. In order to play this game you have to be 18 or older") age = int(input("Please enter your age: ")) if age < 18: print("You are not old enough to play.") exit() else: print(f"OK! You are {age}. You can play") x = random.randint(1, 9) y = random.randint(1, 9) print(f"Your first number is {x}.") counter = 0 truecounter = 0 falsecounter = 0 while counter < 10: print("Press UP for high and DOWN for low.") # Detect arrow keys: they send two bytes via getch() first_byte = getch() if first_byte in (b'\x00', b'\xe0'): second_byte = getch() if second_byte == b'H': # UP arrow code user_choice = "high" elif second_byte == b'P': # DOWN arrow code user_choice = "low" else: print("Please press UP or DOWN arrow!") continue else: print("Please press UP or DOWN arrow!") continue # Check correctness and update counters if (user_choice == "high" and y > x) or (user_choice == "low" and y < x): truecounter += 1 print(f"Your answer is correct! The other number was {y}") else: falsecounter += 1 print(f"Ooops! You guessed wrong. The number was {y}") # Prepare next round x = random.randint(1, 9) y = random.randint(1, 9) print(f"Let's see if you can do it again. The number is {x}") counter += 1 print(f"Congrats! You got {truecounter} out of 10!")
This works because arrow keys send two bytes when pressed with getch(): the first is either 0 or 224, and the second is H for UP, P for DOWN.
Either approach will get your arrow key input working as expected. Have fun playing your HiLo game!
内容的提问来源于stack exchange,提问作者Sedat Şıracı

