Ejemplo n.º 1
0
    def _main_loop(self):
        gameover_flash_time = 25
        gameover_flash_count = 0
        self.__gameover_show_flag = True
        self.__is_quit_game = False

        clock = pygame.time.Clock()
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        TankGame().quit_game_flag = self.__is_quit_game
                        return
                    elif event.key in [
                            pygame.K_UP, pygame.K_DOWN, pygame.K_w, pygame.K_s
                    ]:
                        self.__is_quit_game = not self.__is_quit_game

            gameover_flash_count += 1
            if gameover_flash_count > gameover_flash_time:
                self.__gameover_show_flag = not self.__gameover_show_flag
                gameover_flash_count = 0
            if self.__is_quit_game:
                self.__tank_rect.right, self.__tank_rect.top = self.__quit_rect.left - 10, self.__quit_rect.top
            else:
                self.__tank_rect.right, self.__tank_rect.top = self.__restart_rect.left - 10, self.__restart_rect.top

            self._draw_interface()

            pygame.display.update()
            clock.tick(60)
Ejemplo n.º 2
0
    def _main_loop(self):
        game_tip_flash_time = 25
        game_tip_flash_count = 0
        self.__game_tip_show_flag = True
        self.__is_multiplayer_mode = False
        clock = pygame.time.Clock()
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        TankGame(
                        ).multiplayer_mode = self.__is_multiplayer_mode
                        return
                    elif event.key == pygame.K_UP or event.key == pygame.K_DOWN or event.key == pygame.K_w or event.key == pygame.K_s:
                        self.__is_multiplayer_mode = not self.__is_multiplayer_mode

            game_tip_flash_count += 1
            if game_tip_flash_count > game_tip_flash_time:
                self.__game_tip_show_flag = not self.__game_tip_show_flag
                game_tip_flash_count = 0

            if self.__is_multiplayer_mode:
                self.__tank_rect.right, self.__tank_rect.top = self.__players_rect.left - 10, self.__players_rect.top
            else:
                self.__tank_rect.right, self.__tank_rect.top = self.__player_rect.left - 10, self.__player_rect.top

            self._draw_interface()
            pygame.display.update()
            clock.tick(60)
Ejemplo n.º 3
0
 def _init_text(self):
     config = self.config
     self.__font_render = self.__font.render(
         'LEVEL%d' % (TankGame().level + 1),
         True,
         (255, 255, 255)  # White
     )
     self.__font_rect = self.__font_render.get_rect()
     self.__font_rect.centerx, self.__font_rect.centery = config.WIDTH / 2, config.HEIGHT / 2
Ejemplo n.º 4
0
 def show(self):
     self._init_game_window()
     self._init_text()
     self.__load_level_file()
     self.__init_entities()
     self.__init_user_event()
     self.__init_tanks()
     self.__init_collision_config()
     self.__play_sound('start')
     self.__is_win_flag = False
     self.__has_next_loop = True
     self._main_loop()
     TankGame().is_win = self.__is_win_flag
Ejemplo n.º 5
0
    def __init_tanks(self):
        self.__tank_player1 = self.__tank_factory.create_tank(
            self.__player_spawn_point[0], TankFactory.PLAYER1_TANK)
        self.__entities.add(self.__tank_player1)

        self.__tank_player2 = None
        if TankGame().multiplayer_mode:
            self.__tank_player2 = self.__tank_factory.create_tank(
                self.__player_spawn_point[1], TankFactory.PLAYER2_TANK)
            self.__entities.add(self.__tank_player2)
        # 敌方坦克
        for position in self.__enemy_spawn_point:
            self.__entities.add(
                self.__tank_factory.create_tank(position,
                                                TankFactory.ENEMY_TANK))
Ejemplo n.º 6
0
    def __dispatch_player_operation(self):
        key_pressed = pygame.key.get_pressed()
        key_maps = {
            'dir': {
                self.__tank_player1: {
                    pygame.K_w: DIRECTION.UP,
                    pygame.K_s: DIRECTION.DOWN,
                    pygame.K_a: DIRECTION.LEFT,
                    pygame.K_d: DIRECTION.RIGHT,
                },
                self.__tank_player2: {
                    pygame.K_UP: DIRECTION.UP,
                    pygame.K_DOWN: DIRECTION.DOWN,
                    pygame.K_LEFT: DIRECTION.LEFT,
                    pygame.K_RIGHT: DIRECTION.RIGHT,
                },
            },
            'fire': {
                self.__tank_player1: pygame.K_SPACE,
                self.__tank_player2: pygame.K_KP0,
            },
        }

        # 玩家一, WSAD移动, 空格键射击
        player_tank_list = []
        if self.__tank_player1.health >= 0:
            player_tank_list.append(self.__tank_player1)
        if TankGame().multiplayer_mode and (self.__tank_player1.health >= 0):
            player_tank_list.append(self.__tank_player2)

        for tank in player_tank_list:
            for key, dir in key_maps['dir'][tank].items():
                if key_pressed[key]:
                    self.__entities.remove(tank)
                    tank.move(dir, self.__scene_elements,
                              self.__entities.player_tanks,
                              self.__entities.enemy_tanks, self.__home)
                    tank.roll()
                    self.__entities.add(tank)
                    break

            if key_pressed[key_maps['fire'][tank]]:
                bullet = tank.shoot()
                if bullet:
                    self.__play_sound(
                        'fire') if tank._level < 2 else self.__play_sound(
                            'Gunfire')
                    self.__entities.add(bullet)
Ejemplo n.º 7
0
    def _init_resources(self):
        config = self.config
        self.__sounds = TankGame().sounds
        self.__other_images = config.OTHER_IMAGE_PATHS
        self.__home_images = config.HOME_IMAGE_PATHS
        self.__background_img = pygame.image.load(
            self.__other_images.get('background'))
        self.__font = pygame.font.Font(config.FONTPATH, config.HEIGHT // 35)

        self.__border_len = config.BORDER_LEN
        self.__grid_size = config.GRID_SIZE
        self.__screen_width, self.__screen_height = config.WIDTH, config.HEIGHT
        self.__panel_width = config.PANEL_WIDTH
        self.__tank_factory = TankFactory(self.config)
        self.__scene_factory = SceneFactory(self.config)
        self.__scene_elements = None
Ejemplo n.º 8
0
 def _draw_interface(self):
     screen = TankGame().screen
     screen.fill((0, 0, 0))
     screen.blit(self.__background_img, (0, 0))
     self.__scene_elements.draw(screen, 1)
     self.__entities.draw(screen, 1)
     self.__scene_elements.draw(screen, 2)
     self.__home.draw(screen)
     self.__entities.draw(screen, 2)
     self.__draw_game_panel()
     pygame.display.flip()
Ejemplo n.º 9
0
 def _init_text(self):
     config = self.config
     if TankGame().is_win:
         self.__font_render = self.__font.render(
             'Congratulations, You win!', True, (255, 255, 255))
     else:
         self.__font_render = self.__font.render('Sorry, You fail!', True,
                                                 (255, 0, 0))
     self.__font_rect = self.__font_render.get_rect()
     self.__font_rect.centerx, self.__font_rect.centery = config.WIDTH / 2, config.HEIGHT / 3
     self.__restart_render_white = self.__font.render(
         'RESTART', True, (255, 255, 255))
     self.__restart_render_red = self.__font.render('RESTART', True,
                                                    (255, 0, 0))
     self.__quit_render_white = self.__font.render('QUIT', True,
                                                   (255, 255, 255))
     self.__quit_render_red = self.__font.render('QUIT', True, (255, 0, 0))
Ejemplo n.º 10
0
    def __draw_game_panel(self):
        color_white = (255, 255, 255)
        dynamic_text_tips = {
            16: {
                'text': 'Health: %s' % self.__tank_player1.health
            },
            17: {
                'text': 'Level: %s' % self.__tank_player1._level
            },
            23: {
                'text': 'Game Level: %s' % (TankGame().level + 1)
            },
            24: {
                'text': 'Remain Enemy: %s' % self.__total_enemy_num
            }
        }
        if self.__tank_player2:
            dynamic_text_tips[20] = {
                'text': 'Health: %s' % self.__tank_player2.health
            }
            dynamic_text_tips[21] = {
                'text': 'Level: %s' % self.__tank_player2._level
            }
        else:
            dynamic_text_tips[20] = {'text': 'Health: %s' % None}
            dynamic_text_tips[21] = {'text': 'Level: %s' % None}

        for pos, tip in dynamic_text_tips.items():
            tip['render'] = self.__font.render(tip['text'], True, color_white)
            tip['rect'] = tip['render'].get_rect()
            tip['rect'].left, tip[
                'rect'].top = self.__screen_width + 5, self.__screen_height * pos / 30

        screen = TankGame().screen
        for pos, tip in self.__fix_text_tips.items():
            screen.blit(tip['render'], tip['rect'])
        for pos, tip in dynamic_text_tips.items():
            screen.blit(tip['render'], tip['rect'])
Ejemplo n.º 11
0
    def _draw_interface(self):
        screen = TankGame().screen
        screen.blit(self.__background_img, (0, 0))
        screen.blit(self.__logo_img, self.__logo_rect)
        if self.__game_tip_show_flag:
            screen.blit(self.__game_tip, self.__game_tip_rect)

        if not self.__is_multiplayer_mode:
            screen.blit(self.__tank_cursor, self.__tank_rect)
            screen.blit(self.__player_render_red, self.__player_rect)
            screen.blit(self.__players_render_white, self.__players_rect)
        else:
            screen.blit(self.__tank_cursor, self.__tank_rect)
            screen.blit(self.__player_render_white, self.__player_rect)
            screen.blit(self.__players_render_red, self.__players_rect)
Ejemplo n.º 12
0
 def _init_game_window(self):
     TankGame().init_game_window(
         (self.config.WIDTH + self.config.PANEL_WIDTH, self.config.HEIGHT))
Ejemplo n.º 13
0
    def __load_level_file(self):
        self.__scene_elements = groups.SceneElementsGroup()

        elems_map = {
            'B': SceneFactory.BRICK,
            'I': SceneFactory.IRON,
            'C': SceneFactory.ICE,
            'T': SceneFactory.TREE,
            'R': SceneFactory.RIVER_1
        }

        home_walls_position = []
        home_position = ()

        f = open(TankGame().level_file, errors='ignore')
        num_row = -1
        for line in f.readlines():
            line = line.strip('\n')
            # 注释
            if line.startswith('#') or (not line):
                continue
            # 敌方坦克总数量
            elif line.startswith('%TOTALENEMYNUM'):
                self.__total_enemy_num = 20 + TankGame(
                ).level  #int(line.split(':')[-1])
            # 场上敌方坦克最大数量
            elif line.startswith('%MAXENEMYNUM'):
                self.max_enemy_num = 6 + TankGame(
                ).level  #int(line.split(':')[-1])
            # 大本营位置
            elif line.startswith('%HOMEPOS'):
                home_position = line.split(':')[-1]
                home_position = [
                    int(home_position.split(',')[0]),
                    int(home_position.split(',')[1])
                ]
                home_position = (self.__border_len +
                                 home_position[0] * self.__grid_size,
                                 self.__border_len +
                                 home_position[1] * self.__grid_size)
            # 大本营周围位置
            elif line.startswith('%HOMEAROUNDPOS'):
                home_walls_position = line.split(':')[-1]
                home_walls_position = [[
                    int(pos.split(',')[0]),
                    int(pos.split(',')[1])
                ] for pos in home_walls_position.split(' ')]
                home_walls_position = [
                    (self.__border_len + pos[0] * self.__grid_size,
                     self.__border_len + pos[1] * self.__grid_size)
                    for pos in home_walls_position
                ]
            # 我方坦克初始位置
            elif line.startswith('%PLAYERTANKPOS'):
                self.__player_spawn_point = line.split(':')[-1]
                self.__player_spawn_point = [[
                    int(pos.split(',')[0]),
                    int(pos.split(',')[1])
                ] for pos in self.__player_spawn_point.split(' ')]
                self.__player_spawn_point = [
                    (self.__border_len + pos[0] * self.__grid_size,
                     self.__border_len + pos[1] * self.__grid_size)
                    for pos in self.__player_spawn_point
                ]
            # 敌方坦克初始位置
            elif line.startswith('%ENEMYTANKPOS'):
                self.__enemy_spawn_point = line.split(':')[-1]
                self.__enemy_spawn_point = [[
                    int(pos.split(',')[0]),
                    int(pos.split(',')[1])
                ] for pos in self.__enemy_spawn_point.split(' ')]
                self.__enemy_spawn_point = [
                    (self.__border_len + pos[0] * self.__grid_size,
                     self.__border_len + pos[1] * self.__grid_size)
                    for pos in self.__enemy_spawn_point
                ]
            # 地图元素
            else:
                num_row += 1
                for num_col, elem in enumerate(line.split(' ')):
                    position = self.__border_len + num_col * self.__grid_size, self.__border_len + num_row * self.__grid_size

                    scene_element = None
                    if elem in elems_map:
                        scene_element = self.__scene_factory.create_element(
                            position, elems_map[elem])
                    elif elem == 'R':
                        scene_element = self.__scene_factory.create_element(
                            position,
                            random.choice(
                                [SceneFactory.RIVER_1, SceneFactory.RIVER_2]))
                    if scene_element is not None:
                        self.__scene_elements.add(scene_element)
        self.__home = Home(position=home_position,
                           imagefile=self.__home_images,
                           walls_position=home_walls_position)
Ejemplo n.º 14
0
 def _draw_interface(self):
     screen = TankGame().screen
     screen.blit(self.__background_img, (0, 0))
     screen.blit(self.__logo_img, self.__logo_rect)
     screen.blit(self.__font_render, self.__font_rect)
     screen.blit(self.__loadbar, self.__loadbar_rect)
     screen.blit(self.__tank_cursor_img, self.__tank_rect)
     pygame.draw.rect(
         screen,
         (192, 192, 192),  # Gray
         (self.__loadbar_rect.left + 8, self.__loadbar_rect.top + 8,
          self.__tank_rect.left - self.__loadbar_rect.left - 8,
          self.__tank_rect.bottom - self.__loadbar_rect.top - 16))
     self.__tank_rect.left += 8
Ejemplo n.º 15
0
 def show(self):
     TankGame().init_game_window()
     self._init_text()
     self._init_bottons()
     self._main_loop()
     pass
Ejemplo n.º 16
0
 def config(self):
     return TankGame().config
Ejemplo n.º 17
0
import config
from modules.TankGame import TankGame

game_instance = None

if __name__ == '__main__':
    TankGame(config)
Ejemplo n.º 18
0
    def _draw_interface(self):
        screen = TankGame().screen
        screen.blit(self.__background_img, (0, 0))

        if self.__gameover_show_flag:
            screen.blit(self.__gameover_logo, self.__gameover_logo_rect)

        screen.blit(self.__font_render, self.__font_rect)

        if not self.__is_quit_game:
            screen.blit(self.__tank_cursor, self.__tank_rect)
            screen.blit(self.__restart_render_red, self.__restart_rect)
            screen.blit(self.__quit_render_white, self.__quit_rect)
        else:
            screen.blit(self.__tank_cursor, self.__tank_rect)
            screen.blit(self.__restart_render_white, self.__restart_rect)
            screen.blit(self.__quit_render_red, self.__quit_rect)