Racket GUI画布按键事件如何忽略大小写?新手游戏开发求助
Hey there! Since you're new to Racket and building a game with the GUI canvas, making key presses case-insensitive is a common and straightforward fix. Here's how to adjust your code:
Step 1: Create a Normalization Helper Function
First, write a small function to convert any character key code to a consistent case (we’ll use lowercase here—uppercase works too if you prefer). Non-character keys (like arrow keys, spacebar, or function keys) stay unchanged since they don’t have case variants.
(define (normalize-key-code key-code) (cond [(char? key-code) (char-downcase key-code)] [else key-code])) ; Leave non-character keys as-is
Step 2: Update Your on-char Method
Modify your canvas’s on-char override to use this helper function for both key presses and releases. This ensures that both #\a and #\A are treated as the same key, whether you’re pressing or releasing it.
Here’s the updated code:
(define game-canvas% (class canvas% (super-new) ; Don't forget to call super-new if you haven't already! (define/override (on-char ke) (let* ([key-code (send ke get-key-code)] [normalized-code (normalize-key-code key-code)]) (case key-code ['release (let ([release-code (send ke get-key-release-code)]) (send controller key-up (normalize-key-code release-code)))] [else (send controller key-down normalized-code)])))) (define dinosaur-controller% (class controller% ; Your controller implementation here... (super-new)))
How It Works
- For any character key (like letters),
char-downcaseconverts it to lowercase. So pressingShift+A(which returns#\A) will be normalized to#\a, matching a regular lowercaseapress. - Non-character keys (like
'upfor the up arrow, or#\space) aren’t affected—they pass through the helper function unchanged, so your game’s other key controls will work as expected.
This approach keeps your code clean and focused, and it’s easy to adjust if you ever need to tweak the case handling later.
内容的提问来源于stack exchange,提问作者Elle Sullivan

