示例#1
0
    def __init__(self):
        """Initialize the game, and create game ressources."""
        pygame.init()
        self.settings = Settings()
        self.clock = pygame.time.Clock()

        # # Switch the comments on these blocks for fullscreen or window screen
        # self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        # self.settings.screen_width = self.screen.get_rect().width
        # self.settings.screen_height = self.screen.get_rect().height

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption('COVID Invasion')

        # Create an instance to store game statistics
        #   and create a scoreboard
        self.stats = GameStats(self)
        self.scoreboard = Scoreboard(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        self.play_button = Button(self, 'Play')
示例#2
0
    def __init__(self):
        """Initialize the game, and create game resource."""
        pygame.init()

        self.settings = Setting()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        #self.screen = pygame.display.set_mode((0,0),pygame.FULLSCREEN)
        #self.settings.screen_width = self.screen.get_rect().width
        #self.settings.screen_height = self.screen.get_rect().height

        pygame.display.set_caption("Alien_Invation")

        # Create instance to store game statistics.
        self.stats = GameStats(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()
        # Make the play button.
        self.play_button = Button(self, "Play")
        # Set background color.
        self.bg_color = self.settings.bg_color
示例#3
0
def run_game():
    # Инициализирует игру и создает объект экрана.
    pygame.init()
    ai_settings = Settings()
    stats = GameStats(ai_settings)
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    sb = Scoreboard(ai_settings, screen, stats)
    play_button = Button(ai_settings, screen, "Play")
    ship = Ship(ai_settings, screen)
    # Group for bullet
    bullets = Group()
    # Group for alien
    aliens = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # alien = Alien(ai_settings, screen)

    while True:
        # Отслеживание событий клавиатуры и мыши.
        gf.check_events(ai_settings, screen, stats, play_button, ship, bullets)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets)
def run_game():
    # 初始化游戏并创建一个屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))

    pygame.display.set_caption("Alien vasion")

    # 创建Play按钮
    play_button = Button(ai_settings, screen, "Play")
    # 创建一艘飞船、一个子弹编组、一个外星人编组
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()
    # 创建外星人群
    gf.create_fleet(ai_settings, screen, ship, aliens)
    # 创建一个用于存储游戏统计信息的实例
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    # 开始游戏的主循环
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, bullets,
                              aliens)
            gf.update_aliens(ai_settings, stats, sb, screen, aliens, ship,
                             bullets)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
示例#5
0
def run_game():
    pygame.init()
    clock = pygame.time.Clock()
    game_settings = Settings()
    screen = pygame.display.set_mode((game_settings.screen_width, game_settings.screen_height))
    game_menu = Menu(screen, "Game Menu")
    play_button = Button(game_settings, screen, "Play", 500, 250)
    option_button = Button(game_settings, screen, "Options", 500, 350)
    reset_button = Button(game_settings, screen, "Reset game", 500, 450)
    exit_button = Button(game_settings, screen, "Exit", 500, 550)
    pygame.display.set_caption("Alien Invasion")
    stats = GameStats(game_settings)
    score_board = Scoreboard(game_settings, screen, stats)
    player_ship = Ship(screen)
    rockets = Group()
    aliens = Group()

    create_alien_fleet(game_settings, screen, player_ship, aliens)

    # game loop
    while True:
        clock.tick(60)
        check_events(score_board, stats, game_settings, screen, player_ship, aliens, rockets, play_button, reset_button)
        if game_settings.game_active:
            player_ship.update_position()
            update_rockets(game_settings, stats, screen, player_ship, rockets, aliens, score_board)
            update_aliens(game_settings, stats, screen, player_ship, aliens, rockets)
        update_screen(game_settings, screen, player_ship, rockets, aliens, play_button,
                      option_button, exit_button, reset_button, game_menu, score_board)
def run_game():
    #初始化pygame、设置和屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width,ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    #创建play按钮
    play_button = Button(screen,"play")
    #创建一个用于存储游戏统计信息的实例,并显示记分牌
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings,screen,stats)

    #创建一个飞船、子弹、外星人的编组
    ship = Ship(ai_settings,screen)
    bullets = Group()
    aliens = Group()

    #创建外星人人群
    gf.create_fleet(ai_settings,screen,aliens,ship)

    #开始游戏的主循环
    while True:
        #监视键盘和鼠标事件
        gf.check_events(ai_settings,screen,ship,bullets, play_button,stats,aliens,sb)

        if stats.game_active:
            ship.update()
            gf.update_bullets(bullets,aliens,ship,ai_settings,screen,stats,sb)
            gf.update_aliens(ai_settings,aliens,ship,screen,bullets,stats,sb)

        # 更新屏幕上图像,并切换新屏幕
        gf.update_screen(ai_settings,screen,ship,aliens,bullets,play_button,stats,sb)
示例#7
0
def run_game():

    pygame.init()

    ai_settings = Settings()
    screen_size = (ai_settings.screen_width, ai_settings.screen_height)

    pygame.display.set_caption("Alien Invasion")
    screen = pygame.display.set_mode(screen_size)

    play_button = Button(ai_settings, screen, "Play")

    stats = GameStats(ai_settings)
    scoreboard = Scoreboard(ai_settings, screen, stats)

    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

    gf.create_fleet(ai_settings, screen, ship, aliens)

    while True:
        gf.check_events(ai_settings, screen, stats, scoreboard, play_button,
                        ship, aliens, bullets)

        if stats.game_active:
            ship.update()
            bullets.update()
            gf.update_bullets(ai_settings, screen, stats, scoreboard, ship,
                              aliens, bullets)
            gf.update_aliens(ai_settings, screen, stats, scoreboard, ship,
                             aliens, bullets)

        gf.update_screen(ai_settings, screen, stats, scoreboard, ship, aliens,
                         bullets, play_button)
 def __init__(self):
     """Initialize the game , and create game resources"""
     pygame.init()
     self.setting = Setting()
     self.bullets = pygame.sprite.Group(
     )  # use for collecting similar type of object
     self.screen = pygame.display.set_mode(
         (0, 0), pygame.FULLSCREEN
     )  # 0 width and 0 length expresses the full screen
     self.setting.screen_width = self.screen.get_rect().width
     self.setting.screen_height = self.screen.get_rect().height
     # pygame.display.set_caption("Alien Invasion")
     self.ship = Ship(self)
     self.enemy = pygame.sprite.Group()
     self.stats = GameStats(self)
     self.score_board = ScoreBoard(self)  #create a score board
     self._create_fleet()
     # as we need only one button then we need to call it once
     self.play_button = Button(self, "Play")
示例#9
0
def aline_invasion_game_handle():
    #创建默认设置对象(获取默认设置参数)
    settings = Setting()
    screen_size = settings.get_screen_size()

    #初始化pygame模块、创建一个屏幕对象、设置标题栏标题
    pygame.init()
    screen = pygame.display.set_mode(screen_size)
    pygame.display.set_caption("疯狂外星人")

    #初始化游戏状态
    status = GameStats(settings)
    game.game_init_deal(status, settings)
    new_ship = game.create_new_ship(screen, settings)

    #创建PLAY按钮
    button_attr = settings.button
    button_attr["text_msg"] = "PLAY"
    play_bubtton = Button(screen, button_attr)

    #STOP提示栏
    button_attr["text_msg"] = "STOP"
    stop_bubtton = Button(screen, button_attr)

    #计分板
    score = ScoreBoard(screen, settings, status)

    #游戏主循环
    while True:
        #屏幕背景色颜色绘制
        screen_attr = settings.screen.copy()
        surface_screen_color_draw(screen, screen_attr["color"])

        #处理pygame系统事件
        game.event_traverl_deal(settings, \
            screen, new_ship, play_bubtton, status)

        #暂停(提示,按钮不可按)
        if status.game_stop:
            stop_bubtton.__draw__()
            score_board_draw(score)
            pygame.display.flip()
            continue

        if not status.game_over:
            #处理外星人、子弹、飞船在屏幕中的位置以及相关逻辑
            game.update_game_status(screen, settings, new_ship, status)

        #游戏结束则绘制按钮并处理一些统计信息等数据
        game.game_over_check(status, new_ship, play_bubtton, settings)

        #绘制最新屏幕(刷新)
        score_board_draw(score)
        pygame.display.flip()
示例#10
0
def run_game():
    # 初始化背景设置
    image_list = gf.init_images()
    pygame.init()
    ai_settings = Settings()

    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    background = Background(ai_settings, screen)
    stats = GameStats(ai_settings)
    sb = Stepboard(ai_settings, screen, stats)
    pygame.display.set_caption("图片华容道")
    logo = Logo(ai_settings, screen)

    # 创建开始游戏按钮
    play_button = Button(ai_settings, screen, stats, "",
                         "images_material/play_button.png")
    replay_button = Button(ai_settings, screen, stats, "",
                           "images_material/again.png")
    exit_button = Button(ai_settings, screen, stats, "",
                         "images_material/exit_button.png")
    back_button = Button(ai_settings, screen, stats, "",
                         "images_material/back.png")
    reset_button = Button(ai_settings, screen, stats, "",
                          "images_material/reset.png")

    # 创建滑块列表
    blocks = list()

    # 填充滑块列表
    gf.create_all_blocks(ai_settings, screen, blocks,
                         image_list)  # 把切割好的图像列表传进来
    BLOCKS_ORI = list(blocks)
    reset_blocks = list()
    # 开始游戏主循环
    while True:
        # 监视键盘和鼠标事件
        gf.check_events(ai_settings, screen, blocks, BLOCKS_ORI, reset_blocks,
                        stats, sb, play_button, replay_button, reset_button,
                        exit_button, back_button, image_list)
        if stats.game_menu:
            gf.update_screen_menu(ai_settings, screen, blocks, stats, sb,
                                  play_button, exit_button, logo, background)
        else:
            gf.update_screen_playing(ai_settings, screen, blocks, stats, sb,
                                     replay_button, back_button, reset_button,
                                     background)
示例#11
0
文件: main.py 项目: Ceasty/myGame
    def __init__(self):
        pygame.init()
        self.my_settings = Settings()

        self.error = False
        self.screen = pygame.display.set_mode(
            [self.my_settings.window_width, self.my_settings.window_height])
        #self.screen = pygame.display.set_mode([0,0], pygame.FULLSCREEN)

        self.title = pygame.display.set_caption("Game Toilet")
        self.bg_color = self.my_settings.bg_color

        self.bullets = pygame.sprite.Group(
        )  #container for bullet, tujuan biar ketika remove bullet semua bullet tidak hilang/
        self.my_toilet = Toilet(self)
        self.tahi_army = pygame.sprite.Group()  #container for tai.
        self.my_viruses = pygame.sprite.Group()

        self.my_stats = GameStats(self)

        self.create_tahi_army()
        self.create_my_viruses()
示例#12
0
def run_game():
    # Инициализирует игру и создаёт объект экрана.
    pygame.init()
    ai_settings = Settings()

    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Nataherizada Wars")

    # Создание кнопки Play
    play_button = Button(ai_settings, screen, "Play")

    # Создание корабля
    ship = Ship(ai_settings, screen)

    # Создание группы для хранения пуль.
    bullets = Group()

    # Создание пришельца.
    aliens = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Создание экземляров GameStats и Scoreboard
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    while True:
        # Отслеживает события клавиатуры и мыши.
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)

        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
def run_game():
    # initialize game and create a screen object
    pygame.init()
    ai_setting = Setting()
    screen = pygame.display.set_mode(
        (ai_setting.screen_width, ai_setting.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # make the play button.
    play_button = Button(ai_setting, screen, "Play")

    # create an instance to store game statictics and create a scoreboard
    stats = GameStats(ai_setting)
    sb = Scoreboard(ai_setting, screen, stats)
    # make a ship
    ship = Ship(ai_setting, screen)

    # make a group to store bullets and alien in.
    bullets = Group()
    aliens = Group()

    # create the fleet of aliens
    gf.create_fleet(ai_setting, screen, ship, aliens)

    # start the main loop for the game
    while True:

        # watch for keyboard and mouse events.
        gf.check_events(ai_setting, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_setting, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_setting, screen, stats, sb, ship, aliens,
                             bullets)
        gf.update_screen(ai_setting, screen, stats, sb, ship, aliens, bullets,
                         play_button)
def run_game():
	#Инициализирует игру и создает объект экрана
	pygame.init()
	ai_settings = Settings()
	screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
	pygame.display.set_caption("Ловец вкусняшек")
	#Назначение фона
	ai_settings.bg = pygame.image.load('images/bg.bmp').convert()
	#Создание группы для вкусняшек
	yummie_gr = pygame.sprite.Group()
	#Загрузка изображений вкусняшек
	load_yum_img()
	#Создание кнопки Play
	play_button = Button(screen, 'Играть')
	#Создание героя
	hero = Hero(ai_settings, screen)
	#Создание секундомера
	timer = Timer(ai_settings, screen)
	#Создание экзмепляров GameStats и ScoreBoard
	stats = GameStats(ai_settings, screen)
	sb = ScoreBoard(ai_settings, screen, stats)
	#Фиксируем fps
	clock = pygame.time.Clock()
	FPS = 60
	#Запуск основого цикла игры
	while True:
		clock.tick(FPS)
		#Отслеживание событий клавиатуры и мыши.
		#print(clock.get_fps())
		gf.check_events(ai_settings, screen, hero, yummie_gr, stats, sb, timer, play_button)
		#Если игра активна, обновление героя и вкусняшек
		if stats.game_active:
			hero.update()
			gf.update_yummie(ai_settings, screen,  yummie_gr, hero, stats, sb, timer, play_button)
		#Обновление экрана
		gf.update_screen(ai_settings, screen, hero, yummie_gr, stats, sb, timer, play_button)
def run_game():
    global score#enable the "score" variable to be called from inside the function
    pygame.init()#initialize pygame module as the run_game function is started
    settings    = Setting()#import settings and make an instance of setting
    #import the screen width and height from settings module
    screen      = pygame. display.set_mode((settings.screen_width,settings.screen_height))

    #make an empty group to hold all sprites in game
    bullets     = Group()
    ebullets    = Group()
    tornados    = Group()

    #####################################################################
    #__import each modules and make an instance of each related module__#
    #####################################################################
    stats   = GameStats(settings)
    chara   = Chara(settings,screen)
    enemy   = Enemy(settings,screen)
    #first background's x and y position is set 0, thus appear before the second background
    bg1 = Background(0,0,settings,screen)
    #second background's x position is set next to the first background
    bg2 = Background(1300,0,settings,screen)
    bgt = Background(0,0,settings,screen)#instance of the title screen background
    sb  = Scoreboard(settings,screen,stats)#instance of the scoreboard
    #make an instance of the play button, the "PLAY" string is used for the button to be clicked
    #while the "High score" is used to display the high score and calls the global variable of "score"
    play_button = Button(screen, "PLAY", "High Score : " + str(score))#instance of the play button

    ########################################
    #___caption,music file, and booleans___#
    ########################################
    pygame.display.set_caption("Cuphead")#set the programs caption while running
    pygame.mixer.music.load("panic.mp3")#load the music in mp3 format
    pygame.mixer.music.set_volume(0.5)#sets the music volume
    music = 0#acts as the boolean of the music player
    title = 1#sets boolean of the title screen

    ##########################################################
    #____function to display the title screen of the game____#
    ##########################################################
    def main_menu():
        #the title screen is dispalyed right after running the game and when the game is not active
        if title == 1 and stats.game_active == False:
            bgt.blitme2()#displays the background title image
        #check list of events in the game function and perform tasks depending on the type of event which occured
        gf.check_events(settings,screen,stats,chara,bullets,enemy,ebullets,tornados,play_button)
        gf.play_button(stats,play_button)#displays the play button if the game is not active yet

    ##############################################################################
    #___contains event loop and code which manages the game and performs tasks___#
    ##############################################################################
    while True:
        main_menu()#calls the main_menu function

        #performs condition checking after the play button is pressed
        if stats.game_active:
            title = 0#disable the title screen
            if music == 0:
                pygame.mixer.music.play()#plays the music
                music = 1#change music from 0 to 1 to plays the music after the game is set to active

            #displays the first and second background on screen
            screen.blit(bg1.image,bg1.rect)
            screen.blit(bg2.image,bg2.rect)

            gf.check_col(chara, enemy)  # check the collision of chara and enemy

            #updates every module that needed to keep being updated while the game is running
            gf.update_sprites(chara,enemy)
            gf.update_bullets(chara,enemy,bullets,stats,settings,sb)
            gf.update_ebullets(chara,ebullets)
            gf.update_tornados(chara,tornados)
            gf.update_screen(chara,enemy,bullets,ebullets,tornados,sb)

            #update background to move
            bg1.update()#update the first background
            bg2.update()#update the scond background

            ################################################
            #_____conditions while the game is running_____#
            ################### #############################
            #set new high score if the last game score is higher than the current high score
            if stats.score > score and chara.lives_left == 0:
                # rounds up the new high score to the nearest ten and separate it with a comma
                score = "{:,}".format(int(round(stats.score, -1)))

            #to restart the game everytime the player runs out of lives
            if chara.lives_left == 0:
                pygame.mouse.set_visible(True)#set the mouse cursor to be visible
                run_game()#restart the game

        pygame.display.flip()#make the most recently drawn screen be visible
示例#16
0
class AlienInvasion:
    """Overall class to manage game asset and behavior."""
    def __init__(self):
        """Initialize the game, and create game resource."""
        pygame.init()

        self.settings = Setting()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        #self.screen = pygame.display.set_mode((0,0),pygame.FULLSCREEN)
        #self.settings.screen_width = self.screen.get_rect().width
        #self.settings.screen_height = self.screen.get_rect().height

        pygame.display.set_caption("Alien_Invation")

        # Create instance to store game statistics.
        self.stats = GameStats(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()
        # Make the play button.
        self.play_button = Button(self, "Play")
        # Set background color.
        self.bg_color = self.settings.bg_color

    def run_game(self):
        """Start the main loop for the game"""
        while True:
            self._check_events()

            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()

            self._update_screen()

            # Get rid of bullets that have disappeared.

    def _update_bullets(self):
        """Update postion of bullets and get rid of old bullets."""
        # Update bullet position.
        self.bullets.update()

        # Get rid of bullets that have disappeared.
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)
            print(len(self.bullets))
        self._check_bullet_alien_collisions()

    def _check_bullet_alien_collisions(self):
        """Respond to bullet-alien collisions."""
        # Remove any bullets and aliens that have collided.
        # Check for any bullets that have hit aliens.
        # If so, get rid of the bullet and the alien.
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                False, True)
        if not self.aliens:
            # Destroy existing bullets and create new fleet.
            self.bullets.empty()
            self._create_fleet()

    def _check_events(self):
        """Respond to keypresses and mouse event."""
        # Watch for the keyboard and mouse event.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """Start new game when the player click play."""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            # Reset the game settings
            self.settings.initialize_dynamic_settings()
            self.stats.reset_stats()
            self.stats.game_active = True

            # Get rid of any remaining aliens and bullets.
            self.aliens.empty()
            self.bullets.empty()

            # Create a new fleet and center the ship.
            self._create_fleet()
            self.ship.center_ship()

            # Hide the mouse cursor.
            pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        """Response to keypress"""
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _check_keyup_events(self, event):
        """Response to releases"""
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False

    def _fire_bullet(self):
        """Create a new bullet and add it to the bullet group."""
        if len(self.bullets) < self.settings.bullet_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_screen(self):
        """Update image on the screen, and flip to new screen."""
        self.screen.fill(self.settings.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()

        self.aliens.draw(self.screen)

        # Draw play button if the game is inactive.
        if not self.stats.game_active:
            self.play_button.draw_button()
        # Make the most recently drawn screen visible.
        pygame.display.flip()

    def _create_fleet(self):
        """Create the fleet to aliens."""
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_aliens_x = available_space_x // (2 * alien_width)

        # Determine the numberof rows of aliens that fit on the screen.
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        number_rows = available_space_y // (2 * alien_height)

        # Create the full fleet of aliens.
        for row_number in range(number_rows):
            # Create the first row of aliens.
            for alien_number in range(number_aliens_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        # Create an alien and place it in the row.
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def _update_aliens(self):
        """
        Check if the fleet is at an edge,
            then update the positions of all aliens in the fleet."""
        self._check_fleet_edges()
        self.aliens.update()

        # Look for alien-ship collisions.
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            print('Ship hit!!')
            self._ship_hit()

        # Check alien reching bottom.
        self._check_aliens_bottom()

    def _check_fleet_edges(self):
        """Response appropriately if any aliens have reached an edge."""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """Drop entire fleet and change the fleet's direction."""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _ship_hit(self):
        """Respond to the ship beibg hit by an alien."""
        if self.stats.ship_left > 0:
            # Decresment ship_left.
            self.stats.ship_left -= 1

            # Get rip of any remaining aliens and bullets.
            self.aliens.empty()
            self.bullets.empty()

            # Create a new fleet and center the ship.
            self._create_fleet()
            self.ship.center_ship()

            # Pause
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_aliens_bottom(self):
        """Check if any aliens have reached the bottom of the screen."""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                # Treat this the same as if the ship got hit.
                self._ship_hit()
                break
class AlienAttack:
    """Overall class to manage game assests and characterstics of game"""
    def __init__(self):
        """Initialize the game , and create game resources"""
        pygame.init()
        self.setting = Setting()
        self.bullets = pygame.sprite.Group(
        )  # use for collecting similar type of object
        self.screen = pygame.display.set_mode(
            (0, 0), pygame.FULLSCREEN
        )  # 0 width and 0 length expresses the full screen
        self.setting.screen_width = self.screen.get_rect().width
        self.setting.screen_height = self.screen.get_rect().height
        # pygame.display.set_caption("Alien Invasion")
        self.ship = Ship(self)
        self.enemy = pygame.sprite.Group()
        self.stats = GameStats(self)
        self.score_board = ScoreBoard(self)  #create a score board
        self._create_fleet()
        # as we need only one button then we need to call it once
        self.play_button = Button(self, "Play")

    def _create_fleet(self):
        """Create a fleet of alien"""

        new_enemy = Enemy(self)
        enemy_width, enemy_height = new_enemy.rect.size
        available_space_x = self.setting.screen_width - (2 * enemy_width)
        number_enemy_x = available_space_x // (2 * enemy_width)

        # determine the number of rows that will fit
        ship_height = self.ship.ship_rect.height
        available_space_y = self.setting.screen_height - (
            3 * enemy_height) - ship_height
        number_rows = available_space_y // (2 * enemy_height)

        # create a full fleet of aliens
        for row_number in range(number_rows + 1):
            for enemy_number in range(number_enemy_x + 1):
                self._create_alien(enemy_number, row_number)

    def _create_alien(self, enemy_number, row_number):
        new_enemy = Enemy(self)
        enemy_width, enemy_height = new_enemy.rect.size
        new_enemy.x = enemy_width + 2 * enemy_width * enemy_number
        new_enemy.rect.x = new_enemy.x
        new_enemy.rect.y = new_enemy.rect.height + 2 * new_enemy.rect.height * row_number
        self.enemy.add(new_enemy)

    def run_game(self):
        """Start the main loop for game"""
        while True:
            self._check_event()
            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_enemy()
            self._update_screen()

    def _ship_hit(self):
        """Respond to the ship being hit by alien"""
        # decrement ship left
        if self.stats.ships_left > 0:
            self.stats.ships_left -= 1
            self.score_board.prep_ships()

            # get rid of any remaining aliens and bulllets
            self.enemy.empty()
            self.bullets.empty()

            # Create a new fleet
            self._create_fleet()
            self.ship.center_ship()

            # pause
            sleep(0.5)
        else:
            self.stats.game_active = False
            self.stats.reset_stat()
            self.ship.center_ship()
            pygame.mouse.set_visible(True)
            self.stats.level = 0

    def _update_enemy(self):
        """Update the position of enemy ships"""
        self._check_fleet_edges()
        self.enemy.update()
        # Look for alien-ship collision
        if pygame.sprite.spritecollideany(
                self.ship,
                self.enemy):  # use for collision bw images or rectangles
            self._ship_hit()
        self._check_enemy_bottom()

    def _check_fleet_edges(self):
        """Respond appropriatly if any aliens have reached an edge"""
        for enemy in self.enemy.sprites():
            if enemy.check_edge():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """Drop the entire fleet and change the fleet's direction"""
        for enemy in self.enemy.sprites():
            enemy.rect.y += self.setting.fleet_drop_speed
        self.setting.fleet_direction *= -1

    def _update_bullets(self):
        self.bullets.update()

        # get rid of the bullets that have disapperead
        for bullet in self.bullets.copy():
            if bullet.rect.y <= 0:
                self.bullets.remove(bullet)
        self._check_bullet_enemy_collision()

    def _check_bullet_enemy_collision(self):
        """Respond to bullet - alien collision"""
        # check for any bullet that have hit enemy
        # if so , get rid of the bullet and the enemy
        collisions = pygame.sprite.groupcollide(self.bullets, self.enemy, True,
                                                True)
        if not self.enemy:
            self.bullets.empty()
            self._create_fleet()
            self.setting.increase_speed()

            #increase level
            self.stats.level += 1
            self.score_board.prep_level()
        if collisions:
            for enemy in collisions.values():
                self.stats.score += self.setting.enemy_point * len(enemy)
            self.score_board.prep_score()
            self.score_board.check_high_score()

    def _check_event(self):
        """Response to keypress and mouse event"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_event(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """Start a new game when the player clicked clicks play"""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            self.stats.reset_stat()
            self.score_board.prep_score()
            self.setting.initialize_dynamic_setting()
            self.stats.game_active = True
            self.score_board.prep_level()
            pygame.mouse.set_visible(False)
            self.score_board.prep_ships()
            # Get rid of any remaining aliens and bullets
            self.enemy.empty()
            self.bullets.empty()

            # create a new fleet and center the ship
            self._create_fleet()
            self.ship.center_ship()

    def _check_keydown_events(self, event):
        """Response to keyup events"""
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_UP:
            self.ship.moving_up = True
        elif event.key == pygame.K_DOWN:
            self.ship.moving_down = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()

    def _fire_bullet(self):
        if len(self.bullets) < self.setting.bullet_alloewed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _check_keyup_event(self, event):
        """Response to keyup events"""
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = False
        elif event.key == pygame.K_UP:
            self.ship.moving_up = False
        elif event.key == pygame.K_DOWN:
            self.ship.moving_down = False

    def _update_screen(self):
        """update images on the screen, and flip to the new screen"""
        self.screen.fill(self.setting.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self.enemy.draw(self.screen)
        self.score_board.show_score()
        # draw the play button if the game is inactive
        if not self.stats.game_active:
            self.play_button.draw_button()
        """Make the latest change visible on screen"""
        pygame.display.flip()

    def _check_enemy_bottom(self):
        """check if any aliens have reached the bottom of screen"""
        screen_rect = self.screen.get_rect()
        for enemy in self.enemy.sprites():
            if enemy.rect.bottom >= screen_rect.bottom:
                self._ship_hit()
                break
示例#18
0
class AlienInvasion:
    """Overall class to manage game assets and behavior."""
    def __init__(self):
        """Initialize the game, and create game ressources."""
        pygame.init()
        self.settings = Settings()
        self.clock = pygame.time.Clock()

        # # Switch the comments on these blocks for fullscreen or window screen
        # self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        # self.settings.screen_width = self.screen.get_rect().width
        # self.settings.screen_height = self.screen.get_rect().height

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption('COVID Invasion')

        # Create an instance to store game statistics
        #   and create a scoreboard
        self.stats = GameStats(self)
        self.scoreboard = Scoreboard(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        self.play_button = Button(self, 'Play')

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self._check_events()

            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._update_aliens()

            self._update_screen()
            self.clock.tick(300)

    def _check_events(self):
        """Response to keypresses ans mouse events"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)

    def _check_play_button(self, mouse_pos):
        """Start a new game when the player hit start"""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            self._start_game()

    def _start_game(self):
        """Start the game"""
        # Reset the dynamic settings
        self.settings.init_dynamic()

        # Hide the mouse cursor
        pygame.mouse.set_visible(False)

        # Reset the game stat
        self.stats.reset_stat()
        self.stats.game_active = True
        self.scoreboard.prep_score()
        self.scoreboard.prep_level()
        self.scoreboard.prep_ships()

        # Get rid of all remaining alien and bullets
        self.aliens.empty()
        self.bullets.empty()

        # Create a new fleet and center the ship
        self._create_fleet()
        self.ship.center_ship()

    def _check_keydown_events(self, event):
        """response to key presses."""
        if event.key in (pygame.K_RIGHT, pygame.K_d):
            self.ship.moving_right = True
        elif event.key in (pygame.K_LEFT, pygame.K_a):
            self.ship.moving_left = True
        elif event.key == pygame.K_SPACE:
            self._fire_bullet()
        elif event.key == pygame.K_p:
            self._start_game()
        elif event.key == pygame.K_ESCAPE:
            sys.exit()

    def _check_keyup_events(self, event):
        """response to key releases."""
        if event.key in (pygame.K_RIGHT, pygame.K_d):
            self.ship.moving_right = False
        elif event.key in (pygame.K_LEFT, pygame.K_a):
            self.ship.moving_left = False

    def _fire_bullet(self):
        """Create a new bullet and add it to the bullet group"""
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullets(self):
        """Update position of the bullets and get rid of old ones."""
        # Update bullets position
        self.bullets.update()

        # Get rid of bullets that have disappeared
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        self._check_bullet_aliens_collision()

    def _check_bullet_aliens_collision(self):
        """Respond to bullet-aliens collisions"""
        # Remove any bullets and aliens that collided
        collisions = pygame.sprite.groupcollide(
            self.bullets,
            self.aliens,
            True,  # dokill1: if True, the bullet is gone if coll
            True  # dokill2: if True, the alien is gone if coll
        )

        if collisions:
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)

            self.scoreboard.prep_score()
            self.scoreboard.check_high_score()

        # Create a new fleet if every aliens is down
        if not self.aliens:
            # Destroy existing bullets and create new fleet
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_stats()

            # Increase the level
            self.stats.level += 1
            self.scoreboard.prep_level()

    def _create_fleet(self):
        """Create the fleet of aliens"""
        # Create an alien and find the numbre of aliens in a row
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        available_space = self.settings.screen_width - (2 * alien_width)
        number_alien_x = available_space // (2 * alien_width)

        # Determine the number of rows of aliens that fit on the screen
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) -
                             ship_height)
        number_rows = available_space_y // (2 * alien_height)

        # Creating the full fleet of aliens
        for row_number in range(number_rows):
            for alien_number in range(number_alien_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        """Create an alien and place it in the row"""
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien.x_pos = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x_pos
        alien.rect.y = alien_height + 2 * alien_height * row_number
        self.aliens.add(alien)

    def _update_aliens(self):
        """
        Check if the fleet is at an edge,
            then update the position of all aliens in the fleet"""
        self._check_fleet_edge()
        self.aliens.update()

        # Look for alien-ship collision
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()

        # Looks for aliens hitting the bottom of the screen
        self._check_aliens_bottom()

    def _check_fleet_edge(self):
        for alien in self.aliens.sprites():
            if alien.check_edge():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """Drop the entire fleet and change direction"""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.alien_drop_speed
        self.settings.fleet_direction *= -1

    def _ship_hit(self):
        """Respond to the ship being hit by an alien"""
        if self.stats.ships_left > 0:
            # Decrement ship_left
            self.stats.ships_left -= 1
            self.scoreboard.prep_ships()

            # Get rid of any remaining bullets and aliens
            self.bullets.empty()
            self.aliens.empty()

            # Create a new fleet and recenter the ship
            self._create_fleet()
            self.ship.center_ship()

            # Little pause for the suspens
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_aliens_bottom(self):
        """Check if the aliens have reach the bottom of the screen"""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                # Same treatment as the ship hit
                self._ship_hit()
                break

    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
        self.screen.fill(self.settings.background_color)
        self.ship.blitme()

        for bullet in self.bullets.sprites():
            bullet.draw_bullet()

        self.aliens.draw(self.screen)

        # Draw the score informations
        self.scoreboard.show_score()

        if not self.stats.game_active:
            self.play_button.draw_button()

        pygame.display.flip()