你好,我是 pygame 的新手。
当我尝试向右或向左移动我的矩形
时。矩形不会从一个位置移动到另一个位置,而是向右或向左扩展/延伸。
为什么?
import pygame, sys, time
pygame.init()
red = (255, 0, 0)
gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption('MyGame')
move_x = 200
move_y = 200
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
move_x -= 10
if event.key == pygame.K_RIGHT:
move_x += 10
# pygame.Rect.move(10, 10)
# gameDisplay.fill(white, rect=[move_x, move_y, 10, 100])
pygame.draw.rect(gameDisplay, red, [move_x, move_y, 10, 10])
pygame.display.update()
pygame.display.flip()
请参见上图。 按左右键后的样子。
最佳答案
在绘制之前使用surface.fill。
我使用的[0, 0, 0]
在RGB代码中是黑色的。你应该声明类似的内容
BLACK = (0, 0, 0)
作为常数以避免重复。因此,请更改它并像上面一样使用它。
import pygame, sys, time
pygame.init()
red = (255, 0, 0)
gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption('MyGame')
move_x = 200
move_y = 200
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
move_x -= 10
if event.key == pygame.K_RIGHT:
move_x += 10
# pygame.Rect.move(10, 10)
gameDisplay.fill([0,0,0]) # The line added.
pygame.draw.rect(gameDisplay, red, [move_x, move_y, 10, 10])
pygame.display.update()
pygame.display.flip()
小心不要在 fill
方法之前绘制任何内容,它会被删除,因为您用其他内容填充了屏幕。
编辑:我刚刚意识到您已经定义了red
。如果您声明全部大写可能会更好。红色。因为它是一个全局常量 PEP-8建议。
关于python - Pygame 的矩形不移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35818505/