2016-12-04 23 views
0

私はpygameで描画された矩形を画面上で動かすのに苦労しています。私はSnakeゲームを作成しようとしています。私はPythonとオブジェクト指向のプログラミングにはとても新しいので、おそらく愚かな間違いです。以下のコード。Python PyGame Moving Rectangle

#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])を入れる必要があります。現時点では、画面上に1回だけrectを描画しています。これはプログラムの最初です。四角形を画面上で動かすために、別のlead_xlead_yの位置に連続的に矩形を描画したいとします。

また、ループ内にscreen.fill(background_colour)(前の図を消去する)とpygame.display.update()(変更を更新する)を配置する必要があります。

EDIT:私は何かに気づいた:あなたはおそらく変数lead_yを作成するので、あなたが斜めにするたびに移動しないpygame.draw.rect(screen, blue, [lead_x, lead_y, 10, 10])を使用します。

+0

お手数をおかけしていただきありがとうございます。これらのことを試してみて、ドキュメントをご覧ください。 – BoJ

+0

実行中のループに描画矩形を移動して、その2つのものを入れても問題はありませんが、今はすべて矩形のない空白の画面になります。 – BoJ

+0

'pygame.draw.rect(screen、blue、[lead_x、lead_y、10、10])'の後ろに 'screen.fill(background_colour)'を入れましたか?ちょうど彼らのポジションを反転し、それは動作するはずです。何かを描画する前に、通常は 'screen.fill(background_colour)'が必要です。 –