You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中检测上下箭头按键输入并处理HiLo游戏逻辑?

Fixing Arrow Key Input for Your Python HiLo Game

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 > x are missing the actual key press check (you need to verify if the user pressed UP or DOWN first).
  • Unused getch(): You call getch() but don’t save or check its return value to identify which key was pressed.
  • Incorrect exit: exit is a function, so you need to call it as exit() 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:

  1. Pygame event handling: We use pygame.event.get() to listen for KEYDOWN events, which reliably detects UP (K_UP) and DOWN (K_DOWN) arrow keys across Windows, Mac, and Linux.
  2. 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.
  3. Proper cleanup: We call pygame.quit() before exiting to free up system resources, and use exit() correctly to terminate the program.
  4. Exact 10 rounds: Changed the loop condition to counter <10 so the game runs exactly 10 times (your original <=10 would 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ı

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:17:03