2017-10-18 117 views
0

我正在嘗試創建一個簡單的遊戲,其中用戶在屏幕上移動「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)* 
+0

[蟒蛇按鍵簡單的遊戲(https://stackoverflow.com/questions/44002474/python-keypress-simple-game) – bendl

+0

檢測按鍵的可能的複製不同,這取決於你是什麼操作系統使用。這就是爲什麼人們通常使用庫代碼來做它,所以他們不需要擔心雜亂的細節。 –

回答

1

嘗試使用pygame的!它擔心所有的細枝末節,併爲您提供了一個簡單的界面,用戶輸入的遊戲:

https://www.pygame.org/news

(我想說的是,這是可能阻力最小的路徑。我可能是錯的)

+0

OP提到他們已經看過Pygame。但也許他們應該再看一眼。 ;) –

+0

是的,這就是我所指的這個答案。 –

0

我相信這樣做你描述使用的是什麼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() 

窗口上首先點擊使它監聽器。然後,您可以單獨向下按或按住它(稍微延遲一段時間後),它會自動重複。

enter image description here