从Python获取按键输入

2024-10-02 12:22:53 发布

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

我正在尝试创建一个简单的游戏,用户在屏幕上移动一个“X”来尝试得到一个“O”。它需要我使用箭头(上,下,左,右),我不知道如何编程。我在网上看了很多例子,比如curses,getch,sys,pygame,但不是太复杂就是不能在我的电脑上运行。你知道吗

有人能提供一个完整的例子和解释如何在Python中检测按键,比如。还需要游戏屏幕的帮助,特别是在某个位置打印一些东西,比如说lie(0,0),有点像turtle在(0,0)处开始绘图:

userposy = 0 (y position of the 'X')
*print 'X' at (0, userposy)*
while True:
    char = *detect what key is pressed*
    if char == *down arrow*:
        userposy -= 1.
    *print 'X' at (0, userposy)*

Tags: 用户游戏屏幕编程sys箭头pygameat
2条回答

我相信这正是您使用Python turtle所描述的:

from turtle import Turtle, Screen

FONT_SIZE = 24
FONT = ('Arial', FONT_SIZE, 'normal')

def tortoise_down(distance=1):
    screen.onkeypress(None, "Down Arrow")  # disable event hander in event hander
    tortoise.forward(distance)
    display.undo()  # erase previous distance
    display.write('X at {:.1f}'.format(tortoise.ycor()), align='center', font=FONT)
    screen.onkeypress(tortoise_down, "Down")  # (re)enable even handler

screen = Screen()
screen.setup(500, 500)

display = Turtle(visible=False)
display.speed('fastest')
display.penup()
display.goto(0, screen.window_height() / 2 - FONT_SIZE * 2)
display.write('', align='center', font=FONT)  # garbage for initial .undo()

tortoise = Turtle('turtle')
tortoise.speed('fastest')
tortoise.setheading(270)
tortoise.penup()

tortoise_down(0)  # initialize display and event handler

screen.listen()
screen.mainloop()

首先单击窗口使其成为侦听器。然后你可以单独按下或按住向下箭头键(稍有延迟后),它会自动重复。你知道吗

enter image description here

尝试使用Pygame!它关注所有的细节,并为您提供了一个简单的游戏用户输入界面:

https://www.pygame.org/news

(我想说的是,这可能是阻力最小的路径。但我可能错了)

相关问题 更多 >

    热门问题