太空射击游戏有轻微的错误

时间:2016-03-07 05:47:40

标签: python

我的游戏水平遇到了麻烦,我想知道为什么我的游戏中的敌人没有从屏幕顶部掉下来,我试图制作关卡,但我的班级水平不起作用。有人请帮忙!

我的代码:

import pygame
import random

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
LAV = (209, 95, 250)


#Enemy 
class Block(pygame.sprite.Sprite):
    """ This class represents the block. """
    def __init__(self, color):
        # Call the parent class (Sprite) constructor
        super().__init__()

        self.image = pygame.image.load("enemy2.png")

        self.rect = self.image.get_rect()
    def reset_pos(self):


        self.rect.y = random.randrange(-300,-20)
        self.rect.x = random.randrange(0,screen_width)
#Player
class Player(pygame.sprite.Sprite):
    """ This class represents the Player. """

    def __init__(self):
        """ Set up the player on creation. """
        # Call the parent class (Sprite) constructor
        super().__init__()
        self.image = pygame.image.load("SS1.png")



        self.rect = self.image.get_rect()
#Controls
    def update(self):
        """ Update the player's position. """
        # Get the current mouse position. This returns the position
        # as a list of two numbers.
        pos = pygame.mouse.get_pos()

        # Set the player x position to the mouse x position
        self.rect.x = pos[0]



class Bullet(pygame.sprite.Sprite):
    """ This class represents the bullet . """
    def __init__(self):
        # Call the parent class (Sprite) constructor
        super().__init__()

        self.image = pygame.image.load("fireball2.png")

        self.rect = self.image.get_rect()

    def update(self):
        """ Move the bullet. """
        self.rect.y -= 6



# --- Create the window

# Initialize Pygame
pygame.init()

pygame.display.set_caption("Space Shooter")

# Set the height and width of the screen
screen_width = 850
screen_height = 850
screen = pygame.display.set_mode([screen_width, screen_height])
BG = pygame.image.load("Bg.png")
# --- Sprite lists

# This is a list of every sprite. All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()

# List of each block in the game
block_list = pygame.sprite.Group()

# List of each bullet
bullet_list = pygame.sprite.Group()

# --- Create the sprites
class Level():
    """ This is a generic super-class used to define a level.
        Create a child class for each level with level-specific
        info. """

    def __init__(self, player):
        """ Constructor. Pass in a handle to player. Needed for when moving
            platforms collide with the player. """
        self.platform_list = pygame.sprite.Group()
        self.enemy_list = pygame.sprite.Group()
        self.player = player

        # How far this world has been scrolled left/right
        self.world_shift = 0

    # Update everythign on this level
    def update(self):
        """ Update everything in this level."""
        self.platform_list.update()
        self.enemy_list.update()

    def draw(self, screen):
        """ Draw everything on this level. """

        # Draw the background
        screen.fill(BLUE)

        # Draw all the sprite lists that we have
        self.platform_list.draw(screen)
        self.enemy_list.draw(screen)

    def shift_world(self, shift_x):
        """ When the user moves left/right and we need to scroll
        everything: """

        # Keep track of the shift amount
        self.world_shift += shift_x

        # Go through all the sprite lists and shift
        for platform in self.platform_list:
            platform.rect.x += shift_x

        for enemy in self.enemy_list:
            enemy.rect.x += shift_x


# Create platforms for the level
class Level_01(Level):
    """ Definition for level 1. """

    def __init__(self, player):
        """ Create level 1. """

        # Call the parent constructor
        Level.__init__(self, player)

        self.level_limit = 10

    for i in range(15):
    # This represents a block
        block = Block(BLUE)

    # Set a random location for the block
        block.rect.x = random.randrange(825)
        block.rect.y = random.randrange(500)

    # Add the block to the list of objects
        block_list.add(block)
        all_sprites_list.add(block)

# Create a red player block
class Level_02(Level):
    """ Definition for level 2. """

    def __init__(self, player):
        """ Create level 1. """

        # Call the parent constructor
        Level.__init__(self, player)

        self.level_limit = -3000

        # Array with type of platform, and x, y location of the platform.
        for i in range(30):
    # This represents a block
            block = Block(BLUE)

    # Set a random location for the block¸    
            block.rect.x = random.randrange(650)
            block.rect.y = random.randrange(350)

    # Add the block to the list of objects
            block_list.add(block)
            all_sprites_list.add(block)

        # Go through the arrzay above and add platforms


player = Player()
all_sprites_list.add(player)

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

font = pygame.font.Font(None, 25)

frame_count = 0
frame_rate = 60
start_time = 90

score = 0
player.rect.y = 600
bg_sound = pygame.mixer.Sound("Countdown - Timer.wav")
fire_sound = pygame.mixer.Sound("Laser-SoundBible.com-602495617.wav")
bg_sound.play(-1)

# -------- Main Program Loop -----------
while not done:
    # --- Event Processing
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True



        elif event.type == pygame.MOUSEBUTTONDOWN:
            # Fire a bullet if the user clicks the mouse button
            bullet = Bullet()
            # Set the bullet so it is where the player is
            bullet.rect.x = player.rect.x
            bullet.rect.y = player.rect.y
            # Add the bullet to the lists
            all_sprites_list.add(bullet)
            bullet_list.add(bullet)
            fire_sound.play()




    # --- Game logic

    # Call the update() method on all the sprites
    all_sprites_list.update()

    # Calculate mechanics for each bullet
    for bullet in bullet_list:

        # See if it hit a block
        block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)

        # For each block hit, remove the bullet and add to the score
        for block in block_hit_list:
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)
            score += 1
            print(score)

        # Remove the bullet if it flies up off the screen
        if bullet.rect.y < -50:
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)



    # --- Draw a frame
    screen.blit(BG, [0, 0])

    # Clear the screen


    font = pygame.font.SysFont('Calibri', 25,True, False)
    text = font.render('Enemies Shot:'+ str(score),True, LAV)
    screen.blit(text,[650,500])


    # Draw all the spites
    all_sprites_list.draw(screen)

    total_seconds = start_time - (frame_count // frame_rate)
    if total_seconds == 0:
        font = pygame.font.SysFont('Calibri', 25,True, False)
        text = font.render('YOURE DONE',True, LAV)
        screen.blit(text,[650,500])


    # Divide by 60 to get total minutes
    minutes = total_seconds // 60

    # Use modulus (remainder) to get seconds
    seconds = total_seconds % 60

    # Use python string formatting to format in leading zeros
    output_string = "Time left: {0:00}:{1:02}".format(minutes, seconds)

    # Blit to the screen
    text = font.render(output_string, True, LAV)

    screen.blit(text, [650, 525])

    # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
    frame_count += 10

    # Limit frames per second
    clock.tick(frame_rate)

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

pygame.quit()

1 个答案:

答案 0 :(得分:0)

您可能需要注意的一件事是在更新所有项目符号后清除屏幕。我建议将屏幕清除为while循环中的第一个内容。另一件事是我没有看到你试图移动敌人的任何地方(我可能是错的)。 Block类中的这个函数可能会有所帮助:

def render(self):
    self.rect.y +=3

您可以在渲染功能中更改块的移动方式,这只是一个例子 输入之后,您需要输入类似的内容:

for block in block_list:
    block.render()

在你清除它之后,这将在你的while循环中进行。您可能需要为此设置阻止列表。希望这会有所帮助:)