实战 Space Jump: 使用python中的pygame写一个类似doodle jump的小游戏

Space Jump介绍

首先感谢朋友们的精诚团结,通力协作!以下排名不分先后:Adeline(绘画+ps+audio), lxz(开始界面), ccc(结束界面),yc(boss,player,bullet,enemy,prop,gameobject,后来又加了个button,但还没写好,写好了再多更新一下)和我自己(main,board,scoreboard,interface整合开始界面和结束界面凌乱代码,config整合全部代码)!
GitHub链接:https://github.com/Skywuuuu/Space-Jump,记得给个star!

文件目录

.ipynb文件是将全部的.py文件都放进去而已,为了方便写这篇博客哈哈哈哈哈哈哈哈
在这里插入图片描述
文件夹下images目录中有全部的图片
在这里插入图片描述
文件夹下font目录中有字体,字体可以从网上下载
在这里插入图片描述

操作方式:

上:跳以西
下:发射子弹
左:向左移动
右:向右移动

道具

火箭背包:快速飞行
毒药:左右键呼唤,按左往右移动,按右往左移动
盾:抵挡一次怪物或boss的子弹的攻击伤害

砖块

滑动砖块,跳一次就会消失的砖块,固定砖块

完整代码

Import Package

import pygame
from pygame.sprite import *
from pygame.locals import *
import sys
import random
import time

Game Object


class GameObject(Sprite):
    def __init__(self):
        super().__init__()
        self.alive = True           # Represent that the object is alive
        self.acceleration = 1       # Acceleration in physics
        self.vertical_speed = 0     # Vertical_speed
        self.horizontal_speed = 0

    def collide_with(self, group) -> Sprite:
        """
        Handle the object collide with other object

        :param group:
        :return Sprite Object:
        """
        return spritecollideany(self, group)

    def get_platform(self, boards):
        """
        Get the board

        :param boards:
        :return platform:
        """
        for board in boards:
            # Determine whether or not the object collides with the platform
            if self.rect.right >= board.rect.left and self.rect.left <= board.rect.right:
                if board.rect.top == self.rect.bottom or self.rect.bottom - (self.vertical_speed - self.acceleration) <= board.rect.top <= self.rect.bottom:
                    return board
        return None

    def update(self):
        if self.rect.bottom < 0 or self.rect.top > HEIGHT:
            self.alive = False

Configuration

configuration可以设定很多关于游戏参数的设置(应该是我能想到的全部了)

# The configuration of the game
# Color
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
SAND = (244, 164, 96)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
CYAN = (0, 255, 255)

# Screen
WIDTH = 600
HEIGHT = 800
FPS = 30

# Board
BOARD_WIDTH = 60
BOARD_HEIGHT = 10
BOARD_NUM = 30
BOARD_VERTICAL_SPEED = 3

# Score board
INITIAL_SCORE = 0

# Bullet
BULLET_WIDTH = 20
BULLET_HEIGHT = 20
BULLET_SPEED = 12

# Player
PLAYER_WIDTH = 50
PLAYER_HEIGHT = 50
PLAYER_VERTICAL_SPEED = 18
PLAYER_HORIZONTAL_SPEED = 7
PLAYER_SHOOT_PERIOD = 0.3
PLAYER_DIZZY_PERIOD = 5
PLAYER_FLYING_PERIOD = 5

# Enemy
ENEMY_PROB = 10
ENEMY_WIDTH = 50
ENEMY_HEIGHT = 40

# Prop
PROPS_PROB = 10
POISON_WIDTH = 30
POISON_HEIGHT = 30
JETPACK_WIDTH = 30
JETPACK_HEIGHT = 30
JETPACK_SPEED = 50
SHIELD_WIDTH = 30
SHIELD_HEIGHT = 30

# Boss
BOSS_HP = 10
BOSS_WIDTH = 300
BOSS_HEIGHT = 50
BOSS_HORIZONTAL_SPEED = 2
BOSS_REFRESH_PERIOD = 20

# Interface
RESTART_BUTTON_WIDTH = int(2.25*70)
RESTART_BUTTON_HEIGHT = 1*70
RESTART_BUTTON_TOP = HEIGHT*2//3
RESTART_BUTTON_LEFT = WIDTH//5
RESTART_BUTTON_BOTTOM = RESTART_BUTTON_HEIGHT + RESTART_BUTTON_TOP
RESTART_BUTTON_RIGHT = RESTART_BUTTON_LEFT + RESTART_BUTTON_WIDTH
RESTART_BUTTON_CENTERX = RESTART_BUTTON_WIDTH//2 + RESTART_BUTTON_LEFT
RESTART_BUTTON_CENTERY = RESTART_BUTTON_HEIGHT//2 + RESTART_BUTTON_TOP

QUIT_BUTTON_WIDTH = int(2.25*50)
QUIT_BUTTON_HEIGHT = 1*50
QUIT_BUTTON_TOP = RESTART_BUTTON_TOP+10
QUIT_BUTTON_LEFT = RESTART_BUTTON_LEFT+250
QUIT_BUTTON_BOTTOM = QUIT_BUTTON_HEIGHT + QUIT_BUTTON_TOP
QUIT_BUTTON_RIGHT = QUIT_BUTTON_LEFT + QUIT_BUTTON_WIDTH
QUIT_BUTTON_CENTERX = QUIT_BUTTON_WIDTH//2 + QUIT_BUTTON_LEFT
QUIT_BUTTON_CENTERY = QUIT_BUTTON_HEIGHT//2 + QUIT_BUTTON_TOP

START_BUTTON_WIDTH = int(2.25*50)
START_BUTTON_HEIGHT = 1*50
START_BUTTON_TOP = HEIGHT//2
START_BUTTON_LEFT = WIDTH*5//8
START_BUTTON_BOTTOM = RESTART_BUTTON_HEIGHT + RESTART_BUTTON_TOP
START_BUTTON_RIGHT = RESTART_BUTTON_LEFT + RESTART_BUTTON_WIDTH
START_BUTTON_CENTERX = START_BUTTON_WIDTH//2 + START_BUTTON_LEFT
START_BUTTON_CENTERY = START_BUTTON_HEIGHT//2 + START_BUTTON_TOP

# The quit image must be called as "quit.png" in order to use the quit function in the interface
END_IMAGES = {
    
    'gameover.jpg' : ((WIDTH, HEIGHT), (0,0)),
              'replay.png' : ((RESTART_BUTTON_WIDTH, RESTART_BUTTON_HEIGHT), (RESTART_BUTTON_CENTERX, RESTART_BUTTON_CENTERY)),
              'quit.png' : ((QUIT_BUTTON_WIDTH, QUIT_BUTTON_HEIGHT), (QUIT_BUTTON_CENTERX, QUIT_BUTTON_CENTERY)),
              'replaywhite.png' : ((RESTART_BUTTON_WIDTH, RESTART_BUTTON_HEIGHT), (RESTART_BUTTON_CENTERX, RESTART_BUTTON_CENTERY)),
              'quitwhite.png' : ((QUIT_BUTTON_WIDTH, QUIT_BUTTON_HEIGHT), (QUIT_BUTTON_CENTERX, QUIT_BUTTON_CENTERY))
              }
END_BLINK_IMAGES_NUM = 2

START_IMAGES = {
    
    'start.png': ((WIDTH, HEIGHT), (0,0)),
                'play.png': ((START_BUTTON_WIDTH, START_BUTTON_HEIGHT), (START_BUTTON_CENTERX, START_BUTTON_CENTERY)),
                'playwhite.png': ((START_BUTTON_WIDTH, START_BUTTON_HEIGHT), (START_BUTTON_CENTERX, START_BUTTON_CENTERY))
                }
START_BLINK_IMAGES_NUM = 1

Score Board

class ScoreBoard(pygame.sprite.Sprite):
    '''
    Define the score you get in the game
    '''
    def __init__(self):
        super().__init__()
        self.score = INITIAL_SCORE
        self.font = pygame.font.Font("./fonts/arista.ttf", 48)
        self.image = self.font.render(str(self.score), True, WHITE)
        self.rect = self.image.get_rect(topleft=(10, 10))
        self.alive = True

    def update(self, scores):
        for score in scores:
            self.score += score
        if len(scores) == 0:
            self.rect = self.image.get_rect(center=(WIDTH/2,HEIGHT/10))
            self.image = self.font.render('Your final score is '+str(self.score)+'!', True, WHITE)
        else:
            self.image = self.font.render(str(self.score), True, WHITE)

Props

class Prop(GameObject):
    def __init__(self, board):
        super().__init__()
        self.board = board
        self.type = random.randint(0, 2)  # 0 represents poison, 1 represents jetpack, 2 represents shield
        if self.type == 0:
            self.image = pygame.transform.scale(pygame.image.load('images/poison.png'), (POISON_WIDTH, POISON_HEIGHT))
        elif self.type == 1:
            self.image = pygame.transform.scale(pygame.image.load('images/jetpack.png'), (JETPACK_WIDTH, JETPACK_HEIGHT))
        elif self.type == 2:
            self.image = pygame.transform.scale(pygame.image.load('images/shield.png'), (SHIELD_WIDTH, SHIELD_HEIGHT))
        self.rect = self.image.get_rect(midbottom=board.rect.midtop)

    def update(self, boards):
        super().update()

        # Keep the prop moving the same speed of the board
        if self.get_platform(boards):
            self.rect.move_ip(self.get_platform(boards).horizontal_speed, Board.vertical_speed)
        else:
            self.vertical_speed += self.acceleration
            self.rect.move_ip(0, self.vertical_speed)

Interface

class Interface(Sprite):
    """
    The interface of the game
    """
    def __init__(self, screen, type, images, blink_images_num):
        super().__init__()
        self.screen = screen
        self.alive = True
        self.type = type
        self.blink_images_num = blink_images_num
        self.images = {
    
    }

        # print(images) # For test
        for image_name, (size, location) in images.items():
            # print(image_name, size, location) # For test
            self.load_image(image_name, size, location)
        self.image = None
        self.blit_image()
        self.rect = self.image.get_rect(topleft=(0, 0))

    def blit_image(self):
        """
        The first image should be the background of this interface, the images after the first image are buttons or
        other decorations

        :return:
        """
        for i, key in enumerate(self.images.keys()):
            if i == 0:
                self.image = self.images[key][0]
            else:
                self.image.blit(self.images[key][0],
                                self.images[key][0].get_rect(center=self.images[key][2]))

    def load_image(self, image_name, size, location):
        """
        Load the image information and store the image into a dictionary

        :param image_name: the name of image
        :param size: the size of the image
        :param location: the location of the image in the screen
        :return:
        """
        self.images[image_name] = (pygame.transform.scale(pygame.image.load('./images/' + image_name), size), size, location)

    def mouse_on_button(self, image_name):
        """
        Determine whether the mouse is on button or not

        :param image_name: the name of the image
        :return: Boolean value
        """
        # Identify the location of mouse
        x, y = pygame.mouse.get_pos()

        # Do if the mouse on the button
        if self.images[image_name][2][0] - self.images[image_name][1][0]//2 <= x <= self.images[image_name][2][0] + self.images[image_name][1][0]//2\
                and self.images[image_name][2][1] - self.images[image_name][1][1]//2<= y <= self.images[image_name][2][1] + self.images[image_name][1][1]//2:
            self.image = self.images[image_name][0]
            self.rect = self.image.get_rect(center=(self.images[image_name][2]))
            return True
        return False

    def click_button(self, image_name):
        """
        Judge whether the mouse click or not
        :param image_name:
        :return:
        """
        buttons = pygame.mouse.get_pressed()
        if buttons[0]:  # If click the left button on the mouse, buttons[0]=True
            self.alive = False
            if image_name == 'quit.png':
                pygame.quit()
                sys.exit()


    def update(self):
        super().update()

        # Detect mouse clicks
        for key in list(self.images.keys())[1:1+self.blink_images_num]:
            if self.mouse_on_button(key):
                # print(key) # For test
                self.click_button(key)
                break
        else:
            self.image = list(self.images.values())[0][0]
            self.rect = self.image.get_rect(topleft=(0, 0))

Player

class Player(GameObject):
    def __init__(self):
        super().__init__()
        self.image = pygame.transform.scale(pygame.image.load('images/player.png'), (PLAYER_WIDTH, PLAYER_HEIGHT))
        self.rect = self.image.get_rect(midbottom=(WIDTH / 2, HEIGHT * 2 / 3))
        self.init_speed = -PLAYER_VERTICAL_SPEED
        self.horizontal_speed = PLAYER_HORIZONTAL_SPEED
        self.shot_time = time.time()
        self.shot_period = PLAYER_SHOOT_PERIOD
        self.dizzy = False
        self.dizzy_time = time.time()
        self.flying = False
        self.flying_time = time.time()
        self.protected = False


    def update(self, pressed_keys, boards, player_bullets, boss_bullets, enemies, props):
        super().update()

        # Check whether player hit the prop
        prop = self.collide_with(props)
        if prop is not None:
            prop.alive = False
            # 0 stands for poison
            if prop.type == 0:
                self.dizzy = True
                self.dizzy_time = time.time()

            # 1 stands for the jetpack
            elif prop.type == 1:
                self.flying = True
                self.flying_time = time.time()
                Board.vertical_speed = JETPACK_SPEED
            # 2 stands for the shield
            elif prop.type == 2:
                self.protected = True

        # Check whether the player hit the bullets of boss
        bullet = self.collide_with(boss_bullets)
        if  not self.flying :
            if bullet is not None and not self.protected  :
                self.alive = False
                bullet.alive = False
            if bullet is not None and self.protected:
                self.protected = False
                bullet.alive = False

        # Check whether the player hit the enemy
        enemy = self.collide_with(enemies)
        if  not self.flying :
            if enemy is not None and not self.protected  :
                self.alive = False
                enemy.alive = False
            if enemy is not None and self.protected:
                self.protected = False
                enemy.alive = False



        if self.flying and self.dizzy and self.protected:
                self.image = pygame.transform.scale(pygame.image.load('images/player_dizzy_shield_rocket.png'),
                                                (PLAYER_WIDTH, PLAYER_HEIGHT))
        elif self.protected and self.flying:
                self.image = pygame.transform.scale(pygame.image.load('images/player_shield_rocket.png'),
                                                (PLAYER_WIDTH, PLAYER_HEIGHT))
        elif self.protected and self.dizzy:
                self.image = pygame.transform.scale(pygame.image.load('images/player_dizzy_shield.png'),
                                                (PLAYER_WIDTH, PLAYER_HEIGHT))
        elif self.flying and self.dizzy:
                self.image = pygame.transform.scale(pygame.image.load('images/player_dizzy_rocket.png'),
                                                (PLAYER_WIDTH, PLAYER_HEIGHT))
        elif self.protected:
                self.image = pygame.transform.scale(pygame.image.load('images/player_shield.png'),
                                                (PLAYER_WIDTH, PLAYER_HEIGHT))
        elif self.dizzy:
                 self.image = pygame.transform.scale(pygame.image.load('images/player_dizzy.png'),
                                                (PLAYER_WIDTH, PLAYER_HEIGHT))
        elif self.flying:
                 self.image = pygame.transform.scale(pygame.image.load('images/player_rocket.png'),
                                                (PLAYER_WIDTH, PLAYER_HEIGHT))
        else:
            self.image = pygame.transform.scale(pygame.image.load('images/player.png'), (PLAYER_WIDTH, PLAYER_HEIGHT))

        # Adjust the dizzy status if the dizzy time is over
        if time.time() - self.dizzy_time > PLAYER_DIZZY_PERIOD:
            self.dizzy = False

        # Adjust the flying status if the flying time is over
        if time.time() - self.flying_time > PLAYER_FLYING_PERIOD:
            self.flying = False
            Board.vertical_speed = 3

        if not self.flying:
            board = self.get_platform(boards)
            if board:
                if pressed_keys[K_UP]:  # The UP KEY is pressed
                    self.vertical_speed = self.init_speed  # Give an initial speed
                    self.rect.move_ip(0, self.vertical_speed)
                if self.vertical_speed > 0:  # Player drop to board from the air
                    self.vertical_speed = 0
                    self.rect.bottom = board.rect.top
                if self.vertical_speed == 0:  # Player stay on the board
                    self.rect.move_ip(self.get_platform(boards).horizontal_speed, Board.vertical_speed)
                if not board.stable: # If the player touch the unstable board, it will jump automatically
                    self.vertical_speed = self.init_speed
                    board.alive = False
            else:  # Player is not on the board
                self.vertical_speed += self.acceleration
                self.rect.move_ip(0, self.vertical_speed)




        if pressed_keys[K_DOWN]:  # Press the DOWN KEY to shoot the bullet
            if time.time() - self.shot_time > self.shot_period:
                player_bullets.add(Bullet(self.rect.midtop, 0, -BULLET_SPEED,0))
                self.shot_time = time.time()

        if pressed_keys[K_LEFT]:  # Press the LEFT KEY to move the player to the left
            if not self.dizzy:
                self.rect.move_ip(-self.horizontal_speed, 0)
            else:
                self.rect.move_ip(self.horizontal_speed, 0)

        if pressed_keys[K_RIGHT]:  # Press the RIGHT KEY to move the player to the right
            if not self.dizzy:
                self.rect.move_ip(self.horizontal_speed, 0)
            else:
                self.rect.move_ip(-self.horizontal_speed, 0)

        # Keep the player in the screen
        if self.rect.left < 0:
            self.rect.left = 0
        if self.rect.right > WIDTH:
            self.rect.right = WIDTH
        if self.rect.top <= 0:
            self.rect.top = 0

Boss/The biggest monster

class Boss(GameObject):
    def __init__(self):
        super().__init__()
        self.HP = BOSS_HP
        self.image = pygame.transform.scale(pygame.image.load('images/ufo.png'), (BOSS_WIDTH, BOSS_HEIGHT))
        self.rect = self.image.get_rect(midtop=(WIDTH/2, 0))
        self.horizontal_speed = BOSS_HORIZONTAL_SPEED

    def update(self, player_bullets, boss_bullets):
        super().update()
        bullet = self.collide_with(player_bullets)
        if bullet is not None:
            self.HP -= 1
            player_bullets.remove(bullet)

        if self.HP == 0:
            self.alive = False

        if random.randint(0, 50) == 0:

            boss_bullets.add(Bullet((random.randint(self.rect.left, self.rect.right), self.rect.bottom), random.randint(-5, 5), 6, 1))

        self.rect.move_ip(self.horizontal_speed, 0)
        # Keep the boss inside the screen
        if self.rect.left <= 0:
            self.rect.left = 0
            self.horizontal_speed = -self.horizontal_speed
        if self.rect.right >= WIDTH:
            self.rect.right = WIDTH
            self.horizontal_speed = -self.horizontal_speed

Bullet

class Bullet(GameObject):
    def __init__(self, pos, horizontal_speed, vertical_speed, type ): #BOSS.tpye=1 Player.type=0
        super().__init__()
        self.type=type
        if self.type:
            self.image = pygame.transform.scale(pygame.image.load('images/bullet_enemy.png'), (BULLET_WIDTH, BULLET_HEIGHT))
        else:
            self.image = pygame.transform.scale(pygame.image.load('images/bullet.png'), (BULLET_WIDTH, BULLET_HEIGHT))
        self.rect = self.image.get_rect(midbottom=pos)
        self.horizontal_speed = horizontal_speed
        self.vertical_speed = vertical_speed

    def update(self):
        super().update()
        self.rect.move_ip(self.horizontal_speed, self.vertical_speed)   # The speed of the bullet

        if self.rect.left < 0 or self.rect.right > WIDTH:
            self.horizontal_speed = -self.horizontal_speed

Board

class Board(GameObject):
    num = BOARD_NUM  # Indicate the total number of the board
    vertical_speed = BOARD_VERTICAL_SPEED  # Indicate the vertical speed of the board

    def __init__(self, pos, randomly):
        super().__init__()
        self.stable = bool(random.randint(0, 5)) if randomly else True  # Indicates the board is stable or not
        self.horizontal_speed = random.randint(-1, 1) * 5 if randomly and self.stable and random.randint(0,
                                                                                                         3) == 0 else 0

        if not self.stable:
            self.image = pygame.transform.scale(pygame.image.load('images/redbroken.png'), (
                BOARD_WIDTH, BOARD_HEIGHT))  # Indicate the unstable but static board
        else:
            if self.horizontal_speed == 0:
                self.image = pygame.transform.scale(pygame.image.load('images/blue.png'), (
                    BOARD_WIDTH, BOARD_HEIGHT))  # Indicate the stable and static board
            else:
                self.image = pygame.transform.scale(pygame.image.load('images/beige.png'), (
                    BOARD_WIDTH, BOARD_HEIGHT))  # Indicate the stable and sliding board
        self.rect = self.image.get_rect(midtop=pos)

    def update(self):
        super().update()
        self.rect.move_ip(self.horizontal_speed,
                          Board.vertical_speed)  # Move the board down in order to make the player feel like jumping

        # Keep the sliding board inside the screen
        if self.rect.left <= 0:
            self.rect.left = 0
            self.horizontal_speed = -self.horizontal_speed
        if self.rect.right >= WIDTH:
            self.rect.right = WIDTH
            self.horizontal_speed = -self.horizontal_speed

Enemy

class Enemy(GameObject):
    def __init__(self, board):
        super().__init__()
        self.board = board
        self.image = pygame.transform.scale(pygame.image.load('images/enemy'+str(random.randint(1, 5))+'.png'), (ENEMY_WIDTH, ENEMY_HEIGHT))
        self.rect = self.image.get_rect(midbottom=board.rect.midtop)

    def update(self, boards, player_bullets):
        super().update()
        bullet = self.collide_with(player_bullets)
        if bullet is not None:  # If the enemy collides with bullets
            self.alive = False
            bullet.alive = False

        # Keep the enemy moving the same speed of the boards
        if self.get_platform(boards):
            self.rect.move_ip(self.get_platform(boards).horizontal_speed, Board.vertical_speed)
        else:
            self.vertical_speed += self.acceleration
            self.rect.move_ip(0, self.vertical_speed)

Main

def create_new(groups):
    """
    Create new board, enemy and props.

    :return:
    """
    if len(groups['boards']) < Board.num:
        board = Board(pos=(random.randint(0, WIDTH), 0), randomly=True)
        groups['boards'].add(board)
        random_num = random.randint(1, 100)
        if random_num <= ENEMY_PROB:
            groups['enemies'].add(Enemy(board))
        if random_num >= 100 - PROPS_PROB:
            groups['props'].add(Prop(board))

    if len(groups['boss']) == 0 and time.time() - boss_dead_time > BOSS_REFRESH_PERIOD:
        groups['boss'].add(Boss())


def remove_dead(group):
    """
    Remove the everything that are outside the screen.

    :param group:
    :return:
    """
    for sprite in group:
        if not sprite.alive:
            group.remove(sprite)


def init_group():
    player = pygame.sprite.GroupSingle(Player())
    boss = pygame.sprite.Group()
    player_bullets = pygame.sprite.Group()
    boss_bullets = pygame.sprite.Group()
    scoreboard = pygame.sprite.GroupSingle(ScoreBoard())
    enemies = pygame.sprite.Group()
    boards = pygame.sprite.Group()
    props = pygame.sprite.Group()

    # Initialize the boards
    for i in range(Board.num):
        boards.add(Board((random.randint(0, WIDTH), random.randint(0, HEIGHT)), True))
    boards.add(Board((WIDTH / 2, HEIGHT * 2 / 3), False))

    return {
    
    'player': player, 'boss': boss, 'player_bullets': player_bullets, 'boss_bullets': boss_bullets,
            'scoreboard': scoreboard, 'enemies': enemies, 'boards': boards, 'props': props}


if __name__ == '__main__':
    pygame.init()
    pygame.display.set_caption("Space Jump")
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    background = pygame.image.load('images/background.jpg')
    end_interface = Interface(screen, type='end', images=END_IMAGES, blink_images_num=END_BLINK_IMAGES_NUM)
    start_interface = Interface(screen, type='start', images=START_IMAGES, blink_images_num=START_BLINK_IMAGES_NUM)
    boss_dead_time = time.time()
    clock = pygame.time.Clock()

    #load music
    pygame.mixer.music.load(r"sound_track.mp3")
    pygame.mixer.music.play()
    pygame.mixer.music.play(loops=-1)

    # Initialize the player, player_bullets, enemies, boards, props and scoreboard.
    groups = init_group()
    create_new(groups)

    while True:
        # Close the window of the game and end the program
        for event in pygame.event.get():
            if event.type == QUIT or pygame.key.get_pressed()[K_ESCAPE]:
                pygame.quit()
                sys.exit()

        clock.tick(FPS)
        pygame.display.flip()
        # The start page
        if start_interface.alive:
            screen.blit(start_interface.image, start_interface.rect)
            start_interface.update()
            if start_interface.alive == False:
                continue

        # If player is alive
        elif len(groups['player']) == 1:
            screen.blit(background, background.get_rect())

            # Draw all the objects
            for group in groups.values():
                group.draw(screen)

            # Record temporary number of objects
            temp_boards_num = len(groups['boards'])
            temp_enemies_num = len(groups['enemies'])
            temp_boss_num = len(groups['boss'])

            # Delete the boards or player_bullets off the screen and the dead enemies
            for group in groups.values():
                remove_dead(group)

            # Update all the objects
            groups['player'].update(pygame.key.get_pressed(), groups['boards'], groups['player_bullets'], groups['boss_bullets'], groups['enemies'], groups['props'])
            groups['boss'].update(groups['player_bullets'], groups['boss_bullets'])
            groups['player_bullets'].update()
            groups['boss_bullets'].update()
            groups['enemies'].update(groups['boards'], groups['player_bullets'])
            groups['props'].update(groups['boards'])
            groups['boards'].update()
            groups['scoreboard'].update([temp_boards_num - len(groups['boards']), (temp_enemies_num - len(groups['enemies'])) * 10,
                               (temp_boss_num - len(groups['boss'])) * 1000])

            # Boss is dead
            if temp_boss_num != len(groups['boss']):
                boss_dead_time = time.time()

            # Create new boards, enemy and boss if the number of them is not enough
            create_new(groups)
        else:  # If player is dead, display the ending interface
            screen.blit(end_interface.image, end_interface.rect)
            end_interface.update()
            groups['scoreboard'].draw(screen)
            groups['scoreboard'].update([])
            # If the click restart, reinitialize the game.
            if end_interface.alive == False:
                # Clear the screen
                for group in groups.values():
                    group.empty()
                # Initialize the game
                groups = init_group()
                boss_dead_time = time.time()
                end_interface.alive = True

An exception has occurred, use %tb to see the full traceback.


SystemExit

Conclusion


猜你喜欢

转载自blog.csdn.net/skywuuu/article/details/115286535
今日推荐