2016-03-05 154 views
2

你好,我是pygame的新手。 当我试图将我的rect向右或向左移动时。矩形不会从一个位置移动到另一个位置,而是向右或向左扩展/延伸。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() 

enter image description here

请参阅上面的图像。 按下右键或左键后的样子。

回答

3

绘图前使用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。如果你宣布它全部上限,可能会更好。 RED。因为它是一个全球常数,如PEP-8所示。

1
import pygame, sys, time 

pygame.init() 
red = (255, 0, 0) 

gameDisplay = pygame.display.set_mode((800, 600)) 
background = pygame.Surface(gameDisplay.get_size()) 
background = background.convert() 
background.fill((0,0,0)) 

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]) 


    background.fill((0,0,0)) 
    pygame.draw.rect(background, red, [move_x, move_y, 10, 10]) 

    gameDisplay.blit(background, (0, 0)) 
    pygame.display.flip()