我只想左右移动一个块,但现在不知道为什么keydown代码没有通过。当我打开程序时,它只显示了“坦克”。在它的位置,但你不能用左或右键移动它。
import pygame, sys
from pygame.locals import *
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
TANK_SIZE = 20
BLACK = (0 ,0 ,0 )
WHITE = (255,255,255)
def drawArena():
DISPLAYSURF.fill(BLACK)
def drawTank(tank):
pygame.draw.rect(DISPLAYSURF, WHITE, tank)
def main():
pygame.init()
global DISPLAYSURF
DISPLAYSURF = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('Tanks')
tankX = 200
tankY = 200
tank = pygame.Rect(tankX, tankY, TANK_SIZE, TANK_SIZE)
drawArena()
drawTank(tank)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
tankX -= 20
if event.key == pygame.K_RIGHT:
tankX += 20
drawArena()
drawTank(tank)
pygame.display.update()
if __name__ == '__main__':
main()
答案 0 :(得分:0)
这是因为更新的tankX
值不会影响tank
对象。有很多方法可以使它发挥作用。例如,在while True
循环中插入tank的重新初始化:
import pygame, sys
from pygame.locals import *
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
TANK_SIZE = 20
BLACK = (0 ,0 ,0 )
WHITE = (255,255,255)
def drawArena():
DISPLAYSURF.fill(BLACK)
def drawTank(tank):
pygame.draw.rect(DISPLAYSURF, WHITE, tank)
def main():
pygame.init()
global DISPLAYSURF
DISPLAYSURF = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('Tanks')
tankX = 200
tankY = 200
tank = pygame.Rect(tankX, tankY, TANK_SIZE, TANK_SIZE)
drawArena()
drawTank(tank)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
tankX -= 20
if event.key == pygame.K_RIGHT:
tankX += 20
tank = pygame.Rect(tankX, tankY, TANK_SIZE, TANK_SIZE)
drawArena()
drawTank(tank)
pygame.display.update()
if __name__ == '__main__':
main()
答案 1 :(得分:0)
您不应更新tankX和tankY变量,因为这不会影响tank
Rect对象。您不需要重新初始化tank
对象,因为这可能是浪费资源。更有效的方法是使用它的move_ip()函数直接更新tank
对象的x和y值。
在你的主循环......
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.type == pygame.K_LEFT:
tank.move_ip(-20, 0)
if event.type == pygame.K_RIGHT:
tank.move_ip(20, 0)
drawArena()
drawTank(tank)
pygame.display.update()