随机生成敌人pygame

时间:2014-05-10 11:33:33

标签: python random pygame

我一直试图创造一个类似于太空入侵者的小型pygame,我试图随机生成敌人,我所知道的是生成3个敌人,我手动将它们传递到屏幕上他们应该开始的地方,但这意味着如果它会杀死它不会reapear我希望他们一遍又一遍地回应。这是我的代码:

#!/usr/bin/env python

from helpers import *


class Space1(pygame.sprite.Sprite):
    def __init__(self, i):                      
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image("space.png", 10)
        self.dx = -5
        self.reset(i)

    def update(self, i):
        self.rect.top += self.dx
        if i == 1:
            if self.rect.top <= -600:
                self.__init__(i) 
        else:
            if self.rect.top <= -1200:
                self.__init__(i) 

    def reset(self, i):
        if i == 1:
            self.rect.top = 1
        else:
            self.rect.top = 300

class Space2(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image("space.png", 10)
        self.dx = -5
        self.reset()

    def update(self):
        self.rect.top += self.dx
        if self.rect.top <= -1200:
            self.__init__() 

    def reset(self):
        self.rect.top = 600

class Player(pygame.sprite.Sprite):

    def __init__(self):

        pygame.sprite.Sprite.__init__(self)

        self.image, self.rect = load_image('ship.gif', -1)
        self.x_dist = 5
        self.y_dist = 5
        self.lasertimer = 0
        self.lasermax = 5
        self.rect.centery = 400
        self.rect.centerx = 400

    def update(self):
        key = pygame.key.get_pressed()

        # Movement
        if key[K_UP]:
            self.rect.centery += -3
        if key[K_DOWN]:
            self.rect.centery += 3
        if key[K_RIGHT]:
            self.rect.centerx += 3
        if key[K_LEFT]:
            self.rect.centerx += -3

        # Lasers
        if key[K_SPACE]:
            self.lasertimer = self.lasertimer + 1
            if self.lasertimer == self.lasermax:
                laserSprites.add(Laser(self.rect.midtop))
                self.lasertimer = 0

        # Restrictions
        self.rect.bottom = min(self.rect.bottom, 600)
        self.rect.top = max(self.rect.top, 0)
        self.rect.right = min(self.rect.right, 800)
        self.rect.left = max(self.rect.left, 0)

class Laser(pygame.sprite.Sprite):
    def __init__(self, pos):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image("laser.png", -1)
        self.rect.center = pos

    def update(self):
        if self.rect.right > 800:
            self.kill()
        else:
            self.rect.move_ip(0, -15)

class Enemy(pygame.sprite.Sprite):
    def __init__(self, centerx):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image("alien.png", -1)
        self.rect = self.image.get_rect()
        self.dy = 8
        self.reset()

    def update(self):
        self.rect.centerx += self.dx
        self.rect.centery += self.dy
        if self.rect.top > 600:
            self.reset()

        # Laser Collisions    
        if pygame.sprite.groupcollide(enemySprites, laserSprites, 1, 1):
           explosionSprites.add(EnemyExplosion(self.rect.center))

        # Ship Collisions
        if pygame.sprite.groupcollide(enemySprites, playerSprite, 1, 1):
           explosionSprites.add(EnemyExplosion(self.rect.center))
           explosionSprites.add(PlayerExplosion(self.rect.center))

    def reset(self):
        self.rect.bottom = 0
        self.rect.centerx = random.randrange(0, 600)
        self.dy = random.randrange(5, 10)
        self.dx = random.randrange(-2, 2)

class EnemyExplosion(pygame.sprite.Sprite):
    def __init__(self, pos):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image("enemyexplosion.png", -1)
        self.rect.center = pos        
        self.counter = 0
        self.maxcount = 10

    def update(self):
        self.counter = self.counter + 1
        if self.counter == self.maxcount:
            self.kill()

class PlayerExplosion(pygame.sprite.Sprite):
    def __init__(self, pos):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image("enemyexplosion.png", -1)
        self.rect.center = pos        
        self.counter = 0
        self.maxcount = 10

    def update(self):
        self.counter = self.counter + 1
        if self.counter == self.maxcount:
            self.kill()
            exit()

def main():       
# Initialize Everything

    pygame.init()

    screen = pygame.display.set_mode((800, 600))

    pygame.display.set_caption('UoN Invaders')

# Create The Backgound

    background = pygame.Surface(screen.get_size())

    background = background.convert()

    background.fill((000, 000, 000))

# Display The Background

    screen.blit(background, (0, 0))

    pygame.display.flip()

# Start Music   

    music = pygame.mixer.music.load ("data/spacequest.mp3")
    pygame.mixer.music.play(-1)



# Initialize Game Objects
    global clock

    clock = pygame.time.Clock()

    i = 0
    i += 1

    space1 = Space1(i)
    space2 = Space2()
    global player

    player = Player()


# Render Objects
    # Space
    space1 = pygame.sprite.RenderPlain((space1))
    space2 = pygame.sprite.RenderPlain((space2))

    # Player
    global playerSprite   
    playerSprite = pygame.sprite.RenderPlain((player))

    # Enemy
    global enemySprites
    enemySprites = pygame.sprite.RenderPlain(())
    enemySprites.add(Enemy(200))
    enemySprites.add(Enemy(300))
    enemySprites.add(Enemy(400))    

    # Projectiles    
    global laserSprites
    laserSprites = pygame.sprite.RenderPlain(())   

    # Collisions   
    global enemyExplosion
    enemyExplosion = pygame.sprite.RenderPlain(())
    global playerExplosion
    playerExplosion = pygame.sprite.RenderPlain(())
    global explosionSprites
    explosionSprites = pygame.sprite.RenderPlain(())


# Main Loop

    going = True

    while going:

        clock.tick(60)



        # Input Events

        for event in pygame.event.get():

            if event.type == QUIT:

                going = False

            elif event.type == KEYDOWN and event.key == K_ESCAPE:

                going = False

        # Update
        space1.update(i)
        space2.update()
        player.update()
        enemySprites.update()
        laserSprites.update()
        enemyExplosion.update()
        playerExplosion.update()
        explosionSprites.update()



        screen.blit(background, (0, 0))


        # Draw
        space1.draw(screen) 
        space2.draw(screen)          
        playerSprite.draw(screen)
        enemySprites.draw(screen)
        laserSprites.draw(screen)
        enemyExplosion.draw(screen)
        playerExplosion.draw(screen)
        explosionSprites.draw(screen)


        pygame.display.flip()



    pygame.quit()

if __name__ == '__main__':

    main()

1 个答案:

答案 0 :(得分:0)

所以下面我决定只是注释掉我改变的地方,我也需要导入一个名为随机的新模块,以便轻松获得一个随机的地方让外星人/敌人在游戏中产生。

#!/usr/bin/env python

import random #as explained above
from helpers import *

class Space1(pygame.sprite.Sprite):
    def __init__(self, i):                      
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image("space.png", 10)
        self.dx = -5
        self.reset(i)

    def update(self, i):
        self.rect.top += self.dx
        if i == 1:
            if self.rect.top <= -600:
                self.__init__(i) 
        else:
            if self.rect.top <= -1200:
                self.__init__(i) 

    def reset(self, i):
        if i == 1:
            self.rect.top = 1
        else:
            self.rect.top = 300

class Space2(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image("space.png", 10)
        self.dx = -5
        self.reset()

    def update(self):
        self.rect.top += self.dx
        if self.rect.top <= -1200:
            self.__init__() 

    def reset(self):
        self.rect.top = 600

class Player(pygame.sprite.Sprite):

    def __init__(self):

        pygame.sprite.Sprite.__init__(self)

        self.image, self.rect = load_image('ship.gif', -1)
        self.x_dist = 5
        self.y_dist = 5
        self.lasertimer = 0
        self.lasermax = 5
        self.rect.centery = 400
        self.rect.centerx = 400

    def update(self):
        key = pygame.key.get_pressed()

        # Movement
        if key[K_UP]:
            self.rect.centery += -3
        if key[K_DOWN]:
            self.rect.centery += 3
        if key[K_RIGHT]:
            self.rect.centerx += 3
        if key[K_LEFT]:
            self.rect.centerx += -3

        # Lasers
        if key[K_SPACE]:
            self.lasertimer = self.lasertimer + 1
            if self.lasertimer == self.lasermax:
                laserSprites.add(Laser(self.rect.midtop))
                self.lasertimer = 0

        # Restrictions
        self.rect.bottom = min(self.rect.bottom, 600)
        self.rect.top = max(self.rect.top, 0)
        self.rect.right = min(self.rect.right, 800)
        self.rect.left = max(self.rect.left, 0)

class Laser(pygame.sprite.Sprite):
    def __init__(self, pos):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image("laser.png", -1)
        self.rect.center = pos

    def update(self):
        if self.rect.right > 800:
            self.kill()
        else:
            self.rect.move_ip(0, -15)

class Enemy(pygame.sprite.Sprite):
    def __init__(self, centerx):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image("alien.png", -1)
        self.rect = self.image.get_rect()
        self.dy = 8
        self.reset()

    def update(self):
        self.rect.centerx += self.dx
        self.rect.centery += self.dy
        if self.rect.top > 600:
            self.reset()

        # Laser Collisions    
        if pygame.sprite.groupcollide(enemySprites, laserSprites, 1, 1):
           explosionSprites.add(EnemyExplosion(self.rect.center))
           ###################################################
           ###---LOOK HERE - I've added two lines here  ---###
           ###---First you need to replace this sprite  ---###
           ###---before removing it, then you need to   ---###
           ###---remove this sprite from the group      ---###
           ###################################################
           enemySprites.add(Enemy(random.randint(1, 800))  ###--- add new sprite with random position between 1 and 800
           self.remove() ###--- remove this sprite from the group

        # Ship Collisions
        if pygame.sprite.groupcollide(enemySprites, playerSprite, 1, 1):
           explosionSprites.add(EnemyExplosion(self.rect.center))
           explosionSprites.add(PlayerExplosion(self.rect.center))

    def reset(self):
        self.rect.bottom = 0
        self.rect.centerx = random.randrange(0, 600)
        self.dy = random.randrange(5, 10)
        self.dx = random.randrange(-2, 2)

class EnemyExplosion(pygame.sprite.Sprite):
    def __init__(self, pos):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image("enemyexplosion.png", -1)
        self.rect.center = pos        
        self.counter = 0
        self.maxcount = 10

    def update(self):
        self.counter = self.counter + 1
        if self.counter == self.maxcount:
            self.kill()

class PlayerExplosion(pygame.sprite.Sprite):
    def __init__(self, pos):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image("enemyexplosion.png", -1)
        self.rect.center = pos        
        self.counter = 0
        self.maxcount = 10

    def update(self):
        self.counter = self.counter + 1
        if self.counter == self.maxcount:
            self.kill()
            exit()

def main():       
# Initialize Everything

    pygame.init()

    screen = pygame.display.set_mode((800, 600))

    pygame.display.set_caption('UoN Invaders')

# Create The Backgound

    background = pygame.Surface(screen.get_size())

    background = background.convert()

    background.fill((000, 000, 000))

# Display The Background

    screen.blit(background, (0, 0))

    pygame.display.flip()

# Start Music   

    music = pygame.mixer.music.load ("data/spacequest.mp3")
    pygame.mixer.music.play(-1)



# Initialize Game Objects
    global clock

    clock = pygame.time.Clock()

    i = 0
    i += 1

    space1 = Space1(i)
    space2 = Space2()
    global player

    player = Player()


# Render Objects
    # Space
    space1 = pygame.sprite.RenderPlain((space1))
    space2 = pygame.sprite.RenderPlain((space2))

    # Player
    global playerSprite   
    playerSprite = pygame.sprite.RenderPlain((player))

    # Enemy
    global enemySprites
    enemySprites = pygame.sprite.RenderPlain(())
    ###---LOOK HERE I SWITCHED SOME THINGS ---###
    ###---not that much. random.randint    ---###
    ###---just takes a sudo-random integer ---###
    ###---which is why it's called rand-int---###
    ###---       or random integer         ---###
    enemySprites.add(Enemy(random.randint(1, 800)))
    enemySprites.add(Enemy(random.randint(1, 800)))
    enemySprites.add(Enemy(random.randint(1, 800)))    

    # Projectiles    
    global laserSprites
    laserSprites = pygame.sprite.RenderPlain(())   

    # Collisions   
    global enemyExplosion
    enemyExplosion = pygame.sprite.RenderPlain(())
    global playerExplosion
    playerExplosion = pygame.sprite.RenderPlain(())
    global explosionSprites
    explosionSprites = pygame.sprite.RenderPlain(())


# Main Loop

    going = True

    while going:

        clock.tick(60)



        # Input Events

        for event in pygame.event.get():

            if event.type == QUIT:

                going = False

            elif event.type == KEYDOWN and event.key == K_ESCAPE:

                going = False

        # Update
        space1.update(i)
        space2.update()
        player.update()
        enemySprites.update()
        laserSprites.update()
        enemyExplosion.update()
        playerExplosion.update()
        explosionSprites.update()



        screen.blit(background, (0, 0))


        # Draw
        space1.draw(screen) 
        space2.draw(screen)          
        playerSprite.draw(screen)
        enemySprites.draw(screen)
        laserSprites.draw(screen)
        enemyExplosion.draw(screen)
        playerExplosion.draw(screen)
        explosionSprites.draw(screen)


        pygame.display.flip()



    pygame.quit()

if __name__ == '__main__':

    main()

所以这个问题与你之前提到的空间问题有点不同,所以至少你正在考虑如何存储sprite,但是在这种情况下,有一种更简单的方法来实现它。我希望您从中吸取教训,如果您对此有任何疑问,请告诉我,我会尽快给您回复。

干杯!