【发布时间】:2020-05-27 13:05:05
【问题描述】:
我是 Python 的初学者,我正在尝试想出一个函数来在 Pygame 的帮助下绘制一个在屏幕上水平和垂直移动的正方形。当我们单击键盘上的箭头时,正方形应该会移动。
我的问题:虽然正方形显示在屏幕上,但它根本不动,但 Python 没有显示任何类型的错误。
有人知道缺少什么吗?提前致谢!
这是我目前所写的:
import pygame
altura_tela = 600
largura_tela = 800
tela = pygame.display.set_mode((largura_tela, altura_tela))
vermelho = (255, 0, 0)
altura_quadrado = 100
largura_quadrado = 100
def desenhaQuadrado(quadrado):
pygame.draw.rect(tela, vermelho, (350,250,largura_quadrado, altura_quadrado))
def posicaoquadrado(quadradoPos):
tela.blit(quadrado, (quadradoPos[0],quadradoPos[1]))
def moveQuadrado(teclas, quadradoPos):
if teclas[0] and quadradoPos[1] > 0:
quadradoPos[1] -= 20
elif teclas[2] and quadradoPos[1] < 420:
quadradoPos[1] += 20
if teclas[1] and quadradoPos[0] > 0:
quadradoPos[0] -= 20
elif teclas[3]and quadradoPos[0] < 570:
quadradoPos[0] += 20
return quadradoPos
def main():
pygame.init()
teclas = [False, False, False, False]
quadradoPos = [350,250]
pygame.display.set_caption('Movimentação do Quadrado')
terminou = False
while not terminou:
for event in pygame.event.get():
if event.type == pygame.QUIT:
terminou = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
teclas[0] = True
elif event.key == pygame.K_DOWN:
teclas[1] = True
elif event.key == pygame.K_LEFT:
teclas[2] = True
elif event.key == pygame.K_RIGHT:
teclas[3] = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
teclas[0] = False
elif event.key == pygame.K_DOWN:
teclas[1] = False
elif event.key == pygame.K_LEFT:
teclas[2] = False
elif event.key == pygame.K_RIGHT:
teclas[3] = False
quadradoPos = moveQuadrado(teclas, quadradoPos)
desenhaQuadrado(quadradoPos)
pygame.display.update()
pygame.display.quit()
pygame.quit()
if __name__ == '__main__':
main()
【问题讨论】: