Пример #1
0
def run_game():
    # 初始化游戏并创建一个屏幕对象
    pygame.init()
    pygame.display.set_caption('Alien Invasion')

    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    ship = Ship(ai_settings, screen)
    play_button = Button(ai_settings, screen, 'Play')

    bullets = Group()
    aliens = Group()
    gf.create_fleet(ai_settings, screen, aliens, ship)
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    # 开始游戏的主循环
    while True:
        gf.check_events(ai_settings, screen, ship, bullets, stats, play_button,
                        aliens, sb)
        if not stats.game_over:
            ship.update()
            gf.update_bullets(ai_settings, screen, bullets, aliens, ship,
                              stats, sb)
            gf.update_aliens(ai_settings, screen, aliens, bullets, ship, stats,
                             sb)
        gf.update_screen(ai_settings, screen, ship, bullets, aliens, stats,
                         play_button, sb)
Пример #2
0
def run_game():
    pygame.init()
    screen_settings = Settings()
    stats = GameStats(screen_settings)

    screen = pygame.display.set_mode(
        (screen_settings.screen_width, screen_settings.screen_height))
    ship = Ship(screen)
    pygame.display.set_caption('Alien Inv')
    screen_y = 0
    background = Background(screen_settings.bg_image, [0, 0])
    play_button = Button(screen_settings, screen, "Play")
    bullets = Group()
    enemies = Group()

    while True:  # Game Loop
        gf.check_events(
            screen_settings,
            screen,
            ship,
            bullets,
            stats,
            play_button,
            enemies,
        )
        if stats.game_active:
            ship.update()
            gf.update_bullets(bullets, enemies)
            gf.update_enemies(enemies, ship, screen_settings, stats, screen,
                              bullets)
        gf.update_screen(screen_settings, screen, ship, screen_y, background,
                         bullets, enemies, play_button, stats)
        screen_y += screen_settings.bg_speed
Пример #3
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("Alien Invasion")

    # 创建一艘飞船
    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, ship, bullets)
        ship.update()
        gf.update_bullets(ai_settings, screen, ship, aliens, bullets)
        gf.update_aliens(ai_settings, ship, aliens)
        gf.update_screen(ai_settings, screen, ship, aliens, bullets)
        time.sleep(0.01)
Пример #4
0
 def __init__(self):
     self.board = Board()
     self.ships = dict()
     self.ships['carrier'] = Ship(5)
     self.ships['battleship'] = Ship(4)
     self.ships['cruiser'] = Ship(3)
     self.ships['submarine'] = Ship(3)
     self.ships['destroyer'] = Ship(2)
Пример #5
0
 def spawn_ship(self):
     ship = Ship(
         weapon_locations=[(-5, 2), (5, 2)],
         shield=Shield(**random.choice(self.shield_selection).__dict__),
         reactor=Reactor(**random.choice(self.reactor_selection).__dict__))
     for index, _ in enumerate(ship.weapon_locations):
         weapon = Weapon(**random.choice(self.weapon_selection).__dict__)
         ship.equip_weapon(weapon, index)
     return ship, self.position
Пример #6
0
def check_keydown_events(event, ai_settings: Settings, screen, ship: Ship,
                         bullets: Group):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_SPACE:
        fire_bullet(bullets, ai_settings, screen, ship)
    elif event.key == pygame.K_q:
        sys.exit()
Пример #7
0
def update_screen(ai_settings: Settings, screen, ship: Ship, aliens: Group,
                  bullets: Group, stats: GameStats, play_button: Button):
    # Draw(update) the screen.
    screen.fill(ai_settings.bg_color)
    ship.blitme()
    aliens.draw(screen)
    for bullet in bullets:
        bullet.draw_bullet()
    if not stats.game_active:
        play_button.draw_botton()

    pygame.display.flip()
Пример #8
0
def ship_hit(ai_settings: Settings, stats: GameStats, screen, ship: Ship,
             aliens: Group, bullets: Group):
    if stats.ships_left > 0:
        stats.ships_left -= 1
        aliens.empty()
        bullets.empty()

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

        sleep(0.5)
    else:
        stats.game_active = False
Пример #9
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("Alien Invasion")
    ship = Ship(ai_settings, screen)
    bullets = Group()
    alien = Alien(ai_settings, screen)
    while True:
        gf.check_events(ai_settings, screen, ship, bullets)
        ship.update()
        gf.update_bullet(bullets)
        gf.update_screen(ai_settings, screen, ship, alien, bullets)
Пример #10
0
 def placing(self, effectiveX, effectiveY, gs, player_name):
     """!
     @pre A player has selected a location on the grid to attempt to place a ship
     @post The message is updated. If the location is valid, the ship is placed and the game proceeds to the next ship placement (or to shooting if all ships placed).
     @param effectiveX int: The X-coordinate of the grid the ship will attempt to be placed (0-19)
     @param effectiveY int: The Y-coordinate of the grid the ship will attempt to be placed (0-9)
     @param gs GameState: The object representing the current state of the game. This will be modified upon successful ship placement.
     @param player_name string: The name of the current player to include in the message
     """
     player_ships = gs.p1Ships if gs.is_P1_turn else gs.p2Ships
     if self.checkValidShip(gs.is_P1_turn, effectiveX, effectiveY,
                            gs.lenShip, gs.shipDir):
         newShip = Ship()
         self.placeShip(newShip, effectiveX, effectiveY, gs.lenShip,
                        gs.shipDir)
         player_ships.append(newShip)
         gs.lenShip += 1
         gs.msg = player_name + " place your " + str(
             gs.lenShip) + " ship. Press \"R\" to rotate."
         # If player one finishes placing, reset things for player two's turn
         if gs.lenShip > gs.numShipsPerPlayer:
             if gs.is_P1_turn:
                 gs.msg = "Now P2, place your 1 ship. Press \"R\" to rotate."
                 gs.shipDir = 0
                 gs.is_P1_turn = False
                 gs.lenShip = 1
             else:  #P2 turn
                 gs.is_P1_turn = True
                 gs.is_placing = False
                 gs.is_shooting = True
                 gs.msg = "All ships placed. P1 shoot first."
     else:
         gs.msg = player_name + " invalid ship location! Press \"R\" to rotate."
Пример #11
0
 def prep_ship(self):
     self.ships = Group()
     for ship_number in range(self.stats.ships_left):
         ship = Ship(self.ai_settings, self.screen)
         ship.rect.x = 10 + ship_number * ship.rect.width
         ship.rect.y = 10
         self.ships.add(ship)
Пример #12
0
def train(ship_name=config.SHIP_NAME,
          full_cycles=config.FULL_CYCLES,
          maroon_cycles=config.MAROON_CYCLES,
          max_pirates_in_ship=config.MAX_PIRATES_IN_SHIP,
          min_pirates_in_ship=config.MIN_PIRATES_IN_SHIP):
    """
    Train mode: runs a local UnityEnvironment, general loop is:
         - Generate pirates until you have some minimum amount in the ship
         - Run matches to rank pirates
         - Cull the worse performing pirates in the ship
    :param ship_name: (str) name of the ship
    :param full_cycles: (int) number of  full pirateAI cycles to run
    :param maroon_cycles: (int) number of maroonings to run for each hyperopt training
    :param max_pirates_in_ship: (int) max number of pirates in ship
    :param min_pirates_in_ship: (int) min number of pirates in ship
    """
    with Ship(ship_name=ship_name) as ship:
        for _ in range(full_cycles):
            pirates_in_ship = ship.headcount()
            while pirates_in_ship < max_pirates_in_ship:
                ship.more_pirates()  # Not enough hands on deck
                pirates_in_ship = ship.headcount()
            with Island(brain='PirateBrain',
                        file_name='local/unityenv/Island') as island:
                for _ in range(maroon_cycles):
                    island.maroon(ship=ship)
            if pirates_in_ship > min_pirates_in_ship:
                ship.less_pirates()
Пример #13
0
    def __init__(self,
                 screen: pygame.Surface,
                 username: str = None,
                 solo: bool = True,
                 is_left: bool = True):
        """
        Initialize the player's game.
        :param screen: surface to display game
        :param username: player's username
        :param solo: True if single player False if multi players
        :param is_left: True if solo and if multi player and player 1
        """
        # game settings
        self.end_game = False
        self.username = username
        self.screen = screen
        self.is_left = is_left
        self.solo = solo

        # display settings
        self.screenWidth, self.screenHeight = pygame.display.get_surface(
        ).get_size()
        self.game_window_width = self.screenWidth if self.solo else self.screenWidth / 2
        self.game_window_height = self.screenHeight
        self.game_window = pygame.Surface(
            (self.game_window_width, self.game_window_height))
        self.rect = self.screen.get_rect(
            left=0 if is_left else self.screenWidth / 2)

        # creating game objects
        self.ship = Ship(self.game_window, solo=solo, is_left=is_left)
        self.pipes = []
        self.pipes_number = 2 if solo else 1
        for i in range(0, self.pipes_number):
            self.pipes.append(
                Pipes(self.game_window,
                      first=True if (i == 0) else False,
                      single_player=solo,
                      is_left=is_left))
        self.bg = Background(self.game_window, is_left=is_left)
        self.hourglass = Hourglass(self.game_window)

        # control settings
        if is_left:
            self.jump_key = pygame.K_SPACE
        else:
            self.jump_key = pygame.K_RETURN
Пример #14
0
def spawn_enemy():
    difficulty_choice = random.choice(["easy", "normal", "hard"])
    enemy_surface = random.choice(enemy_ships[difficulty_choice])
    enemy_ship = Ship(surface=enemy_surface)
    enemy = Enemy(ship=enemy_ship, difficulty=difficulty_choice)
    enemy.ship.pos_y = 1 - int(enemy.ship.height / 2)
    enemy.ship.pos_x = random.randint(30, W - enemy.ship.width)
    return enemy
Пример #15
0
 def prep_ships(self):
     """Show how many ships are left"""
     self.ships = Group()
     for ship_no in range(self.stats.ships_left):
         ship = Ship(self.sett, self.screen)
         ship.rect.x = 10 + ship_no * ship.rect.width
         ship.rect.y = self.screen_rect.bottom - 10
         self.ships.add(ship)
Пример #16
0
def run_game():
    all_setting = Settings()
    pygame.init()
    screen = pygame.display.set_mode((all_setting.width, all_setting.height))
    ship = Ship(screen, all_setting)
    pygame.display.set_caption('my first bullshit')

    bulls = Group()
    monsters = Group()

    while (True):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                gf.check_event_keydown(ship, bulls, all_setting, screen, event)
            elif event.type == pygame.KEYUP:
                gf.check_event_keyup(ship, bulls, all_setting, screen, event)

        ship.move()
        bulls.update()
        gf.update_screen(screen, ship, all_setting, bulls)
Пример #17
0
def run_game():
    """Initialize game, settings and create a screen object"""
    pygame.init()
    sounds = Sounds()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # Make the play button.
    play_button = Button(ai_settings, screen, 'Play')

    # Make a ship, a group of aliens and a group of bullets
    ship = Ship(ai_settings, screen)
    aliens = Group()
    bullets = Group()

    # Create a fleet of aliens
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Create an instance to store the game statistics and scoreboard
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # Start the main loop for the game.
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        sounds, aliens, bullets)

        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, sounds,
                              aliens, bullets)
            gf.update_aliens(ai_settings, stats, sb, screen, ship, aliens,
                             bullets)
            gf.update_screen(ai_settings, screen, sb, ship, aliens, bullets)
        else:
            gf.display_menu_screen(ai_settings, screen, play_button)
Пример #18
0
    def setUp(self):
        self.ship = Ship(ship_name='TestBoat')
        self.test_dnas = [str(uuid4()) for _ in range(10)]

        # Make a blank keras model for test pirates
        self.model_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'local', 'models'))
        test_model = Sequential()
        test_model.add(Flatten(input_shape=(128, 128, 3)))
        test_model.add(Dense(1))
        test_model.compile(optimizer='rmsprop', loss='mse')

        # Save models and create pirates
        self.test_pirates = []
        for i, dna in enumerate(self.test_dnas):
            test_model.save(self.model_path + '/' + dna + '.h5')
            self.test_pirates.append(Pirate(dna=dna))
            if i > len(self.test_dnas) - 5:
                break  # Leave some models un-saved

        # Add pirates to the ship
        # Add some pirates
        for i in range(2):
            self.ship._add_pirate(dna=self.test_dnas[i])
Пример #19
0
def rungame():
    # Initialize game,settings and create screen object.
    pygame.init()
    sett = Settings()
    screen = pygame.display.set_mode((sett.screen_width, sett.screen_height))
    pygame.display.set_caption("Alien Invasion")
    """"Instance initialization"""
    # Make instance of game stats.
    stats = GameStats(sett)
    # Make instance of scoreboard.
    sb = ScoreBoard(sett, screen, stats)
    # Make the play button.
    b_play = Button(sett, screen, "PLAY")

    # Make instance of ship.
    ship = Ship(sett, screen)
    # Make a group to store bullets and aliens.
    aliens = Group()
    bullets = Group()
    # Make instance of alien.
    alien = Alien(sett, screen)
    gf.create_fleet(sett, screen, ship, aliens)

    # Start the main loop for the game.
    while True:
        # Watch for keyboard and mouse events.
        gf.check_events(sett, screen, stats, sb, b_play, ship, aliens, bullets)

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

        # Redraw the screen during each pass through the loop.
        gf.update_screen(sett, screen, stats, sb, ship, aliens, bullets,
                         b_play)
Пример #20
0
def test(ship_name=config.SHIP_NAME,
         full_cycles=config.FULL_CYCLES,
         maroon_cycles=config.MAROON_CYCLES):
    """
    Test Mode: runs an external UnityEnvironment, general loop is:
        - Run matches to rank pirates
    :param ship_name: (str) name of the ship
    :param full_cycles: (int) number of  full pirateAI cycles to run
    :param maroon_cycles: (int) number of maroonings to run for each hyperopt training
    """
    with Ship(ship_name=ship_name) as ship:
        for _ in range(full_cycles):
            with Island(host_ip=config.WINDOWS_IP,
                        host_port=config.WINDOWS_PORT,
                        brain='PirateBrain') as island:
                for _ in range(maroon_cycles):
                    island.maroon(ship=ship)
Пример #21
0
    def __init__(self,
                 ship_args: {str, int},
                 num_rows_: int,
                 num_cols_: int,
                 blank_char_: str = '*') -> None:
        self.blank_char = blank_char_
        self.ships = []
        for ship_name, ship_size in ship_args.items():
            self.ships.append(Ship(ship_name, ship_size))

        self.players = []
        for player_num in range(2):
            player_type = self.pick_player_type(player_num)
            self.players.append(
                player_type(player_num, self.players, self.ships, num_rows_,
                            num_cols_, blank_char_))
        self._cur_player_turn = 0
Пример #22
0
    def collide_with_ship(self, ship: Ship):
        """
        Check if ship collide with top of bottom pipe
        :param ship:
        :return:
        """
        ship_mask = ship.get_mask()
        top_mask = pygame.mask.from_surface(self.image["up"])
        bottom_mask = pygame.mask.from_surface(self.image["down"])

        top_offset = round(self.x_pos - ship.x_pos), round(self.y_pos_up - round(ship.y_pos))
        bottom_offset = round(self.x_pos - ship.x_pos), round(self.y_pos_down - round(ship.y_pos))

        b_point = ship_mask.overlap(bottom_mask, bottom_offset)
        t_point = ship_mask.overlap(top_mask, top_offset)

        if t_point or b_point:
            return True

        return False
Пример #23
0
def eval_genome(genomes, config):
    global GEN, SCREEN
    GEN += 1
    nets = []
    ge = []
    ships = []

    for _, g in genomes:
        net = neat.nn.FeedForwardNetwork.create(g, config)
        nets.append(net)
        ships.append(Ship(SCREEN))
        g.fitness = 0
        ge.append(g)

    bg = Background(SCREEN, is_left=True)
    pipes = [PipesIA(SCREEN)]

    score = 0
    clock = pygame.time.Clock()

    play = True
    while play:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                play = False
                pygame.quit()
                quit()

        pipe_ind = 0
        if len(ships) > 0:
            if len(pipes) > 1 and ships[0].x_pos > pipes[0].x_pos + pipes[
                    0].width:  # if we passed the pipe
                pipe_ind = 1  # we will look at the second pipe
        else:
            play = False
            break

        for x, ship in enumerate(ships):
            ship.move()
            ge[x].fitness += 0.1

            output = nets[x].activate(
                (ship.y_pos,
                 abs(ship.y_pos - pipes[pipe_ind].y_pos_up +
                     pipes[pipe_ind].height),
                 abs(ship.y_pos - pipes[pipe_ind].y_pos_down)))

            if output[0] > 0.5:
                ship.jump()

        remove = []
        add_pipe = False
        for pipe in pipes:

            for x, ship in enumerate(ships):
                if pipe.collide_with_ship(ship):
                    ge[x].fitness -= 1
                    ships.pop(x)
                    nets.pop(x)
                    ge.pop(x)

                if not pipe.passed and pipe.x_pos < ship.x_pos:
                    pipe.passed = True
                    add_pipe = True

            if pipe.x_pos + pipe.width < 0:
                remove.append(pipe)

            pipe.move()

        if add_pipe:
            score += 1
            for g in ge:
                g.fitness += 5
            pipes.append(PipesIA(SCREEN))

        for r in remove:
            pipes.remove(r)

        for x, ship in enumerate(ships):
            if ship.y_pos + ship.height >= SCREEN_HEIGHT or ship.y_pos < 0:
                ships.pop(x)
                nets.pop(x)
                ge.pop(x)

        bg.move()
        draw_window(SCREEN, ships, pipes, bg, score, GEN)
Пример #24
0
import pygame

from src.background import Background
from src.config import clock, FPS, bg_pos_y_1, bg_speed, music_1, bg_space
from src.update import Update
from src.player import Player
from src.ship import Ship
from src.util import display_ui

pygame.display.set_caption("Space Shooter")

player = Player("Marcelo", Ship())
background = Background(pos_y_1=bg_pos_y_1,
                        speed=bg_speed,
                        pos_x=0,
                        surface=bg_space)
game_exit = False
update = Update()

music = music_1
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(-1)

while not game_exit:
    background.display()

    for event in pygame.event.get():
        if (event.type == pygame.KEYDOWN
                and event.key == pygame.K_ESCAPE) or event.type == pygame.QUIT:
            game_exit = True
Пример #25
0
def run_game():
    # 初始化背景设置
    pygame.init()

    # 创建游戏设置类的实例
    ai_settings = Settings()

    # 创建屏幕
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))  # 创建surface对象
    pygame.display.set_caption("Alien Invasion")

    # 创建Play按钮
    play_button = Button(screen, "Play")

    # 创建一艘飞船
    ship = Ship(ai_settings, screen)

    # 创建一个用于存储子弹的编组
    bullets = Group()

    # 创建一组外星人
    aliens = Group()
    gf.create_fleet(ai_settings, screen, aliens)

    # 创建游戏角色
    character = Character(screen)

    # 创建一个用于存储游戏统计信息的实例
    stats = GameStats(ai_settings)

    # 创建记分牌
    sb = Scoreboard(ai_settings, screen, stats)

    # 开始游戏的主循环
    while True:

        # 监听事件
        gf.check_events(ai_settings=ai_settings,
                        screen=screen,
                        stats=stats,
                        play_button=play_button,
                        sb=sb,
                        ship=ship,
                        aliens=aliens,
                        bullets=bullets)

        if stats.game_active:
            # 根据标志修改飞船位置
            ship.update()
            # 更新子弹
            gf.update_bullets(ai_settings, screen, stats, sb, aliens, bullets)
            # 更新外星人
            gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens,
                             bullets)

        # 更新屏幕
        gf.update_screen(ai_settings=ai_settings,
                         screen=screen,
                         stats=stats,
                         ship=ship,
                         character=character,
                         aliens=aliens,
                         bullets=bullets,
                         play_button=play_button,
                         sb=sb)
Пример #26
0
def small_ship():
    return Ship(length=1)
Пример #27
0
def long_ship():
    return Ship(length=4)
Пример #28
0
class PlayGame:
    """
    PlayGame class used for solo and duo mode.
    One user plays in one PlayGame object
    """

    username = None

    def __init__(self,
                 screen: pygame.Surface,
                 username: str = None,
                 solo: bool = True,
                 is_left: bool = True):
        """
        Initialize the player's game.
        :param screen: surface to display game
        :param username: player's username
        :param solo: True if single player False if multi players
        :param is_left: True if solo and if multi player and player 1
        """
        # game settings
        self.end_game = False
        self.username = username
        self.screen = screen
        self.is_left = is_left
        self.solo = solo

        # display settings
        self.screenWidth, self.screenHeight = pygame.display.get_surface(
        ).get_size()
        self.game_window_width = self.screenWidth if self.solo else self.screenWidth / 2
        self.game_window_height = self.screenHeight
        self.game_window = pygame.Surface(
            (self.game_window_width, self.game_window_height))
        self.rect = self.screen.get_rect(
            left=0 if is_left else self.screenWidth / 2)

        # creating game objects
        self.ship = Ship(self.game_window, solo=solo, is_left=is_left)
        self.pipes = []
        self.pipes_number = 2 if solo else 1
        for i in range(0, self.pipes_number):
            self.pipes.append(
                Pipes(self.game_window,
                      first=True if (i == 0) else False,
                      single_player=solo,
                      is_left=is_left))
        self.bg = Background(self.game_window, is_left=is_left)
        self.hourglass = Hourglass(self.game_window)

        # control settings
        if is_left:
            self.jump_key = pygame.K_SPACE
        else:
            self.jump_key = pygame.K_RETURN

    def draw(self):
        """
        Draw all game objects on game window and display player's current score (to be called in main loop).
        """
        self.screen.blit(self.game_window, self.rect)

        self.bg.draw()
        self.ship.draw()
        for pipe in self.pipes:
            pipe.draw()
        self.hourglass.draw()

        text_font = pygame.font.Font(font["bradbunr"], 25)

        string1 = "Score {0} : {1}".format(self.username, self.ship.score)
        textSurface, textRect = createTextObj(string1, text_font)
        self.game_window.blit(textSurface, textRect)

        if not self.solo:
            x_rect_split = self.game_window_width if self.is_left else 0
            pygame.draw.rect(self.game_window, colors["black"],
                             (x_rect_split, 0, 3, self.game_window_height))

    def update(self):
        """
        Update position and state of all game objects (to be called in main loop).
        """
        if self.ship.y_pos + self.ship.height > self.game_window_height:  # Ship falls
            self.end_game = True
        self.ship.move()

        if not self.ship.goForward:
            self.bg.move()
            self.hourglass.move()
            for pipe in self.pipes:
                pipe.move()

        self.updateScore()

        # if self.ship.collision_pipes(self.pipes):
        #     self.end_game = True

        for pipe in self.pipes:
            if pipe.collide_with_ship(self.ship):
                self.end_game = True

        if self.ship.collision_hourglass(self.hourglass):
            sounds["slow"].play()
            self.hourglass.updateCoordinates()
            for pipe in self.pipes:
                pipe.velocity = pipe.origin_velocity
            self.bg.velocity = self.bg.origin_velocity
            self.hourglass.x_velocity = self.hourglass.origin_x_velocity

    def updateScore(self):
        """
        Checks if ship passed current pipe without colliding it and add 1 point if it's the case.
        It also increase objects velocity and reduce space between top and bottom pipes.
        """
        for pipe in self.pipes:
            if self.ship.x_pos > pipe.x_pos and not pipe.passed:
                self.ship.score += 1
                sounds["score"].play()
                if pipe.velocity < 13:
                    for pipe_2 in self.pipes:
                        pipe_2.velocity += 0.5
                    self.hourglass.x_velocity += 0.5

                if self.bg.velocity < 4:
                    self.bg.velocity += 0.2

                if pipe.space > 230 and self.ship.score % 2 != 0:
                    for pipe_2 in self.pipes:
                        pipe_2.space -= 5

                pipe.passed = True

                if self.ship.score % 4 == 0 and self.ship.score != 0:
                    self.hourglass.start()

    def reset(self):
        """
        Resets all game settings to start a new game quickly.
        """
        self.end_game = False
        self.ship.reset()
        self.bg.reset()
        self.hourglass.reset()
        for pipe in self.pipes:
            pipe.reset()
Пример #29
0
    def __init__(self):
        self.screen = pg.display.get_surface()
        self.game_over = False
        self.background = pg.Surface((1440, 768))
        self.background.fill((0, 60, 77))

        self.ui_background_right = pg.Surface((R.UI_LEFTBAR, R.WINDOW_HEIGHT))
        self.ui_background_right.fill((0, 0, 0))

        self.ui_background_bottom = pg.Surface(
            (R.WINDOW_WIDTH, R.UI_BOTTOMBAR))
        self.ui_background_bottom.fill((0, 0, 0))

        self.ui_background = pg.Surface((R.WINDOW_WIDTH, R.WINDOW_HEIGHT))
        self.ui_background.fill((100, 200, 100))
        self.ui_background.set_colorkey((100, 200, 100))

        self.ui_background.blit(self.ui_background_bottom, (0, R.UI_DOWN))
        self.ui_background.blit(self.ui_background_right, (R.UI_LEFT, 0))

        self.camera = Camera(simple_camera_two, R.MAP_WINDOW_WIDTH,
                             R.MAP_WINDOW_HEIGHT)
        self.sprites = SortedUpdates()
        self.ui_overlay = RenderUpdates()

        self.galaxy = Galaxy()  # 1024,768,R.tile_size, group=self.sprites)
        print "finished generating"
        self.layer = self.galaxy.active_sector
        self.zoom = "sector"  # galaxy, sector, solar system, planet
        self.selected = None
        self.selector = None  # Sprite((-10, -10), R.TILE_CACHE["data/selection_anim.png"])

        # self.camera.state.topleft = (0,0)#self.camera.camera_func(self.camera, self.layer.dimensions).center

        # self.camera.state.center = self.layer.dimensions.center

        # #test sprites.
        thing3 = Sprite((200, 200),
                        R.TILE_CACHE["data/planet_1.png"],
                        scaling=2,
                        ticks=8,
                        depth=2)
        thing4 = Sprite((500, 350),
                        R.TILE_CACHE["data/planet_1.png"],
                        scaling=2,
                        ticks=8,
                        depth=2,
                        row=1)
        # thing = Sprite((100, 100), R.TILE_CACHE["data/planet_1.png"], scaling=3, ticks=4)
        # thing2 = ParallaxSprite((100, 100), R.TILE_CACHE["data/two.png"], sprite_pos=[1,0])
        # self.sprites.add( thing2, thing3, thing4)  # , self.world)
        # thing2 = ParallaxSprite((500, 500), R.TILE_CACHE["data/two.png"], sprite_pos=[1,0], offset=0.1)
        # self.sprites.add(thing2)
        # thing2 = ParallaxSprite((800, 200), R.TILE_CACHE["data/two.png"], sprite_pos=[1,0])
        # self.sprites.add(thing2)

        self.ship = Ship(group=self.sprites)

        self.sprites.add(self.ship)

        # control
        self.pressed_key = None
        self.mouse_pressed = False
        # self.cam_pos = Rect(0,0,R.MAP_WINDOW_WIDTH, R.MAP_WINDOW_HEIGHT)
        self.drag = False
Пример #30
0
 def test_has(self):
     testShip = Ship()
     testShip.setCoords([[0, 1], [0, 2]])
     self.assertFalse(testShip.has(0, 0))
     self.assertTrue(testShip.has(0, 1))
     self.assertTrue(testShip.has(0, 2))