Python 如何在pygame中移动矩形
我想在Pygame中制作一个移动的矩形。我知道我首先需要使用pygame.draw.rect,在其中我有。我暂时使用在线IDE,Repl.it。我只需要确保这个代码是正确的Python 如何在pygame中移动矩形,python,pygame,repl.it,Python,Pygame,Repl.it,我想在Pygame中制作一个移动的矩形。我知道我首先需要使用pygame.draw.rect,在其中我有。我暂时使用在线IDE,Repl.it。我只需要确保这个代码是正确的 import pygame, sys pygame.init() screen = pygame.display.set_mode((1000,600)) x = 500 y = 300 white = (255,255,255) player = pygame.draw.rect(screen, white, (x,y,5
import pygame, sys
pygame.init()
screen = pygame.display.set_mode((1000,600))
x = 500
y = 300
white = (255,255,255)
player = pygame.draw.rect(screen, white, (x,y,50,40))
while True:
for event in pygame.event.get():
if pygame.event == pygame.QUIT:
pygame.QUIT
sys.exit()
if pygame.event == pygame.KEYDOWN:
if pygame.key == pygame.K_LEFT:
x -= 5
if pygame.event == pygame.K_RIGHT:
x += 5
pygame.display.update()
感谢您的输入。您的代码即将运行
有几个地方你检查了事件的错误部分,大多数情况下你在多个地方都有相同的错误
此外,当坐标发生变化时,您也不会重新绘制矩形
import pygame, sys
pygame.init()
screen = pygame.display.set_mode((1000,600))
x = 500
y = 300
black = ( 0, 0, 0)
white = (255,255,255)
while True:
# Handle Events
for event in pygame.event.get():
if event.type == pygame.QUIT: # <<-- HERE use event.type
pygame.quit() # <<-- HERE use pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN: # <<-- HERE use event.type
if event.key == pygame.K_LEFT: # <<-- HERE use event.key
x -= 5
elif event.key == pygame.K_RIGHT: # <<-- HERE use event.key
x += 5
# Reapint the screen
screen.fill( black ) # erase old rectangle
player = pygame.draw.rect(screen, white, (x,y,50,40)) # draw new rectangle
pygame.display.update()
我已经对pygame.event做了相同的更改。但它仍然不起作用。需要将pygame.event更改为event.type。谢谢: