2017-07-26 44 views
2

我一直在試圖遵循這個老的YouTube教程,如何使用pygame在Python中創建一個遊戲。我遇到了一個殘缺的地方,無法讓按鍵動作奏效。教程中,我一直在關注:https://www.youtube.com/watch?v=g4E9iq0BixA&t=228sPygame鍵按下不起作用

我按W,A,S,d ......但沒有任何反應在屏幕

import pygame 
import sys 
# import math 


class Cam: 
    def __init__(self, pos=(0, 0, 0), rot=(0, 0)): 
     self.pos = list(pos) 
     self.rot = list(rot) 

    def update(self, dt, key): 
     s = dt * 10 

     if key[pygame.K_q]: self.pos[1] += s 
     if key[pygame.K_e]: self.pos[1] -= s 

     if key[pygame.K_w]: self.pos[2] += s 
     if key[pygame.K_s]: self.pos[2] -= s 
     if key[pygame.K_a]: self.pos[0] -= s 
     if key[pygame.K_d]: self.pos[0] += s 

pygame.init() 
w, h = 400, 400; cx, cy = w//2, h//2 
screen = pygame.display.set_mode((w, h)) 
clock = pygame.time.Clock() 

verts = (-1, -1, -1), (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1) 
edges = (0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7) 

cam = Cam((0, 0, -5)) 

while True: 
    dt = clock.tick()/1000 

    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: pygame.quit(); sys.exit() 

     screen.fill((255, 255, 255)) 

    for edge in edges: 

     points = [] 
     for x, y, z in (verts[edge[0]], verts[edge[1]]): 

      x -= cam.pos[0] 
      y -= cam.pos[1] 
      z -= cam.pos[2] 

      f = 200/z 
      x, y = x*f, y*f 
      points += [(cx + int(x), cy + int(y))] 
     pygame.draw.line(screen, (0, 0, 0,), points[0], points[1], 1) 

    pygame.display.flip() 

    key = pygame.key.get_pressed() 
    cam.update(dt, key) 
+0

這可能是因爲它們的位置定義是以'tuple'的形式出現的,逗號分隔括號中的元素列表,'(a,b,c)',創建後無法更改,意思是你會想要使用一個列表,因爲列表的值可以改變。 –

+0

有關元組的進一步閱讀,請參閱SO [元組文檔](https://stackoverflow.com/documentation/python/927/tuple#t = 201707261900111004926) –

+0

@Professor_Joykill我會嘗試你的解決方案,謝謝你的回答.. – Brandon

回答

0

,而真:

dt = clock.tick()/1000 

的問題可能在這裏。如果您調試代碼並查看dt中存儲的時鐘滴答的值,您會發現該值爲0.因此,當您按下鍵盤上的某個鍵時,它不會執行任何操作,因爲

s = dt * 10當dt:= 0 - > s = 0時。

我的解決方案是定義一個模擬fps的靜態值,試圖從時鐘滴答聲中獲取。定義值under.000喜歡:

,而真:

**dt = .0009** 

這會奏效。 (: