2016-09-22 96 views
0

我是Python的初學者。我正在嘗試使用pygame模塊來切換圖像。但我無法在python中移動圖像的位置。你能幫我理解我做錯了什麼嗎?無法在Pygame中移動圖像

import pygame, sys        
from pygame.locals import *      
pygame.init()         

image = pygame.image.load("ball.jpg") 
image = pygame.transform.scale(image, (100, 100)) 

imgrect = image.get_rect() 

Canvas = pygame.display.set_mode((500, 500)) 
pygame.display.set_caption('Text Input') 

imgrect.left = 200 
imgrect.top = 200 

Canvas.blit(image, imgrect) 
pygame.display.update() 

while True:          
    for event in pygame.event.get(): 

     if event.type == KEYDOWN :    
      if event.key == K_ESCAPE:   
       pygame.quit()     
       sys.exit()  
      if event.key == K_UP: 
       imgrect.top += 1 
      if event.key == K_DOWN: 
       imgrect.top -= 1 
+0

對於變量而不是'Canvas'使用小寫字母的名字(比如'canvas')。第二個用於類,如果你混合使用,它可能會混淆其他程序員。 –

回答

1

一個基本的遊戲循環應該做三件事:處理事件,更新和繪製。我看到更新矩形位置的邏輯,但不會在新位置重新繪製圖像。

我已經在遊戲循環的底部添加了線條來繪製場景。

while True: 
    # handle events 
    # update logic 

    # draw 
    Canvas.fill((0, 0, 0)) # Clears the previous image. 
    Canvas.blit(image, imgrect) # Draws the image at the new position. 
    pygame.display.update() # Updates the screen. 
+0

另外,如果背景是黑色以外的其他顏色,只需在'Canvas.fill((R,G,B))'中更改R,G,B值以匹配當前背景顏色。或者如果有背景圖像,用'Canvas.blit(bg_image,(0,0))'替換'Canvas.fill((0,0,0))'。 –