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

CodeHS环境下非箭头键(如E键)的按键检测问题求助

在CodeHS中检测非箭头按键(如E键)的解决方法

核心问题分析

你当前代码里检测E键的写法if e.key == "E"不生效,是因为CodeHS的按键事件对象中,字母键的key属性值是小写字符串,对应E键的是"e"而非"E"。

修正后的按键检测代码

同时清理代码里的语法错误(多余的反引号、无参数的无效回调),修正后的完整代码如下:

from browser import timer

cursor = Rectangle(10, 20)
screen = []
textlist = []
boole = [True] 
username = "EDOS"

def init_screen():
    background = Rectangle(get_width(), get_height())
    screen.append(background)
    txt = Text("Welcome to EdOS")
    txt.set_font("12pt Courier New")
    txt.set_color(Color.white)
    txt.set_position(0, 12)
    usertext = Text(f"{username}@EdPC:/$")
    usertext.set_font("10pt Courier New")
    usertext.set_position(0, get_height() - 10)
    usertext.set_color(Color.white)
    screen.append(usertext)
    screen.append(txt)
    print(screen)

def add_screen():
    screen_copy = screen.copy()
    for i in range(len(screen_copy)):
        add(screen_copy[i])
        if type(screen_copy[i]) == Text:
            item = screen_copy[i]
            screen.remove(item)
            textlist.append(item)

def init_text_input():
    cursor.set_color(Color.white)
    cursor.set_position(get_width() / 5 + 15, get_height() - 25)
    add(cursor)

def blink_cursor(boole):
    if boole[0]:
        cursor.set_color(Color.white)
    else:
        cursor.set_color(Color.black)

def timer_to_blinker():
    boole[0] = not boole[0]
    blink_cursor(boole)
    
def input_handler(e):
    if e.key == "ArrowLeft":
        print("Left Arrow key pressed.")
    if e.key == "ArrowRight":
        print("Right Arrow key pressed.")
    if e.key == "ArrowUp":
        print("Up Arrow key pressed.")
    if e.key == "ArrowDown":
        print("Down Arrow key pressed.")
    # 改为小写的"e"匹配
    if e.key == "e":
        print("E key pressed.")

def kernel():
    init_screen()
    add_screen()
    init_text_input()

init_text_input()
timer_id = timer.set_interval(timer_to_blinker, 500) 

kernel()
add_key_down_handler(input_handler)

额外实用技巧

  1. 若不确定其他按键的正确标识,可以在input_handler中添加print(e.key)语句,按下目标按键后查看控制台输出的字符串值。
  2. CodeHS的按键事件遵循简化版DOM KeyboardEvent标准:字母键统一返回小写字符串,特殊键(如回车、空格)使用标准名称(如"Enter"、"Space")。

内容的提问来源于stack exchange,提问作者Soldrion

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 12:32:26