【问题标题】:pygame group update method not workingpygame组更新方法不起作用
【发布时间】:2018-04-25 13:23:00
【问题描述】:

我正在创建一个类似于 Space Invaders 的游戏,但精灵组更新方法不起作用。

pygame.sprite.Group.update 方法不会逐个更新列表中的对象,而是使列表中存储的所有对象都采用第一个对象的值。

设计外星人的班级:

class Alien(Sprite):
    def __init__(self,screen,ai):
        super().__init__()
        self.image = pygame.image.load("C:\\Users\\ozzy\\Desktop\\project alien invasion\\alien.bmp")
        self.screen = screen
        self.rect = self.image.get_rect()
        self.ai = ai
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height
        self.x = float(self.rect.x)

将舰队向右移动

def update(self):
    self.x += 3
    self.rect.x = self.x

创建舰队

def create_fleet(screen,ai,aliens,ship):    

    alien = Alien(screen,ai)
    alien_width = alien.rect.width
    alien_height = alien.rect.height
    number_alien_x = get_number_x(ai,alien_width)
    number_alien_y = get_number_y(ai,alien_height,ship)
    for alien_coloum in range(number_alien_y):
       for alien_row in range(number_alien_x):
          create_aliens(screen,ai,alien_width,aliens,alien_row,alien_coloum)                            

获取可以在显示器上显示的行数

def get_number_y(ai,alien_height,ship):

    available_space_y = (ai.height - ship.rect.height -(3 * alien_height))
    number_of_rows = int(available_space_y / (2 * alien_height))
    return number_of_rows

获取屏幕上可以容纳的列数

def get_number_x(ai,alien_width):

    available_space_x = ai.width - 2 * alien_width
    number_of_aliens = int(available_space_x /(2 * alien_width))
    return number_of_aliens

将舰队存储在组中

def create_aliens(screen,ai,alien_width,aliens,alien_row,alien_coloum):

    alien = Alien(screen,ai)
    alien_x = alien_width + 2 * alien_width * alien_row
    alien.rect.x = alien_x
    alien.rect.y = alien.rect.height + 2 * alien.rect.height * alien_coloum
    aliens.add(alien)

调用组的更新方法

def update_aliens(aliens):


    for a in aliens.sprites():
       print(a.rect.x)
    aliens.update()
    #the update method cause the x co ordintes to be same first object
    for a in aliens.sprites():
       print(a.rect.x)


#main method
aliens = Group()
create_fleet(screen,ai,aliens,ship)
while True:
   update_aliens(aliens)

在调用更新方法之前,组中的外星人具有不同的 x 坐标,但在更新方法之后,它们都具有相同的 x 坐标。

有人可以解释什么是错的吗?该函数是否会产生某种副作用?

【问题讨论】:

标签: python pygame


【解决方案1】:

update() 方法中定义self.x,而不是__init__() 方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-22
    • 2016-12-07
    • 1970-01-01
    • 2017-06-21
    • 2017-04-18
    • 1970-01-01
    • 2019-08-16
    • 2018-07-27
    相关资源
    最近更新 更多