获取Python用户的按键输入
我正在尝试创建一个简单的游戏,其中用户在屏幕上移动“X”以尝试获取“O”。它要求我使用箭头(上,下,左,右),我不知道如何编程。我在网上看了一下,看到了各种各样的例子,比如curses,getch,sys,pygame,但是它们都太复杂了,或者它们不能在我的电脑上运行。获取Python用户的按键输入
有人可以提供一个完整的例子和解释如何检测在Python中的按键,像。还需要有游戏画面的帮助,特别是,印刷的东西在某个位置,谎言(0,0),有点像甲鱼如何开始在(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)*
尝试使用pygame的!它担心所有的细枝末节,并为您提供了一个简单的界面,用户输入的游戏:
(我想说的是,这是可能阻力最小的路径。我可能是错的)
OP提到他们已经看过Pygame。但也许他们应该再看一眼。 ;) –
是的,这就是我所指的这个答案。 –
我相信这样做你描述使用的是什么Python的龟:
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()
窗口上首先点击使它监听器。然后,您可以单独向下按或按住它(稍微延迟一段时间后),它会自动重复。
[蟒蛇按键简单的游戏(https://*.com/questions/44002474/python-keypress-simple-game) – bendl
检测按键的可能的复制不同,这取决于你是什么操作系统使用。这就是为什么人们通常使用库代码来做它,所以他们不需要担心杂乱的细节。 –