运行python游戏,无需等待即可捕获击键

2024-04-25 21:05:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python编写一个游戏(在终端中,不是图形化的),它捕获按键输入,但仍然保持运行,不等待按键。 例如,我想上下移动球棒,只需按箭头键。但是,当我不按任何按钮时,游戏必须继续,即弹起球

不使用tkinter或pygame等额外模块,可以轻松完成这项任务吗?我的意思是,有什么东西可以像“按下键=按下键”(虚构的一句话)一样

# Sample functions
def print_board(ball_pos, bat_pos):
    # Print the entire board

def move_ball(ball_pos, increment):
    # Check boundaries, if hit wall, reverse increment
    ## Code comes here...
    # Move ball
    ball_pos[0] += increment[0]
    ball_pos[1] += increment[2]
    return ball_pos

def move_bat(bat_pos_y, increment_y):
    # Check boundaries, if hit wall, do not increment
    ## Code comes here...
    bat_pos_y += increment_y
    return bat_pos_y

# Sample main routine
## Initialisation comes here...
## Game routine
while True:
     bat_inc = 0
     # Get a keystroke, without waiting
     ##key_pressed = get_key
     if (key_pressed == UP):
         bat_inc = -1
     elif (key_pressed == DOWN):
         bat_inc = 1     
     move_ball(ball, inc)
     move_bat(bat, bat_inc)
     print_board(ball, bat)

Tags: keyposboard游戏moveifheredef