0
我試圖在Pygame中使用鍵盤控制的方法在屏幕上移動單個圖像,但它似乎是在這些位置創建重複項而不是移動原始圖像。爲什麼會發生這種情況,因爲圖像是在進入主循環之前創建的?Pygame創建多個對象,而不是隻移動一個
這裏是我的代碼:
import pygame, sys
from pygame.locals import *
pygame.init()
FPS = 30
fpsClock = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((600, 500), 0, 32)
pygame.display.set_caption('Animation')
posx = 10
posy = 10
class Hero():
def __init__(self):
self.x = posx
self.y = posy
def appearance(self):
return pygame.image.load('C:\\Users\\admin\\Desktop\\right.png')
def move_right(self):
self.x += 25
return self.x
def move_left(self):
self.x -= 25
return self.x
def move_up(self):
self.y -= 25
return self.y
def move_down(self):
self.y += 25
return self.y
new_hero = Hero() #create a Hero
item = new_hero.appearance() #create one reference
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
posx = new_hero.move_left()
elif event.key == pygame.K_RIGHT:
posx = new_hero.move_right()
elif event.key == pygame.K_UP:
posy = new_hero.move_up()
elif event.key == pygame.K_DOWN:
posy = new_hero.move_down()
DISPLAYSURF.blit(item, (posx, posy))
pygame.display.update()
fpsClock.tick(FPS)
在繪製新元素之前,您必須清除屏幕。即。填充黑色'DISPLAYSURF.fill((0,0,0))'或'blit'一些背景,將刪除'DISPLAYSURF'上的外掛 – furas
[簡單模板](https://github.com/furas/python-例子/ blob/master/pygame/__ template __/1__simple__.py)來組織代碼。 – furas