Esempio n. 1
0
    def __init__(self):
        pygame.init()
        # Set up the music
        self.shoot_sound = pygame.mixer.Sound('music/8bit.wav')
        pygame.mixer.music.load('music/09 - Cherry Bomb.mp3')
        pygame.mixer.music.play(-1, 0.0)
        self.music_playing = True

        self.settings = settings()
        self.scene = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height), 0, 32)
        pygame.display.set_caption('Space Invader')
        self.fleet = Fleet(self.settings, self.shoot_sound)
        self.ship = Ship(self.settings)
        self.start_screen = start_screen(
            self.scene,
            Vector2(self.settings.screen_width, self.settings.screen_height),
            self.settings)
        self.high_score_screen = high_score_screen(self.scene, self.settings)
        self.game_over_screen = game_over_screen(self.settings, self.scene)

        # Set up the music
        self.shoot_sound = pygame.mixer.Sound('music/8bit.wav')
        pygame.mixer.music.load('music/09 - Cherry Bomb.mp3')
        pygame.mixer.music.play(-1, 0.0)
        self.music_playing = True

        self.new_game = True
        self.show_scores = False
        self.game_over = False
        self.round_count = 1

        self.scene_count = 0
Esempio n. 2
0
    def __init__(self):
        """Initialize the game."""
        # Initialize game display
        pygame.init()
        self.settings = Settings()
        if self.settings.fullscreen:
            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
        else:
            self.screen = pygame.display.set_mode(
                (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")

        # Game is paused initiallly
        self.active = False

        # Initialize basic logic variables
        self.level = 1
        self.ships_remaining = self.settings.ship_limit

        # Initialize game elements
        self.player_ship = Ship(self)
        self.fleet = Fleet(self)
        self.play_button = Button(self, "Play")
        self.scoreboard = Scoreboard(self)
Esempio n. 3
0
class Game():
    """Game clas for Battleship."""

    def __init__(self):
        """Initialize the game."""
        self.initialize_game()
        self.set_up_boards()
        self.set_up_fleets()
        self.play_game()

    def initialize_game(self):
        """Initialize game basics."""
        self.level = 'normal'
        self.name = input("Please enter your name: ")
        self.done = False

    def set_up_boards(self):
        """Set up the playing surface."""
        self.user_board = Board(self.name)
        self.computer_board = Board("Computer")
        self.guess_board = Board("Guesses")

    def set_up_fleets(self):
        """Set up the two fleets for the battleship game."""
        self.user_fleet = Fleet()
        self.user_fleet.set_fleet(self.user_board)
        if self.user_fleet.quit_flag:
            self.done = True
        else:
            self.computer_fleet = Fleet()
            self.computer_fleet.set_fleet_auto(self.computer_board)

    def print_game_status(self):
        """Print the current game status."""
        self.guess_board.print_board()
        # self.computer_board.print_board()
        print('=' * self.user_board.columns * 4)
        self.user_board.print_board()

    def play_game(self):
        """Battleship Game mechanics."""
        turn_count = 0
        # print(self.computer_fleet)
        while not self.done:
            functions.clear()
            self.print_game_status()
            user_guess = input("Please Enter a Guess: ")
            user_guess = Guess(user_guess)
            user_guess.check_if_on_board(self.user_board)
            if user_guess.quit_flag:
                break

            self.computer_board.check_damage(user_guess,
                                             self.guess_board,
                                             self.computer_fleet)
            turn_count += 1
            if self.computer_fleet.all_ships_sank():
                msg = "Congratulations you won!  It took you {} turns."
                print(msg.format(turn_count))
                self.done = True
Esempio n. 4
0
 def _create_enemy(self, enemy_number, row_number):
     """Creates an enemy and place it in a row"""
     enemy = Fleet(self)
     enemy_width, enemy_height = enemy.rect.size
     enemy.x = enemy_width + 2 * enemy_width * enemy_number
     enemy.rect.x = enemy.x
     enemy.rect.y = enemy.rect.height + 2 * enemy.rect.height * row_number
     self.fleet.add(enemy)
Esempio n. 5
0
class TestFleet(unittest.TestCase):
    def setUp(self):
        self.f = Fleet()

    def test_fleetcreate(self):
        """Ships are accessible from Fleet module"""
        self.assertEqual(self.f.ac.label, 'AircraftCarrier')
        self.assertEqual(self.f.d.label, 'Destroyer')
        self.assertEqual(self.f.s.label, 'Submarine')
        self.assertEqual(self.f.b.label, 'Battleship')
        self.assertEqual(self.f.pb.label, 'PatrolBoat')

    def test_fleetdamage(self):
        """Damage done to portion of a ship via Fleet module"""
        h = lambda s: 2**random.randint(0, s + 1)

        d = h(self.f.b.size)
        self.f.b.do_damage(d)
        self.assertEqual(self.f.b.damage, d)

        d = h(self.f.d.size)
        self.f.d.do_damage(d)
        self.assertEqual(self.f.d.damage, d)

        d = h(self.f.pb.size)
        self.f.pb.do_damage(d)
        self.assertEqual(self.f.pb.damage, d)

        d = h(self.f.s.size)
        self.f.s.do_damage(d)
        self.assertEqual(self.f.s.damage, d)

        d = h(self.f.ac.size)
        self.f.ac.do_damage(d)
        self.assertEqual(self.f.ac.damage, d)

    def test_sunk(self):
        """Test ship sunk from Fleet module"""
        # Loop through a ship size and hit it until
        # it has sunk. Test after each hit and check for
        # appropriate status.

        # Create a tuple of all ships so they can be iterated through
        # for sunk tests
        fleet = (self.f.ac, self.f.d, self.f.s, self.f.b, self.f.pb)

        for f in fleet:
            for i in range(0, f.size - 1):
                f.do_damage(2**i)
                self.assertFalse(f.is_sunk())

            f.do_damage(2**(f.size - 1))
            self.assertTrue(f.is_sunk())

            if f.is_sunk():
                self.f.sink_ship()

        self.assertTrue(self.f.fleet_sunk())
Esempio n. 6
0
 def set_up_fleets(self):
     """Set up the two fleets for the battleship game."""
     self.user_fleet = Fleet()
     self.user_fleet.set_fleet(self.user_board)
     if self.user_fleet.quit_flag:
         self.done = True
     else:
         self.computer_fleet = Fleet()
         self.computer_fleet.set_fleet_auto(self.computer_board)
Esempio n. 7
0
 def test_hit(self):
     fleet = Fleet([2, 2])
     grid = Grid(10, 10)
     fleet.boats[0].place(grid, 0, 0, Boat.DIR_DOWN)
     fleet.boats[1].place(grid, 1, 0, Boat.DIR_DOWN)
     self.assertEqual(fleet.hit(9, 9), False)
     # Starts shooting down one boat
     self.assertEqual(fleet.hit(0, 0), True)
     self.assertEqual(fleet.size, 2)
     # Finish him
     self.assertEqual(fleet.hit(0, 1), True)
     self.assertEqual(fleet.size, 1)
Esempio n. 8
0
    def kill_alien(self):
        """Handle alien kills."""
        self.scoreboard.set_score(self.scoreboard.score +
                                  self.settings.alien_points)

        # Create a new fleet if all aliens are gone
        if not self.fleet.aliens:
            self.player_ship.reset()
            self.fleet = Fleet(self)
            # Increment speed (difficulty)
            self.settings.increase_speed()
            # Increment level
            self.level += 1
            self.scoreboard.prep_level()
Esempio n. 9
0
 def run_game(self):
     fleet = Fleet()
     herd = Herd()
     player = self.display_welcome()
     team_size = user_prompt(
         "How many on each team? Less than 10 please. :", 10)
     herd.create_herd(team_size)
     fleet.create_fleet(team_size, player)
     self.fleet = fleet
     self.herd = herd
     print("\n" * 10)
     display(self.fleet, self.herd)
     input("Press enter to start the game...")
     winner = None
     game_on = True
     while game_on:
         choice = None
         print("Your turn!\n")
         if player == 1:
             choice = self.show_robo_opponent_options()
             if choice != "skip":
                 self.robo_turn(int(choice))
             # Computer Turn
             print(f"Computer's turn!\n")
             self.dino_turn(1, 2)
         else:
             choice = self.show_dino_opponent_options()
             if choice != "skip":
                 attack_type = user_prompt(
                     "What type of attack?\n1: Slam (more damage, higher energy cost)\n2: Bite\n:",
                     2)
                 self.dino_turn(int(choice), int(attack_type))
             # Computer Turn
             print(f"Computer's turn!\n")
             self.robo_turn(1)
         # Check for dead
         if self.herd.dinosaurs[0].health <= 0:
             print(f"{self.herd.dinosaurs[0].type} has died!")
             self.herd.dinosaurs.remove(self.herd.dinosaurs[0])
         if self.fleet.robots[0].health <= 0:
             print(f"{self.fleet.robots[0].name} has died!")
             self.fleet.robots.remove(self.fleet.robots[0])
         if len(self.herd.dinosaurs) < 1:
             winner = "Robots Win!"
             game_on = False
         if len(self.fleet.robots) < 1:
             winner = "Dinosaurs Win!"
             game_on = False
     self.display_winner(winner)
Esempio n. 10
0
    def _start_game(self):
        """Start a new game."""
        # Reset game
        self.level = 1
        self.ships_remaining = self.settings.ship_limit
        self.scoreboard.reset()
        self.settings.initialize_dynamic_settings()
        self.fleet = Fleet(self)
        self.player_ship.reset()

        # Hide cursor
        pygame.mouse.set_visible(False)

        # Start game
        self.active = True
Esempio n. 11
0
 def __init__(self):
     self.turn = 1
     self.user_selector = 0
     self.enemy_selector = 0
     self.target = 0
     self.fleet = Fleet()
     self.herd = Herd()
     self.user_choice = ""
     self.user = None
     self.enemy = None
     self.user_attacker = None
     self.enemy_attacked = None
     self.enemy_attacker = None
     self.user_attacked = None
     self.try_again = 0
 def fight_sequence(self):
     robotOne = Fleet()
     dinosaurOne = Herd()
     turn = 'Dinosaur'
     while not robotOne.defeated() and not dinosaurOne.defeated():
         if turn == 'Dinosaur':
             for robot in robotOne.robots:
                 robot.health -= dinosaurOne.dinosaurs[0].attack_power
             turn = 'Robot'
         elif turn == 'Robot':
             for dinosaur in dinosaurOne.dinosaurs:
                 dinosaur.health -= robotOne.robots[0].attack_power
         turn = 'Dinosaur'
     print("The dinosaurs won: ", robotOne.defeated())
     print("The robots won: ", dinosaurOne.defeated())
Esempio n. 13
0
 def create_fleet(self, planet):
     self.fleets_counter += 1
     fleet = Fleet(self, planet, self.fleets_counter)
     planet.star.fleets.append(fleet)
     planet.fleets.append(fleet)
     self.fleets.append(fleet)
     return fleet
Esempio n. 14
0
 def fromDOMElement(cls, e):
     import domhelpers
     p = cls()
     p.fleet = Fleet.fromDOMElement(
             domhelpers.getFirstChildElementWithTagName(e, 'fleet'),
             PlayerFleetNavigator)
     return p
Esempio n. 15
0
    def __init__(s, graph, waypoints, pathsfile, maxdist, npeople,
                 peoplespeed, ncars, fleetspeed, sensorrad, splinterval,
                 sensortpr, sensornfp, loglevel):

        s.log = get_multiprocessing_logger(loglevel)
        s.graph = graph
        wpaux = np.transpose(waypoints)
        s.waypoints = graph.cachedravel[wpaux[0], wpaux[1]]
        s.g0 = np.full(graph.nnodes, MAX, dtype=np.double)
        s.wpspaths = s.load_cached_wps_paths(pathsfile, graph, maxdist,
                                             s.waypoints, s.g0)
        s.crossingsmaxdist = maxdist
        s.npeople = npeople
        s.acccount = np.full(graph.nnodes, 0.0)
        s.curcount = np.full(graph.nnodes, 0.0)
        s.clock = 0
        s.lastid = -1

        s.rng = random.SystemRandom()

        s.waypointsidx = copy_list_to_boolindexing(s.waypoints, graph.maplen)
        s.waypointskdtree = cKDTree(waypoints, copy_data=False)

        s.people = []

        pintvl, fintvl =  compute_gcd_intervals(peoplespeed, fleetspeed)
        s.insert_people(npeople, pintvl, waypoints)
        s.fleet = Fleet(graph, ncars, fintvl, sensorrad, splinterval,
                        sensortpr, sensornfp, s.rng, loglevel,
                        s.wpspaths,
                        s.crossingsmaxdist, s.waypointskdtree, s.waypointsidx)

        s.tdens = np.full(graph.nnodes, 0.0)
        s.denserrors = np.array([-1,-1,-1])
Esempio n. 16
0
    def kill_player(self):
        """Handle player death."""
        if self.ships_remaining > 0:
            # Decrement number of ships remaining
            self.ships_remaining -= 1
            self.scoreboard.reset()

            # Create new fleet and ship
            self.fleet = Fleet(self)
            self.player_ship.reset()

            # Pause
            sleep(0.5)
        else:
            self.active = False
            pygame.mouse.set_visible(True)
Esempio n. 17
0
 def test_constructor(self):
     fleet = Fleet([5, 4, 3, 3, 2])
     self.assertEqual(fleet.size, 5)
     # Boats should be built
     boats = fleet.boats
     self.assertEqual(len(boats), 5)
     for boat in boats:
         self.assertIsInstance(boat, Boat)
Esempio n. 18
0
 def resupply_fleets(self):
     """Method that goes through the fleets and resupplies them in the
     resupply menu.
     """
     Util.log_msg("Begin resupplying fleets.")
     for fleet_id, fleet in self.fleets.items():
         if fleet.needs_resupply:
             Util.log_msg("Resupplying fleet {}.".format(fleet_id))
             if fleet_id != 1:
                 Fleet.switch(self.regions['top_submenu'], fleet.fleet_id)
             Util.wait_and_click_and_wait(
                 self.regions['top_submenu'], 'resupply_all.png',
                 self.regions['lower_right'], 'resupply_all_done.png')
             Util.kc_sleep()
             self.stats.increment_resupplies_done()
             fleet.needs_resupply = False
             Util.kc_sleep()
     Util.log_msg("Done resupplying fleets.")
Esempio n. 19
0
def battle():
    dino_player_herd = Herd()
    robot_player_fleet = Fleet()
    print(dino_player_herd)
    print(robot_player_fleet)

    def dino_turn():
        for dino in dino_player_herd.dinos:
            print(
                f'{dino.Name} has {dino.Health} health and {dino.Attack_Power} attack power'
            )
        choice = input('\nWhich dino would you like to use to attack?  ')
        for dino in dino_player_herd.dinos:
            if choice == dino.Name:
                for robot in robot_player_fleet.robots:
                    print(
                        f'{robot.Name} has {robot.Health} health and {robot.Attack_Power} attack power'
                    )
                target = input('\nWhich robot would you like to attack?  ')
                for robot in robot_player_fleet.robots:
                    if target == robot.Name:
                        robot.damage_taken(dino.Attack_Power)
                        if robot.Health < 1:
                            robot_player_fleet.robots.pop(
                                robot_player_fleet.robots.index(robot))
                            print(len(robot_player_fleet.robots))

    def robot_turn():
        for robot in robot_player_fleet.robots:
            print(
                f'{robot.Name} has {robot.Health} health and {robot.Attack_Power} attack power'
            )
        choice = input('\nWhich robot would you like to use to attack?  ')
        for robot in robot_player_fleet.robots:
            if choice == robot.Name:
                for dino in dino_player_herd.dinos:
                    print(
                        f'{dino.Name} has {dino.Health} health and {dino.Attack_Power} attack power'
                    )
                target = input('\nWhich dino would you like to attack?  ')
                for dino in dino_player_herd.dinos:
                    if target == dino.Name:
                        dino.damage_taken(robot.Attack_Power)
                        if dino.Health < 1:
                            dino_player_herd.dinos.pop(
                                dino_player_herd.dinos.index(dino))
                            print(len(dino_player_herd.dinos))

    while len(dino_player_herd.dinos) != 0 or len(
            robot_player_fleet.robots) != 0:
        dino_turn()
        robot_turn()
    if len(dino_player_herd.dinos) == 0:
        print('Congrats RoboMan, You won!')
    else:
        print('Congrats DinoMan, You won!')
Esempio n. 20
0
    def update(self):
        if self.new_game:
            pass
        elif self.show_scores:
            pass
        elif self.game_over:
            pass
        else:
            if len(self.fleet.fleet) == 0:
                self.ship.gun.reset()
                del self.fleet
                self.fleet = Fleet(self.settings)

            self.ship_hit()
            self.alien_hit()
            self.saucer_hit()
            self.fleet.out_of_bound(self.settings)
            self.fleet.move()
            self.ship.move()
Esempio n. 21
0
 def new_game(cls, user):
     """Creates and returns a new game"""
     user_fleet = Fleet()
     user_board = Board()
     user_chart = Board()
     ai_fleet = Fleet()
     ai_board = Board()
     ai_chart = Board()
     user_fleet_key = user_fleet.put()
     user_board_key = user_board.put()
     user_chart_key = user_chart.put()
     ai_fleet_key = ai_fleet.put()
     ai_board_key = ai_board.put()
     ai_chart_key = ai_chart.put()
     game = Game(user=user,
                 user_fleet=user_fleet_key,
                 user_board=user_board_key,
                 user_chart=user_chart_key,
                 ai_fleet=ai_fleet_key,
                 ai_board=ai_board_key,
                 ai_chart=ai_chart_key,
                 game_over=False)
     game.put()
     user_board.build_board()
     user_chart.build_board()
     ai_board.build_board()
     ai_chart.build_board()
     return game
Esempio n. 22
0
    def test_createfleet(self):
        fleet = Fleet(123, 12, 'Austin', ServiceType.COFFEE)

        self.assertEqual(123, fleet.fleetid)
        self.assertEqual(12, fleet.fmid)
        self.assertEqual('Austin', fleet.region)
        self.assertEqual(ServiceType.COFFEE, fleet.serviceType)

        print(fleet)
        print()

        print(repr(fleet))
        print()
Esempio n. 23
0
    def __init__(self):
        self.fleet = Fleet()
        self.herd = Herd()

        match_over = False
        while match_over:
            if Fleet.health == 0:
                match_over = True
                del self
                print('DINOSAURS WIN!')
                print('GAME OVER')
            elif Herd.health == 0:
                match_over = True
                print('ROBOTS WIN!')
                print('GAME OVER')
                del self
Esempio n. 24
0
 def __init__(self, name):
     self.name = name
     self.remaining_ships = {"destroyer": 2, "submarine": 3}
     self.fleet = Fleet()
     self.rows = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
     self.columns = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
     self.my_board = [{"A1": "O", "A2": "O", "A3": "O", "A4": "O", "A5": "O",
                       "A6": "O", "A7": "O", "A8": "O", "A9": "O", "A10": "O"},
                      {"B1": "O", "B2": "O", "B3": "O", "B4": "O", "B5": "O",
                       "B6": "O", "B7": "O", "B8": "O", "B9": "O", "B10": "O"},
                      {"C1": "O", "C2": "O", "C3": "O", "C4": "O", "C5": "O",
                       "C6": "O", "C7": "O", "C8": "O", "C9": "O", "C10": "O"},
                      {"D1": "O", "D2": "O", "D3": "O", "D4": "O", "D5": "O",
                       "D6": "O", "D7": "O", "D8": "O", "D9": "O", "D10": "O"},
                      {"E1": "O", "E2": "O", "E3": "O", "E4": "O", "E5": "O",
                       "E6": "O", "E7": "O", "E8": "O", "E9": "O", "E10": "O"},
                      {"F1": "O", "F2": "O", "F3": "O", "F4": "O", "F5": "O",
                       "F6": "O", "F7": "O", "F8": "O", "F9": "O", "F10": "O"},
                      {"G1": "O", "G2": "O", "G3": "O", "G4": "O", "G5": "O",
                       "G6": "O", "G7": "O", "G8": "O", "G9": "O", "G10": "O"},
                      {"H1": "O", "H2": "O", "H3": "O", "H4": "O", "H5": "O",
                       "H6": "O", "H7": "O", "H8": "O", "H9": "O", "H10": "O"},
                      {"I1": "O", "I2": "O", "I3": "O", "I4": "O", "I5": "O",
                       "I6": "O", "I7": "O", "I8": "O", "I9": "O", "I10": "O"},
                      {"J1": "O", "J2": "O", "J3": "O", "J4": "O", "J5": "O",
                       "J6": "O", "J7": "O", "J8": "O", "J9": "O", "J10": "O"}]
     self.opponent_board = [{"A1": "O", "A2": "O", "A3": "O", "A4": "O", "A5":
                         "O", "A6": "O", "A7": "O", "A8": "O", "A9": "O", "A10": "O"},
                      {"B1": "O", "B2": "O", "B3": "O", "B4": "O", "B5": "O",
                       "B6": "O", "B7": "O", "B8": "O", "B9": "O", "B10": "O"},
                      {"C1": "O", "C2": "O", "C3": "O", "C4": "O", "C5": "O",
                       "C6": "O", "C7": "O", "C8": "O", "C9": "O", "C10": "O"},
                      {"D1": "O", "D2": "O", "D3": "O", "D4": "O", "D5": "O",
                       "D6": "O", "D7": "O", "D8": "O", "D9": "O", "D10": "O"},
                      {"E1": "O", "E2": "O", "E3": "O", "E4": "O", "E5": "O",
                       "E6": "O", "E7": "O", "E8": "O", "E9": "O", "E10": "O"},
                      {"F1": "O", "F2": "O", "F3": "O", "F4": "O", "F5": "O",
                       "F6": "O", "F7": "O", "F8": "O", "F9": "O", "F10": "O"},
                      {"G1": "O", "G2": "O", "G3": "O", "G4": "O", "G5": "O",
                       "G6": "O", "G7": "O", "G8": "O", "G9": "O", "G10": "O"},
                      {"H1": "O", "H2": "O", "H3": "O", "H4": "O", "H5": "O",
                       "H6": "O", "H7": "O", "H8": "O", "H9": "O", "H10": "O"},
                      {"I1": "O", "I2": "O", "I3": "O", "I4": "O", "I5": "O",
                       "I6": "O", "I7": "O", "I8": "O", "I9": "O", "I10": "O"},
                      {"J1": "O", "J2": "O", "J3": "O", "J4": "O", "J5": "O",
                       "J6": "O", "J7": "O", "J8": "O", "J9": "O", "J10": "O"}]
Esempio n. 25
0
    def _create_fleet(self):
        """Creates the fleet of enemies."""
        #Creates an enemy and find the number of enemies in a row
        #Spacing between each ship is equal to one ship width
        enemy = Fleet(self)
        enemy_width, enemy_height = enemy.rect.size
        available_space_x = self.settings.screen_width - (2 * enemy_width)
        number_enemies_x = available_space_x // (2 * enemy_width)

        ship_height = self.ship.rect.height
        available_space_y = self.settings.screen_height - (
            3 * enemy_height) - ship_height
        number_rows = available_space_y // (2 * enemy_height)

        #Creates the full fleet
        for row_number in range(number_rows):
            for enemy_number in range(number_enemies_x):
                self._create_enemy(enemy_number, row_number)
Esempio n. 26
0
def spy_raports_to_attack(spy_reports,
                          max_attacks,
                          useHeavyTransporters=False):
    threats = [
        'LightFighter', 'HeavyFighter', 'Cruiser', 'Battleship',
        'LightTransport', 'HeavyTransport', 'ColonizationShip', 'Dreadnought',
        'Bomber', 'Destroyer', 'DeathStar', 'Recycler', 'SpyProbe',
        'RocketLauncher', 'LightLaserCannon', 'HeavyLaserCannon',
        'GaussCannon', 'IonCannon', 'PlasmaLauncher', 'SmallPlanetaryShield',
        'LargePlanetaryShield', 'AntiMissile', 'InterplanetaryMissile'
    ]

    number_of_reports = len(spy_reports)
    potential_targets = list()

    # search for defensless targets
    for i in range(0, len(spy_reports)):
        defensless = True
        for j in threats:
            if spy_reports[i].get(j) > 0:
                defensless = False
                break
        if defensless:
            potential_targets.append(spy_reports[i])

    # search for best profit targets
    profit_list = list()
    for i in range(0, len(potential_targets)):
        profit = potential_targets[i].get("metal")
        profit += potential_targets[i].get("crystal")
        profit += potential_targets[i].get("deuter")
        profit_list.append((profit, i))

    profit_list.sort(key=lambda profit: profit[0], reverse=True)

    result = list()

    for i in range(0, len(profit_list)):
        if i + 1 > max_attacks:
            break
        attack_fleet = Fleet()
        if useHeavyTransporters:
            attack_fleet.set("HeavyTransport", int(profit_list[i][0] / 50000))
        else:
            attack_fleet.set("LightTransport", int(profit_list[i][0] / 10000))
        target_planet = potential_targets[profit_list[i][1]]
        result.append(Order("attack", attack_fleet, target_planet))

    return result
 def testFleetOneMarks(self):
     fleet = Fleet(1)
     self.assertEqual(fleet.getImage(), "fleet_1_mark.png")
from fleet import Fleet
from thing import Thing

fleet = Fleet()

# Töltsd fel a fleet példányt olyan módon, hogy a következő legyen a kimenet:
# 1. [ ] Get milk
# 2. [ ] Remove the obstacles
# 3. [x] Stand up
# 4. [x] Eat lunch

fleet.add(Thing('Get milk'))
fleet.add(Thing('Remove the obstacles'))
thing2 = Thing('Stand up')
thing2.complete()
fleet.add(thing2)
thing3 = Thing('Eat lunch')
thing3.complete()
fleet.add(thing3)

print(fleet)
Esempio n. 29
0
from fleet import Fleet
from thing import Thing

getMilk=Thing("Get milk")
getMilk.complete()
removeObs=Thing("Remove the obstacles")
removeObs.complete()
standUp=Thing("Stand up")
eatLunch=Thing("Eat lunch")
fleet = Fleet()
fleet.add(getMilk)
fleet.add(removeObs)
fleet.add(standUp)
fleet.add(eatLunch)
# Create a fleet of things to have this output:
# 1. [ ] Get milk
# 2. [ ] Remove the obstacles
# 3. [x] Stand up
# 4. [x] Eat lunch

print(fleet)
 def testFleetTwoAllMarks(self):
     fleet = Fleet(2)
     marks = fleet.getAllImages()
     self.assertEqual(len(marks), 1)
     self.assertEqual(marks[0], "fleet_2_mark.png")
Esempio n. 31
0
    def _conduct_pre_sortie_checks(self):
        """Method to conduct pre-sortie fatigue and supply checks on the
        combat fleets as needed.

        Returns:
            bool: True if the fleet passes the pre-sortie checks, False
                otherwise
        """
        cancel_sortie = False

        if self.config.combat['fleet_mode'] == 'striking':
            # switch fleet to 3rd fleet if striking fleet
            Util.kc_sleep(1)
            Fleet.switch(self.regions['top_submenu'], 3)

        needs_resupply, self.dmg, fleet_fatigue = (
            self._run_pre_sortie_fleet_check_logic(self.primary_fleet))

        if self.combined_fleet:
            # additional combined fleet checks
            Fleet.switch(self.regions['top_submenu'], 2)
            two_needs_resupply, fleet_two_damages, fleet_two_fatigue = (
                self._run_pre_sortie_fleet_check_logic(self.fleets[2]))
            Fleet.switch(self.regions['top_submenu'], 1)

            self.dmg = self._combine_fleet_damages(self.dmg, fleet_two_damages)
            for key in fleet_fatigue:
                fleet_fatigue[key] = (fleet_fatigue[key]
                                      or fleet_two_fatigue[key])

        if needs_resupply:
            Util.log_warning("Canceling combat sortie: resupply required.")
            self.set_next_combat_time()
            cancel_sortie = True

        if 'CheckFatigue' in self.config.combat['misc_options']:
            if fleet_fatigue['high']:
                Util.log_warning(
                    "Canceling combat sortie: fleet has high fatigue.")
                self.set_next_combat_time({'minutes': 25})
                cancel_sortie = True
            elif fleet_fatigue['medium']:
                Util.log_warning(
                    "Canceling combat sortie: fleet has medium fatigue.")
                self.set_next_combat_time({'minutes': 15})
                cancel_sortie = True

        # just use fleet 1's method
        damage_counts_at_threshold = (
            self.primary_fleet.get_damage_counts_at_threshold(
                self.config.combat['repair_limit'], self.dmg))

        if damage_counts_at_threshold > 0:
            Util.log_warning(
                "Canceling combat sortie: {:d} ships above damage threshold.".
                format(damage_counts_at_threshold))
            self.set_next_combat_time()
            cancel_sortie = True

        if ('PortCheck' in self.config.combat['misc_options']
                or self.map.world == 'event'):
            port_full_notice = ('warning_port_full_event.png' if self.map.world
                                == 'event' else 'warning_port_full.png')
            if self.regions['lower'].exists(port_full_notice):
                Util.log_warning("Canceling combat sortie: port is full.")
                self.set_next_combat_time({'minutes': 15})
                cancel_sortie = True

        if cancel_sortie:
            return False
        return True
Esempio n. 32
0
    fighters = int(capacity * fighter_capacity / 100)
    for _ in range(fighters):
        resilience = resilience + fighter.sustain + 1
        cost = cost + fighter.cost
        hits = hits + fighter.hits()
        ships.append(fighter.name[:2])

    return ','.join(['.'.join(ships), cost, hits, hits / cost, resilience])


for _ in range(len(available_units) + 1):
    if args.debug:
        print('computing', _)
    pool = available_units[_:]
    if len(pool) >= args.size:
        add_ship([], pool)

final = []
for fleet in fleets:
    final.append(list(fleet))

breakdown = []
for f in final:
    fleet = Fleet(f)
    breakdown.append(
        fleet.breakdown(fighter_capacity=args.percent, fighter=fighter))

print('Fleet,Fighters,Cost,Hits in Round,Hits/Cost,Resilience')
print('\n'.join(sorted(breakdown)))
print(len(final), " total fleets")
Esempio n. 33
0
 def __init__(self, name, width, height, boats):
     self.name = name
     self.grid = Grid(width, height)
     self.fleet = Fleet(boats)
 def __init__(self):
     self.fleet = Fleet()
     self.herd = Herd()
 def testFleetOneNotSelectedMark(self):
     fleet = Fleet(1)
     self.assertEqual(fleet.getNotSelectedImage(), "fleet_1_mark_not_selected.png")
 def testFleetOneAllMarks(self):
     fleet = Fleet(1)
     marks = fleet.getAllImages()
     self.assertEqual(len(marks), 2)
     self.assertEqual(marks[0], "fleet_1_flagship_mark.png")
     self.assertEqual(marks[1], "fleet_1_mark.png")
Esempio n. 37
0
    def sortie_expedition(self, fleet):
        """Method to sortie an expedition fleet to its assigned expeditions.

        Args:
            fleet (ExpeditionFleet): ExpeditionFleet to send on an expedition

        Returns:
            bool: True if the fleet was successfully sent on an expedition,
                False otherwise
        """
        self.stats.increment_expeditions_attempted()
        fleet.choose_expedition()
        Util.log_msg("Sortieing fleet {:d} to expedition {:d}".format(
            fleet.fleet_id, fleet.expedition))
        # change expedition world if necessary
        while not Util.check_and_click(
                self.kc_region, 'expedition_{}.png'.format(fleet.expedition)):
            Util.kc_sleep()
            Util.wait_and_click(self.kc_region,
                                'e_world_{}.png'.format(fleet.expedition_area))
        Util.kc_sleep(1)
        if not Util.check_and_click(self.kc_region, 'sortie_select.png'):
            if self.kc_region.exists(
                    Pattern('expedition_timer_complete.png').exact()):
                fleet.update_return_time(0, -1)
            else:
                expedition_timer = Util.read_timer(self.kc_region,
                                                   'expedition_timer.png', 'r',
                                                   80)
                fleet.update_return_time(expedition_timer['hours'],
                                         expedition_timer['minutes'] - 1)
                Util.log_warning(
                    "Expedition is already running. Return time: {}".format(
                        fleet.return_time.strftime('%Y-%m-%d %H:%M:%S')))
            return False

        Util.rejigger_mouse(self.regions, 'top')
        # switch fleet as necessary
        if fleet.fleet_id != 2:
            Fleet.switch(self.regions['top_submenu'], fleet.fleet_id)

        if (self.regions['right'].exists('ship_state_busy.png')
                or self.regions['right'].exists('ship_state_dmg_repair.png')):
            # fleet is already on an expedition or ship is being repaired
            Util.log_warning('Fleet or ship not available. Check back later')
            fleet.update_return_time(0, 15)
            Util.wait_and_click_and_wait(
                self.kc_region, 'e_world_1.png', self.regions['top_submenu'],
                'sortie_top_menu_expedition_active.png')
            return False
        else:
            if not fleet.check_supplies(self.regions['check_supply']):
                # fleet needs resupply
                Util.wait_and_click_and_wait(
                    self.kc_region, 'e_world_1.png',
                    self.regions['top_submenu'],
                    'sortie_top_menu_expedition_active.png')
                return False
            # successful expedition sortie
            Util.wait_and_click(self.kc_region, 'expedition_dispatch.png')
            fleet.dispatch_fleet()
            self.stats.increment_expeditions_sent()
            Util.log_msg("Fleet {:d} sortied. Expected return time: {}".format(
                fleet.fleet_id,
                fleet.return_time.strftime('%Y-%m-%d %H:%M:%S')))
            Util.kc_sleep(3)
        Util.rejigger_mouse(self.regions, 'top')
        Util.kc_sleep()
        return True