2017-07-26 42 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** 

这会奏效。 (: