2016-12-04 82 views
0

我正在努力在pygame的屏幕上移动一个绘制的矩形,我试图创建一个Snake游戏。我对Python和面向对象编程一般都很陌生,所以这可能是一个愚蠢的错误。下面的代码。Python PyGame移动矩形

#X coordinate of snake 
lead_x = 300 


#sets window position on screen 
import os 
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (320,240) 


#imports pygame module 
import sys, pygame 

#initialises pygame module 
pygame.init() 

#changes background colour to green 
background_colour = 155, 188, 15 
blue =(0,0,255) 
red = (100,40,20) 
#sets screen size 
screen = pygame.display.set_mode((640, 480)) 

#changes the background colour 
screen.fill(background_colour) 

#creates rectangle on the screen 
pygame.draw.rect(screen, blue, [lead_x,lead_x,10,10]) 



#updates display to show new background colour 
pygame.display.update() 

#Sets the window title to 'Python' 
pygame.display.set_caption('Python') 

#closes the window when user presses X 
running = True 



#if cross is clicked set running = False 
while running: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      running = False 

      #Controls 

     if event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_LEFT: 
       lead_x -= 10 

      if event.key == pygame.K_RIGHT: 
       lead_x += 10 


    #if running = False close pygame window   
if running == False: 
    pygame.quit() 

回答

1

您需要将pygame.draw.rect(screen, blue, [lead_x, lead_y, 10, 10])放在您的游戏循环中。截至目前,您只需在屏幕上绘制矩形一次,这就是程序的开始。您想要连续在不同的lead_xlead_y位置绘制矩形,以便在屏幕上移动矩形。

您还应该在循环中放置一个screen.fill(background_colour)(以清除上一张图)和pygame.display.update()(以更新更改)。

编辑:我注意到的东西:你可能想创建一个变量lead_y和使用pygame.draw.rect(screen, blue, [lead_x, lead_y, 10, 10])所以你不要对角每一次移动。

+0

感谢您的帮助,我会尝试这些事情,看看文档。 – BoJ

+0

仍然有麻烦移动绘制矩形运行循环,并把这两件事情,但现在我得到的是一个没有矩形的空白屏幕。 – BoJ

+0

'pygame.draw.rect(screen,blue,[lead_x,lead_y,10,10])'''后面加了'screen.fill(background_colour)'?只要翻转他们的立场,它应该工作。在绘制任何东西之前,您通常需要'screen.fill(background_colour)'。 –