请非常感谢任何帮助。 我正在用Pygame编写游戏,并在创建了我需要的所有类和方法之后。当我运行游戏时,我看到我的游戏的五个外星人物从屏幕的左侧连接在一起,然后我才真正看到我想要显示的代码(外星人在屏幕上随机移动)。
这是我的代码:
class Alien():
def __init__(self, image):
self.x = random.randrange(20,width - 20)
self.y = random.randrange(-200, -20)
self.speed = random.randint(1, 5)
self.image = pygame.image.load(os.path.join("../images", image)).convert_alpha()
self.rect = self.image.get_rect()
def move_down(self):
self.rect.y += self.speed
def draw(self, screen):
screen.blit(self.image, self.rect)
其实施
for i in range (20):
aliens = Alien("alien.png")
enemies.append(aliens)
done = False
while done == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(white)
for i in range(len(enemies)):
enemies[i].move_down()
enemies[i].draw(screen)
enemies[i].check_landed()
pygame.display.flip()
clock.tick(30)
注意:为清楚起见,我删除了一些代码。 结果
答案 0 :(得分:2)
您将外星人的位置存储在self.x
和self.y
字段中,但为了绘制它们,您实际上不会使用self.x
和self.y
,但是self.rect
。
您可以致电self.rect
来创建self.image.get_rect()
,当您在get_rect()
上致电Surface
时,Rect
的排名始终为(0, 0)
}。
因此x
坐标始终为0
,因此它们都位于屏幕的左侧。
我建议您将代码重写为:
class Alien():
# pass the Surface to the instance instead of the filename
# this way, you only load the image once, not once for each alien
def __init__(self, image):
self.speed = random.randint(1, 5)
self.image = image
# since we're going to use a Rect of drawing, let's use the
# same Rect to store the correct position of the alien
self.rect = self.image.get_rect(top=random.randrange(-200, -20), left=random.randrange(20,width - 20))
def move_down(self):
# the Rect class has a lot of handy functions like move_ip
self.rect.move_ip(0, self.speed)
def draw(self, screen):
screen.blit(self.image, self.rect)
# load the image once. In more complex games, you usually
# want to abstract the loading/storing of images
alienimage = pygame.image.load(os.path.join("../images", 'alien.png')).convert_alpha()
for _ in range (20):
aliens = Alien(alienimage)
enemies.append(aliens)
done = False
while done == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(white)
# just use a "regular" for loop to loop through all enemies
for enemy in enemies:
enemy.move_down()
enemy.draw(screen)
enemy.check_landed()
pygame.display.flip()
clock.tick(30)
您可以更进一步,使用Sprite
- 和Group
- 类来进一步概括您的代码,但这是另一个主题。