Example #1
0
    def add_test_data_to_db():
        """Adds test data to the database, create_db must be called first.
        """
        ships = [
            {'name': 'Achilles', 'sh_class': 'Leander', 'type': 'Light Cruiser', 'country': 'NZL',
             'build_date': '1000-01-01'},
            {'name': 'Admiral Graf Spee', 'sh_class': 'Deutschland', 'type': 'Heavy Cruiser',
             'country': 'GER', 'build_date': '1000-01-01'},
            {'name': 'Cumberland', 'sh_class': 'County-Kent', 'type': 'Heavy Cruiser',
             'country': 'UK', 'build_date': '1000-01-01'},
            {'name': 'Exeter', 'sh_class': 'York', 'type': 'Heavy Cruiser', 'country': 'UK',
             'build_date': '1000-01-01'},
            {'name': 'Ajax', 'sh_class': 'Leander', 'type': 'Light Cruiser', 'country': 'UK',
             'build_date': '1000-01-01'}
        ]

        battles = [
            {'name': 'River Platte', 'conflict': 'WWII', 'date': '1939-12-13'},
            {'name': 'Battle of the Java Sea', 'conflict': 'WWII', 'date': '1942-02-27'}
        ]

        with models.database.atomic():
            Ship.insert_many(ships).execute()
            Battle.insert_many(battles).execute()

            river_platte = Battle.select().where(Battle.name == 'River Platte').get()
            java_sea = Battle.select().where(Battle.name == 'Battle of the Java Sea').get()

            for ship in Ship.select():
                if ship.name == 'Ajax':
                    ShipBattle.create(ship=ship, battle=java_sea)
                ShipBattle.create(ship=ship, battle=river_platte)
        models.database.close()
Example #2
0
def main():
    pygame.init()

    screen = setup_screen()

    pygame.display.set_caption(Settings.APP_NAME)

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

    stats = GameStats(Settings)
    sb = Scoreboard(Settings, screen, stats)
    ship = Ship(screen, Settings.SHIP_SPEED)
    bullets = Group()
    aliens = Group()

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

    while 1:
        gf.check_events(Settings, screen, sb, play_button, stats, ship, aliens,
                        bullets)

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

        gf.update_screen(Settings, screen, sb, stats, ship, aliens, bullets,
                         play_button)
Example #3
0
def build_ship(player, ship_type):
    """
    Schedules a ship for being built on a player's home system.

    Throws utils.NotEnoughMoneyException if the player requires more money
    """
    cost = game_constants.ship_cost(player, ship_type)
    if cost is None:
        return # oops

    if player.resources < cost:
        raise NotEnoughMoneyException()

    ship = Ship(game=player.game,
                owner=player,
                on_build_queue=True,
                ship_type=ship_type,
                attack_tech=game_constants.ship_attack(player, ship_type),
                range_tech=game_constants.ship_range(player, ship_type),
                moves=0,
                system=player.home)

    player.resources -= cost

    player.save()
    ship.save()

    return ship
Example #4
0
 def _place_ship(self, game, user, ship_type, start_position, end_position):
     try:
         ship = Ship(parent=game.key)
         ship.place_ship(game, user, ship_type,
                         start_position, end_position)
         ship.put()
         game.put()
     except ValueError as e:
         raise endpoints.BadRequestException(e)
     return game.to_form('Ship placed!')
Example #5
0
 def validate_db_connection(self):
     """Validate the connection to the database. If database does not exist,
     a new one is created.
     :raises: peewee.DatabaseError if existing database is invalid.
     """
     models.database.init(str(self._db_path))
     if self._db_path.exists():
         models.database.connect()
         Ship.select().first()
         models.database.close()
     else:
         # If database path does not exist, attempt to create a new database.
         self.create_db()
Example #6
0
 def test_ship_creation(self):
     user = User('user', Color.RED)
     start_planet = Planet(1, 25, 25, 2, user, None)
     destination_planet = Planet(2, 100, 100, 2, user, None)
     ship = Ship((1, 1), start_planet, destination_planet)
     self.assertEqual(ship.owner, user)
     self.assertEqual(ship.color, Color.RED)
Example #7
0
def deploy_ship(request, game_id):
    ship_id = Ship.id_str_to_pk(request.REQUEST['shipId'])
    cancel_colony = request.method == 'DELETE'

    ship = Ship.objects.get(pk=ship_id)

    if ship.ship_type != game_constants.COLONY:
        return _forbidden("Only colonies can do that")
    if ship.owner != request.player:
        return _forbidden("You don't own that ship")
    if ship.on_deploy_queue and not cancel_colony:
        return _forbidden("That colony is already deploying")
    elif not ship.on_deploy_queue and cancel_colony:
        return _forbidden("That colony isn't deploying")

    if ship.system.owner == request.player:
        return _forbidden("You already own that system")
    
    if not cancel_colony:
        ships_already_building = ship.system.ship_set.filter(
            owner=request.player,
            ship_type=ship.ship_type,
            on_deploy_queue=True)
        if len(ships_already_building) > 0:
            return _forbidden("You're already deploying a colony there")

    ship.on_deploy_queue = not cancel_colony
    ship.save()

    _game_state_changed(request.game)

    return _json(_game_state(request.game, request.player))
Example #8
0
    def __init__(self, width, height):
        super().__init__(width, height)
 
        arcade.set_background_color(arcade.color.BLACK)
        
        self.ship_sprite = arcade.Sprite('images/ship.png')
        self.ship = Ship(100, 100)
Example #9
0
 def prep_ships(self):
     self._ships = Group()
     for ship_number in range(self._stats._ships_left):
         ship = Ship(self._screen)
         ship.rect.x = 10 + ship_number * ship.rect.width
         ship.rect.y = 10
         self._ships.add(ship)
Example #10
0
    def get_game_history(self, request):
        ''' returns the usual GameForm, plus all related positions and all moves '''
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if not game:
            return endpoints.NotFoundException("Game not found")
        game_key = game.key
        game = game.to_form("")

        ships = Ship.query(ancestor=game_key).order(-Ship.created).fetch()
        ship_forms = []
        for s in ships:
            position_forms = []
            positions = Position.query(ancestor=s.key).fetch()
            for p in positions:
                position_forms.append(XYMessage(x=p.x, y=p.y, hit=p.hit))
            ship_forms.append(
                ShipMessage(player=s.player.get().name,
                            ship=s.ship,
                            created_date=s.created,
                            positions=position_forms))

        moves = Move.query(ancestor=game_key).order(-Move.created).fetch()
        move_forms = []
        for m in moves:
            move_forms.append(
                MoveMessage(player=m.player.get().name,
                            x=m.x,
                            y=m.y,
                            created_date=m.created))

        form = FullGameInfo(game=game, ships=ship_forms, moves=move_forms)
        return form
 def set_up(self):
   for each_player in self.players:
     for i in range(5):
       self.play_view.boardDisplay([], [],each_player.ships, [], [], [])
       x = Ship(self.ship_names[i], self.ship_lengths[i])
       print ("Place your {} (length {}).".format(x.name, x.length))
       valid_placement = 'invalid'
       while valid_placement == 'invalid':
         row = self.play_view.inputRowOrColumn('ROW', 'ship\'s starting ')
         column = self.play_view.inputRowOrColumn('COLUMN', 'ship\'s starting ')
         direction = self.play_view.inputDirection()
         placement = x.place_ship(row,column,direction, each_player.ships)
         if placement == True:
           break
       each_player.ships.append(x)
     self.play_view.boardDisplay([], [], each_player.ships, [], [], [])
     end_turn = input('Finished placing ships.\n\nENTER to clear the screen.')
Example #12
0
 def test_populate_db_message(self, create_db, clean_up):
     db_creator = DbCreatorActor.start(self._db_path)
     db_creator.ask(PopulateDbMessage(None).to_dict())
     assert self._db_path.exists()
     assert len(Ship.select()) == 5
     assert len(Battle.select()) == 2
     assert len(ShipBattle.select()) == 6
     db_creator.stop()
     clean_up()
Example #13
0
 def test_reset_db_message(self, create_db, clean_up):
     db_creator = DbCreatorActor.start(self._db_path)
     db_creator.tell(PopulateDbMessage(None).to_dict())
     db_creator.ask(ResetDbMessage(None).to_dict())
     assert len(Ship.select()) == 0
     assert len(Battle.select()) == 0
     assert len(ShipBattle.select()) == 0
     db_creator.stop()
     clean_up()
Example #14
0
 def set_up(self):
     for each_player in self.players:
         for i in range(5):
             self.play_view.boardDisplay([], [], each_player.ships, [], [],
                                         [])
             x = Ship(self.ship_names[i], self.ship_lengths[i])
             print("Place your {} (length {}).".format(x.name, x.length))
             valid_placement = 'invalid'
             while valid_placement == 'invalid':
                 row = self.play_view.inputRowOrColumn(
                     'ROW', 'ship\'s starting ')
                 column = self.play_view.inputRowOrColumn(
                     'COLUMN', 'ship\'s starting ')
                 direction = self.play_view.inputDirection()
                 placement = x.place_ship(row, column, direction,
                                          each_player.ships)
                 if placement == True:
                     break
             each_player.ships.append(x)
         self.play_view.boardDisplay([], [], each_player.ships, [], [], [])
         end_turn = input(
             'Finished placing ships.\n\nENTER to clear the screen.')
Example #15
0
def define_fleet(player):
    """Define player's ships and place on board"""
    # place each ship
    for ship_spec in SHIP_INFO:
        ship_name = ship_spec[0]
        ship_size = ship_spec[1]
        # display top banner
        clear_screen()
        show_banner()
        print("Placing Ships for {}:\n".format(player.name))
        # display board
        print_board(player.name, player.board.get_player_view())
        # display ship info
        print("Placing {} (size:{})\n".format(ship_name, ship_size))

        # get ship placement details
        while True:
            # 1. ask if vertical or horizontal
            direction = get_vert_or_horiz()
            # 2. ask for top or left starting coordinate
            anchor = get_anchor_coord()
            # 3. validate input (explain why input rejected)
            coords = gen_ship_coords(anchor, ship_size, direction)
            # 4. validate ship placement
            if not coords:
                print("Error: ship coordinates not all on the board\n")
                continue
            if not player.board.verify_empty(coords):
                print("Error: ship coordinates collide with other ships. "
                      "Try again\n")
                continue
            # input valid; last while loop
            break
        # create ship from input
        ship = Ship(ship_name, ship_size, coords, direction)
        # add ship to players list
        player.add_ship(ship)
        # place ship on game board
        player.board.place_ship(ship)
        # 5. redraw screen for next ship (at top of loop)
    # display top banner
    clear_screen()
    show_banner()
    # display board
    print("Placing Ships for {}:\n".format(player.name))
    print_board(player.name, player.board.get_player_view())
    input("All ships placed for {}. Hit ENTER to continue...."
          "".format(player.name))
    clear_screen()
Example #16
0
def create_ship():
    # calling Farmer here like a function return a new object
    farmer_1 = Farmer('Ragnar')
    farmer_2 = Farmer('Rollo', age=25)

    # multiline works for: [], (), {} without \ line continuation escape.
    farmers = [farmer_1, farmer_2]
    ship = Ship(farmers)
    print(f"{len(ship)}")
    print(f"{ship[-1]}")
    print(f"{bool(ship)}")
    print(f"{farmer_2.name} is {farmer_2.age} years old")
    print(farmer_2.travel.__annotations__)
    print(farmer_2.travel('Paris'))
    print(give_farmer_a_sword(farmer_2))
Example #17
0
def move_ship(request, game_id):
        err = _check_phase(request.game, game_constants.MOVE_PHASE)
        if err:
            return err

        system_id = System.id_str_to_pk(request.REQUEST['systemId'])
        ship_id = Ship.id_str_to_pk(request.REQUEST['shipId'])

        system = System.objects.get(pk=system_id)
        ship = Ship.objects.get(pk=ship_id)

        if ship.owner != request.player:
            return _forbidden("You don't own that ship!")

        if ship.on_deploy_queue:
            return _forbidden(
                "That ship is deploying; cancel deployment to move it")

        enemy_fighters = ship.system.ship_set.exclude(owner=request.player). \
            exclude(attack_tech=0)
        if len(enemy_fighters):
            return _forbidden("You can't run from enemy ships")

        lane_traveled = ship.system.neighbors.filter(system=system)
        if not lane_traveled or not lane_traveled[0].lane.passable:
            return _forbidden("Those systems aren't connected")

        ship.system = system
        ship.moves -= 1
        ship.save();

        map_changed = False
        if request.player not in system.visible_to.all():
            system.visible_to.add(request.player)
            map_changed = True

        neighbors = system.neighbors.all()
        for neighbor in neighbors:
            if request.player not in neighbor.lane.visible_to.all():
                map_changed = True
                neighbor.lane.visible_to.add(request.player)
                neighbor.lane.save()

        _game_state_changed(request.game)
        if map_changed:
            _map_changed(request.game, [request.player])

        return _json(_game_state(request.game, request.player))
Example #18
0
 def create_ship(self, ship_data: dict) -> Ship:
     """
     todo:
     built_in_mods
     built_in_wings
     """
     ship = Ship(
         ship_name=ship_data['ship_name'],
         sprite_name=ship_data['sprite_name'],
         width=ship_data['width'],
         height=ship_data['height'],
         hull_id=ship_data['hull_id'],
         hull_size=ship_data['hull_size'],
         style=ship_data['style'],
         center=ship_data['center'],
         armor_rating=ship_data['armor rating'],
         acceleration=ship_data['acceleration'],
         fighter_bays=ship_data['fighter bays']
         if ship_data['fighter bays'] else 0,
         max_burn=ship_data['max burn'] if ship_data['max burn'] else 0,
         cargo=ship_data['cargo'] if ship_data['cargo'] else 0,
         deceleration=ship_data['deceleration'],
         flux_dissipation=ship_data['flux dissipation'],
         fuel=ship_data['fuel'] if ship_data['fuel'] else 0,
         fuel_ly=ship_data['fuel/ly'] if ship_data['fuel/ly'] else 0,
         hitpoints=ship_data['hitpoints'],
         mass=ship_data['mass'],
         max_crew=ship_data['max crew'] if ship_data['max crew'] else 0,
         max_flux=ship_data['max flux'],
         max_speed=ship_data['max speed'],
         max_turn_rate=ship_data['max turn rate'],
         min_crew=ship_data['min crew'] if ship_data['min crew'] else 0,
         ordnance_points=ship_data['ordnance points']
         if ship_data['ordnance points'] else 0,
         shield_arc=ship_data['shield arc']
         if ship_data['shield arc'] else 0,
         shield_efficiency=ship_data['shield efficiency']
         if ship_data['shield efficiency'] else 0,
         shield_type=ship_data['shield type']
         if ship_data['shield type'] else 'none',
         shield_upkeep=ship_data['shield upkeep']
         if ship_data['shield upkeep'] else 0,
         supplies_month=ship_data['supplies/mo']
         if ship_data['supplies/mo'] else 0,
         weapon_slots=ship_data['weapon_slots'],
         description=ship_data['description'],
         mod_name=self.mod_name)
     return ship
Example #19
0
def create_ship(session, user, location, chassis, loadout):

    ship = Ship(location_id=location.id,
                owner_id=user.id,
                chassis_id=chassis.id,
                active=True)

    session.add(ship)

    for item in loadout:
        system = ShipInstalledSystem(system_id=item.id)
        ship.loadout.append(system)

    session.flush()

    return ship
Example #20
0
def add_ship():
    msg=''
    # Insert ship into DB
    if request.method == 'POST':
        try: 
            name = request.form.get('name')
            mass = int(request.form.get('mass'))
            speed = int(request.form.get('speed'))
            jump = int(request.form.get('jump'))
            img_id = request.form.get('img_id')
            s = Ship(name=name, mass=mass, speed=speed, jump=jump, img_id=img_id)
            db.session.add(s)
            db.session.commit()
            msg = "Ship successfully inserted"
        except ValueError as ex:
            msg = ex.__str__
    return render_template("ships/add.html", message=msg)
Example #21
0
    def placing_ships_on_the_field(self, size):
        """
        With this method computer places ships on the game field
        :param size: size of the ship
        """
        old_field = list(self.field)
        upd_field = list(self.field)

        def place_ship(fld, cur_fld, trn):
            current_ship_position = {
                place
                for place in range(len(fld)) if fld[place] == '&'
            }
            forb_places = CheckSurround(fld).forbid_placement()
            forb_places_upd = [
                place for place in forb_places if cur_fld[place] == trn
            ]
            if not forb_places_upd:
                for position in current_ship_position:
                    cur_fld[position] = trn
                self.ships_alive.append(list(current_ship_position))
                return True

        commands = {
            'w': Ship(size).move_up,
            'd': Ship(size).move_right,
            's': Ship(size).move_down,
            'a': Ship(size).move_left,
            'r': Ship(size).rotate_ship,
            'p': place_ship
        }
        while True:
            Ship(size).place_ship(old_field, upd_field)
            upd_field, old_field = list(self.field), upd_field
            attempts = 0
            randoms = random.randint(1, 50)
            try:
                while attempts != randoms:
                    commands[random.choice(
                        ('w', 'd', 's', 'a', 'r'))](old_field, upd_field)
                    if BorderRestriction(upd_field).forbid_of_cross_border():
                        upd_field = list(self.field)
                        continue
                    upd_field, old_field = list(self.field), upd_field
                    attempts += 1
                if commands['p'](old_field, self.field, self.turn):
                    break
                else:
                    continue
            except IndexError:
                upd_field = list(self.field)
                continue
Example #22
0
def create_ship(player, type, weapon, planet, cost=0):
    weapon = Weapon.query.filter_by(name=weapon).first_or_404()
    ship = Ship(player, type, weapon)
    if cost:
        if ship.cost < player.star_tokens:
            player.star_tokens -= ship.cost
            mygalaxy.execute_on_delay("create_ship", [ship.id, planet.id], 30,
                                      "Build ship")
        else:
            return "Not enough credits", 402
            del ship
    db.session.add(ship)
    db.session.commit()
    if cost:
        mygalaxy.execute_on_delay("create_ship", [ship.id, planet.id], 30,
                                  "Build ship")
    else:
        mygalaxy.add_ship(ship.id, mygalaxy.get_planet_location(planet.id))
    return ship
Example #23
0
 def _make_move(self, game, user, at_position, p):
     try:
         history = History(parent=game.key)
         history.user = user.key
         history.guess = p.coordinate
         history.turn = game.turn
         if game.player1_turn:
             history.player_turn = 1
         else:
             history.player_turn = 2
         if at_position <= 0:
             message = 'Miss!'
             history.result = 'miss'
             history.put()
             game.set_fired(user, p.d)
             game.put()
         else:
             message = "Hit!"
             history.result = 'hit'
             ships_query = Ship.query(ancestor=game.key)
             filter_query = ndb.query.FilterNode('user', '=', user.key)
             ships_query1 = ships_query.filter(filter_query)
             filter_query = ndb.query.FilterNode('type', '=', at_position)
             ships_query2 = ships_query1.filter(filter_query)
             ship = ships_query2.get()
             if not ship:
                 filter_query = ndb.query.FilterNode(
                     'type', '=', str(at_position))
                 ships_query3 = ships_query1.filter(filter_query)
                 ship = ships_query3.get()
             ship.hits += 1
             game.set_fired(user, p.d)
             if(ship.is_sank()):
                 message += " Ship %s sank" % ShipType(at_position)
                 game.sink_ship(user, at_position)
             history.put()
             ship.put()
             game.put()
     except ValueError as e:
         raise endpoints.BadRequestException(e)
     return game.to_form(message)
Example #24
0
    def construct_player(cls, *args):
        """Создание игрока"""

        name = cls.get_name(args[0])
        player = Player(name)

        print('Привет, {}, давай заполним твое поле'.format(name))

        for s in cls.storage.ships:
            i = 0
            while (i < s.quantity):
                try:
                    #запрашиваем левую верхнюю координату корабля
                    coord1 = cls.get_coords(
                        'Введите координаты для корабля {} № {} в формате "столбец,строка":'
                        .format(s.name, i + 1))
                    coord2 = Coord(coord1.x, coord1.y)

                    #запрашиваем способ расположения корабля только для многоклеточных
                    if s.size > 1:
                        direction = cls.get_direction(
                            'Укажите расположение корабля, вертикальное (В), или горизонтальное (Г): [В|Г]'
                        )
                        if direction == 'В':
                            coord2.y += s.size
                        elif direction == 'Г':
                            coord2.x += s.size

                    #создаем корабль игрока
                    ship = Ship(s.name, s.size, coord1, coord2)
                    player.add_ship(ship)
                    i += 1
                    clear_screen()
                    Game.print_field(player.field.data, False)

                except Exception as e:
                    print(e)

        player.field.clean_aura()
        return player
    def __init__(self):
        """Initializes the game"""
        # set level
        self.level = 0

        # load sound for level advance
        self.sound = games.load_sound('./res/level.wav')

        # create score
        self.score = games.Text(value=0, size=30, color=color.white, top=5, right=games.screen.width - 10,
                                is_collideable=False)
        games.screen.add(self.score)
        self.score_legend = games.Text(value="score: ", size=30, color=color.white, top=5,
                                       right=self.score.left - 5, is_collideable=False)
        games.screen.add(self.score_legend)

        # create player's ship
        self.ship = Ship(game=self, x=games.screen.width / 2, y=games.screen.height / 2)
        games.screen.add(self.ship)

        self.asteroid_aims = False
        self.alienship_aims = False
Example #26
0
def createShip():
    ship = Ship()
    ship.name = request.json.get('name')
    ship.model = request.json.get('model')
    ship.manufacturer = request.json.get('manufacturer')
    ship.cost_in_credits = request.json.get('cost_in_credits')
    ship.length = request.json.get('length')
    ship.max_atmosphering_speed = request.json.get('max_atmosphering_speed')
    ship.crew = request.json.get('crew')
    ship.passengers = request.json.get('passengers')
    ship.cargo_capacity = request.json.get('cargo_capacity')
    ship.consumables = request.json.get('consumables')
    ship.hyperdrive_rating = request.json.get('hyperdrive_rating')
    ship.MGLT = request.json.get('MGLT')
    ship.starship_class = request.json.get('starship_class')
    ship.save()

    return jsonify(ship.to_dict()), 201
Example #27
0
def popular(request):
    sh = Ship(name="FiTe01", cls=0, skill=1, init=6, attack=6, defense=9, target=3, cost_metal=1000, cost_cristal=1000, cost_gold=1000, race=0).save()
    sh = Ship(name="FiTe02", cls=0, skill=2, init=1, attack=20, defense=8, target=2, cost_metal=1000, cost_cristal=1000, cost_gold=1000, race=0).save()
    sh = Ship(name="CoTe01", cls=1, skill=0, init=12, attack=12, defense=20, target=1, cost_metal=2000, cost_cristal=2000, cost_gold=2000, race=0).save()
    sh = Ship(name="CoTe02", cls=1, skill=1, init=7, attack=11, defense=25, target=2, cost_metal=2000, cost_cristal=2000, cost_gold=2000, race=0).save()
    sh = Ship(name="CoTe03", cls=1, skill=2, init=2, attack=30, defense=30, target=3, cost_metal=2000, cost_cristal=2000, cost_gold=2000, race=0).save()
    sh = Ship(name="CoTe04", cls=1, skill=5, init=20, attack=20, defense=20, target=5, cost_metal=2000, cost_cristal=2000, cost_gold=2000, race=0).save()
    sh = Ship(name="FrTe01", cls=2, skill=3, init=18, attack=17, defense=31, target=1, cost_metal=4000, cost_cristal=4000, cost_gold=4000, race=0).save()
    sh = Ship(name="FrTe02", cls=2, skill=4, init=20, attack=35, defense=35, target=7, cost_metal=4000, cost_cristal=4000, cost_gold=4000, race=0).save()
    sh = Ship(name="FrTe03", cls=2, skill=5, init=20, attack=30, defense=30, target=5, cost_metal=4000, cost_cristal=4000, cost_gold=4000, race=0).save()
    sh = Ship(name="FrTe04", cls=2, skill=0, init=13, attack=20, defense=33, target=2, cost_metal=4000, cost_cristal=4000, cost_gold=4000, race=0).save()
    sh = Ship(name="CrTe01", cls=3, skill=0, init=14, attack=110, defense=110, target=4, cost_metal=15000, cost_cristal=15000, cost_gold=15000, race=0).save()
    sh = Ship(name="BsTe01", cls=4, skill=0, init=15, attack=400, defense=390, target=0, cost_metal=40000, cost_cristal=40000, cost_gold=40000, race=0).save()
    
    
    sh = Ship(name="FiCi01", cls=0, skill=0, init=11, attack=7, defense=9, target=1, cost_metal=1000, cost_cristal=1000, cost_gold=1000, race=1).save()
    sh = Ship(name="FiCi02", cls=0, skill=3, init=16, attack=12, defense=4, target=3, cost_metal=2000, cost_cristal=500, cost_gold=500, race=1).save()
    sh = Ship(name="CoCi01", cls=1, skill=0, init=12, attack=17, defense=20, target=2, cost_metal=2000, cost_cristal=2000, cost_gold=2000, race=1).save()
    sh = Ship(name="CoCi02", cls=1, skill=3, init=17, attack=65, defense=12, target=0, cost_metal=4000, cost_cristal=1000, cost_gold=1000, race=1).save()
    sh = Ship(name="CoCi04", cls=1, skill=3, init=17, attack=65, defense=20, target=4, cost_metal=4000, cost_cristal=1000, cost_gold=1000, race=1).save()
    sh = Ship(name="CoCi05", cls=1, skill=5, init=20, attack=30, defense=30, target=5, cost_metal=2000, cost_cristal=2000, cost_gold=2000, race=1).save()
    sh = Ship(name="FrCi01", cls=2, skill=0, init=13, attack=22, defense=29, target=0, cost_metal=4000, cost_cristal=4000, cost_gold=4000, race=1).save()
    sh = Ship(name="CrCi01", cls=3, skill=0, init=14, attack=50, defense=90, target=1, cost_metal=15000, cost_cristal=15000, cost_gold=15000, race=1).save()
    sh = Ship(name="BsCi01", cls=4, skill=3, init=19, attack=450, defense=200, target=4, cost_metal=80000, cost_cristal=20000, cost_gold=20000, race=1).save()
    sh = Ship(name="BsCi02", cls=4, skill=4, init=20, attack=550, defense=500, target=7, cost_metal=40000, cost_cristal=40000, cost_gold=40000, race=1).save()
    sh = Ship(name="BsCi03", cls=4, skill=5, init=20, attack=500, defense=500, target=5, cost_metal=40000, cost_cristal=40000, cost_gold=40000, race=1).save()
    sh = Ship(name="BsCi04", cls=4, skill=3, init=17, attack=455, defense=350, target=1, cost_metal=80000, cost_cristal=20000, cost_gold=20000, race=1).save()    
    
    sh = Ship(name="FiXe01", cls=0, skill=1, init=6, attack=4, defense=8, target=0, cost_metal=500, cost_cristal=2000, cost_gold=500, race=2).save()
    sh = Ship(name="FiXe02", cls=0, skill=4, init=20, attack=10, defense=9, target=7, cost_metal=1000, cost_cristal=1000, cost_gold=1000, race=2).save()
    sh = Ship(name="FiXe03", cls=0, skill=1, init=6, attack=15, defense=10, target=4, cost_metal=500, cost_cristal=2000, cost_gold=5000, race=2).save()
    sh = Ship(name="FiXe04", cls=0, skill=5, init=20, attack=7, defense=7, target=5, cost_metal=1000, cost_cristal=1000, cost_gold=1000, race=2).save()
    sh = Ship(name="CoXe01", cls=1, skill=1, init=7, attack=27, defense=20, target=4, cost_metal=1000, cost_cristal=4000, cost_gold=1000, race=2).save()
    sh = Ship(name="FrXe01", cls=2, skill=1, init=8, attack=30, defense=30, target=3, cost_metal=2000, cost_cristal=8000, cost_gold=2000, race=2).save()
    sh = Ship(name="CrXe01", cls=3, skill=1, init=9, attack=45, defense=40, target=2, cost_metal=10000, cost_cristal=25000, cost_gold=10000, race=2).save()
    sh = Ship(name="CrXe02", cls=3, skill=1, init=9, attack=50, defense=80, target=1, cost_metal=10000, cost_cristal=25000, cost_gold=10000, race=2).save()
    sh = Ship(name="BsXe01", cls=4, skill=1, init=15, attack=180, defense=300, target=4, cost_metal=20000, cost_cristal=80000, cost_gold=20000, race=2).save()
    sh = Ship(name="BsXe02", cls=4, skill=1, init=15, attack=130, defense=350, target=0, cost_metal=20000, cost_cristal=80000, cost_gold=20000, race=2).save()
    sh = Ship(name="BsXe03", cls=4, skill=1, init=15, attack=150, defense=300, target=1, cost_metal=20000, cost_cristal=80000, cost_gold=20000, race=2).save()
    sh = Ship(name="BsXe04", cls=4, skill=5, init=20, attack=330, defense=330, target=5, cost_metal=40000, cost_cristal=40000, cost_gold=40000, race=2).save()
    
    sh = Ship(name="FiQr01", cls=0, skill=0, init=11, attack=5, defense=12, target=0, cost_metal=1000, cost_cristal=1000, cost_gold=1000, race=3).save()
    sh = Ship(name="CoQr01", cls=1, skill=0, init=12, attack=12, defense=24, target=2, cost_metal=2000, cost_cristal=2000, cost_gold=2000, race=3).save()
    sh = Ship(name="CoQr02", cls=1, skill=4, init=20, attack=15, defense=30, target=7, cost_metal=2000, cost_cristal=2000, cost_gold=2000, race=3).save()
    sh = Ship(name="FrQr01", cls=2, skill=0, init=13, attack=30, defense=50, target=2, cost_metal=4000, cost_cristal=4000, cost_gold=4000, race=3).save()
    sh = Ship(name="FrQr02", cls=2, skill=0, init=13, attack=30, defense=50, target=3, cost_metal=4000, cost_cristal=4000, cost_gold=4000, race=3).save()
    sh = Ship(name="FrQr03", cls=2, skill=0, init=13, attack=50, defense=30, target=4, cost_metal=4000, cost_cristal=4000, cost_gold=4000, race=3).save()
    sh = Ship(name="FrQr04", cls=2, skill=5, init=20, attack=40, defense=40, target=5, cost_metal=4000, cost_cristal=4000, cost_gold=4000, race=3).save()
    sh = Ship(name="CrQr01", cls=3, skill=0, init=14, attack=50, defense=150, target=2, cost_metal=15000, cost_cristal=15000, cost_gold=15000, race=3).save()
    sh = Ship(name="CrQr02", cls=3, skill=0, init=14, attack=80, defense=150, target=3, cost_metal=15000, cost_cristal=15000, cost_gold=15000, race=3).save()
    sh = Ship(name="CrQr03", cls=3, skill=0, init=14, attack=150, defense=100, target=4, cost_metal=15000, cost_cristal=15000, cost_gold=15000, race=3).save()
    sh = Ship(name="CrQr04", cls=3, skill=5, init=20, attack=100, defense=100, target=5, cost_metal=15000, cost_cristal=15000, cost_gold=15000, race=3).save()
    sh = Ship(name="BsQr01", cls=4, skill=0, init=15, attack=500, defense=550, target=1, cost_metal=40000, cost_cristal=40000, cost_gold=40000, race=3).save()
    
    sh = Ship(name="FiMa01", cls=0, skill=2, init=1, attack=5, defense=10, target=0, cost_metal=500, cost_cristal=500, cost_gold=2000, race=4).save()
    sh = Ship(name="FiMa02", cls=0, skill=2, init=1, attack=15, defense=7, target=2, cost_metal=500, cost_cristal=500, cost_gold=2000, race=4).save()
    sh = Ship(name="FiMa03", cls=0, skill=0, init=1, attack=30, defense=5, target=3, cost_metal=1000, cost_cristal=1000, cost_gold=1000, race=4).save()
    sh = Ship(name="FiMa04", cls=0, skill=5, init=20, attack=15, defense=15, target=5, cost_metal=1000, cost_cristal=1000, cost_gold=1000, race=4).save()
    sh = Ship(name="CoMa01", cls=1, skill=2, init=2, attack=40, defense=20, target=4, cost_metal=1000, cost_cristal=1000, cost_gold=4000, race=4).save()
    sh = Ship(name="CoMa02", cls=1, skill=2, init=2, attack=20, defense=15, target=0, cost_metal=1000, cost_cristal=1000, cost_gold=4000, race=4).save()
    sh = Ship(name="FrMa01", cls=2, skill=2, init=3, attack=50, defense=40, target=2, cost_metal=2000, cost_cristal=8000, cost_gold=2000, race=4).save()
    sh = Ship(name="CrMa01", cls=3, skill=2, init=4, attack=100, defense=150, target=4, cost_metal=10000, cost_cristal=25000, cost_gold=10000, race=4).save()
    sh = Ship(name="CrMa02", cls=3, skill=0, init=14, attack=50, defense=100, target=1, cost_metal=15000, cost_cristal=15000, cost_gold=15000, race=4).save()
    sh = Ship(name="CrMa03", cls=3, skill=4, init=20, attack=200, defense=80, target=7, cost_metal=15000, cost_cristal=15000, cost_gold=15000, race=4).save()
    sh = Ship(name="CrMa04", cls=3, skill=5, init=20, attack=120, defense=120, target=5, cost_metal=15000, cost_cristal=15000, cost_gold=15000, race=4).save()
    sh = Ship(name="BsMa01", cls=4, skill=2, init=5, attack=500, defense=400, target=3, cost_metal=20000, cost_cristal=80000, cost_gold=20000, race=4).save()
    
    from base.models import Galaxy
    #a = Galaxy(x=1, y=1, name='UmUm').save()
    a = Galaxy(x=1, y=2, name='UmDois').save()
    a = Galaxy(x=1, y=3, name='UmTres').save()
    a = Galaxy(x=1, y=4, name='UmQuatro').save()
    a = Galaxy(x=2, y=1, name='DoisUm').save()
    a = Galaxy(x=2, y=2, name='DoisDois').save()
    a = Galaxy(x=2, y=3, name='DoisTres').save()
    a = Galaxy(x=2, y=4, name='DoisQuatro').save()
    
    return redirect("overview")
Example #28
0
def create_ships(field):
    # creating ships objects where x1 - mean 1-deck, x2 - two decks and so on
    x1 = Ship(1, 4, [])
    x2 = Ship(2, 3, [])
    x3 = Ship(3, 2, [])
    x4 = Ship(4, 1, [])
    # player_ships - list of all player's ships on a field
    player_ships = []
    # x1+x2+x3+x4 => means types of ships
    ships_to_place = 4

    question = [
        'Place one-deck ship', 'Place two-deck ship', 'Place three-deck ship',
        'Place four-deck ship'
    ]

    # check if ships been already placed
    x1_flag = False
    x2_flag = False
    x3_flag = False
    x4_flag = False

    while ships_to_place > 0:
        print('Select what kind of ships do you want to place now:\n')
        for index, string in enumerate(question):
            print(index, string + '\n')

        usr_choice = input('> ')
        usr_choice = int(usr_choice)
        os.system('cls' if os.name == 'nt' else 'clear')
        Field.print_field(Field, player_ships)

        if usr_choice == 0:
            if x1_flag == False:
                x1.place_ship(player_ships)
                player_ships.extend(x1.coordinates)
                x1_flag = True
                ships_to_place -= 1
            else:
                print('\aError: This ships have been already added!\n\n')

        elif usr_choice == 1:
            if x2_flag == False:
                x2.place_ship(player_ships)
                player_ships.extend(x2.coordinates)
                x2_flag = True
                ships_to_place -= 1
            else:
                print('\aError: This ships have been already added!\n\n')

        elif usr_choice == 2:
            if x3_flag == False:
                x3.place_ship(player_ships)
                player_ships.extend(x3.coordinates)
                x3_flag = True
                ships_to_place -= 1
            else:
                print('\aError: This ships have been already added!\n\n')

        elif usr_choice == 3:
            if x4_flag == False:
                x4.place_ship(player_ships)
                player_ships.extend(x4.coordinates)
                x4_flag = True
                ships_to_place -= 1
            else:
                print('\aError: This ships have been already added!\n\n')

        else:
            print('\aError: Wrong input!\n\n')

    print('Great job! You\'ve just added all your ships!')

    return player_ships
def init_db():
    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    from models import Ship, Race, Crew, Rank
    Base.metadata.drop_all(bind=engine)
    Base.metadata.create_all(bind=engine)

    # Create the fixtures
    vulcan = Race(name='Vulcan')
    db_session.add(vulcan)
    human = Race(name='Human')
    db_session.add(human)
    kelpien = Race(name='Kelpien')
    db_session.add(kelpien)
    synthetic = Race(name='Synthetic')
    db_session.add(synthetic)
    kelpien = Race(name='Kelpien')
    db_session.add(kelpien)
    synthetic = Race(name='Synthetic')
    db_session.add(synthetic)
    klingon = Race(name='Klingon')
    db_session.add(klingon)
    barzan = Race(name='Barzan')
    db_session.add(barzan)

    captain = Rank(name='Captain')
    db_session.add(captain)
    first_officer = Rank(name='First Officer')
    db_session.add(first_officer)
    chief_engineer = Rank(name='Chief Engineer')
    db_session.add(chief_engineer)
    science_officer = Rank(name='Science Officer')
    db_session.add(science_officer)
    chief_medical_officer = Rank(name='Chief Medical Officer')
    db_session.add(chief_medical_officer)
    communication_officer = Rank(name=' Communication Officer')
    db_session.add(communication_officer)
    ensign = Rank(name='Ensign')
    db_session.add(ensign)
    helmsman = Rank(name='Helmsman')
    db_session.add(helmsman)
    security_chief = Rank(name='Security Chief')
    db_session.add(security_chief)
    operations_officer = Rank(name='Operations Officer')
    db_session.add(operations_officer)
    transporter_chief = Rank(name='Transporter Chief')
    db_session.add(transporter_chief)

    discovery = Ship(name='U.S.S Discovery')
    db_session.add(discovery)
    enterprise = Ship(name='U.S.S. Enterprise')
    db_session.add(enterprise)

    jl = Crew(name='Jean-Luc Picard',
              ship=enterprise,
              race=human,
              rank=captain)
    db_session.add(jl)
    pike = Crew(name='Christopher Pike',
                ship=discovery,
                race=human,
                rank=captain)
    db_session.add(pike)
    lorca = Crew(name='Gabriel Lorca',
                 ship=discovery,
                 race=human,
                 rank=captain)
    db_session.add(lorca)

    riker = Crew(name='William Riker',
                 ship=enterprise,
                 race=human,
                 rank=first_officer)
    db_session.add(riker)
    saru = Crew(name='Saru', ship=discovery, race=kelpien, rank=first_officer)
    db_session.add(saru)

    la = Crew(name='Geordi La Forge',
              ship=enterprise,
              race=human,
              rank=chief_engineer)
    db_session.add(la)
    reno = Crew(name='Jett Reno',
                ship=discovery,
                race=human,
                rank=chief_engineer)
    db_session.add(reno)

    data = Crew(name='Data',
                ship=enterprise,
                race=synthetic,
                rank=science_officer)
    db_session.add(data)
    burn = Crew(name='Michael Burnham',
                ship=discovery,
                race=human,
                rank=science_officer)
    db_session.add(burn)

    b_crusher = Crew(name='Beverly Crusher',
                     ship=enterprise,
                     race=human,
                     rank=chief_medical_officer)
    db_session.add(b_crusher)
    pulaski = Crew(name='Katherine Pulaski',
                   ship=enterprise,
                   race=human,
                   rank=chief_medical_officer)
    db_session.add(pulaski)
    hugh = Crew(name='Hugh Culbe',
                ship=discovery,
                race=human,
                rank=chief_medical_officer)
    db_session.add(hugh)
    tracy = Crew(name='Tracy Pollard',
                 ship=discovery,
                 race=human,
                 rank=chief_medical_officer)
    db_session.add(tracy)

    pend = Crew(name='Pendleton',
                ship=enterprise,
                race=human,
                rank=communication_officer)
    db_session.add(pend)
    ra = Crew(name='R.A. Bryce',
              ship=discovery,
              race=human,
              rank=communication_officer)
    db_session.add(ra)

    wc = Crew(name='Wesley Crusher',
              ship=enterprise,
              race=human,
              rank=helmsman)
    db_session.add(wc)
    keyla = Crew(name='Keyla Detmer',
                 ship=discovery,
                 race=human,
                 rank=helmsman)
    db_session.add(keyla)

    worf = Crew(name='Worf',
                ship=enterprise,
                race=klingon,
                rank=security_chief)
    db_session.add(worf)
    nhan = Crew(name='Nhan', ship=discovery, race=barzan, rank=security_chief)
    db_session.add(nhan)

    data = Crew(name='Data',
                ship=enterprise,
                race=synthetic,
                rank=operations_officer)
    db_session.add(data)
    joann = Crew(name='Joann Owosekun',
                 ship=discovery,
                 race=human,
                 rank=operations_officer)
    db_session.add(joann)

    miles = Crew(name='Miles O’Brien',
                 ship=enterprise,
                 race=human,
                 rank=transporter_chief)
    db_session.add(miles)
    airiam = Crew(name='Airiam',
                  ship=discovery,
                  race=synthetic,
                  rank=transporter_chief)
    db_session.add(airiam)

    w_c2 = Crew(name='Wesley Crusher',
                ship=enterprise,
                race=human,
                rank=ensign)
    db_session.add(w_c2)
    st = Crew(name='Sylvia Tilly', ship=discovery, race=human, rank=ensign)
    db_session.add(st)

    db_session.commit()
Example #30
0
                mb[ss_id][item['type_id']].append(item)
            except:
                mb[ss_id][item['type_id']] = [item]
    #Retry with a few seconds pause until you get a proper answer. This is literally the approach I take on zKillboard. In a 5 minute time span I can have anywhere from 200-1000 CREST requests with about a 0.1% error rate.


for region in regions:
    print "fetching region: " + str(region)
    fetch_by_region_s(region)
    fetch_by_region_b(region)

search_paths = False
if search_paths:
    for path in paths:
        print "New ship for path: " + str(path)
        s = Ship()
        s.capacity = cargo_capacity
        s.isk = isk
        s.starting_isk = isk
        count = 0
        pbs = {}
        for ss in path[1:]:
            if ss in mb.keys():  #maybe nothing in ss
                for typeid in mb[ss].keys():
                    for item in mb[ss][typeid]:
                        #print item
                        try:
                            pbs[typeid].append(item)
                        except:
                            pbs[typeid] = [item]
        for ss in path:
Example #31
0
    def make_move(self, request):
        """Makes a move. Returns a game state with message"""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        player = User.by_name(request.user_name)

        # preflight checks for valid request
        if not player:
            raise endpoints.BadRequestException('User not found!')
        if game.status == 'game over':
            raise endpoints.BadRequestException('Game already over!')
        if game.status == 'setting up':
            raise endpoints.BadRequestException(
                'Game not ready yet! Place your ships.')
        if game.p1 != player.key and game.p2 != player.key:
            raise endpoints.BadRequestException(
                'The specified user is not playing the specified game.')

        #  determine who is making a move and if it's really their turn
        if game.p1 == player.key:
            opponent = game.p2.get()
            if game.status == 'p2 move':
                raise endpoints.BadRequestException('Error: It is ' +
                                                    opponent.name +
                                                    '\'s turn!')
        else:
            opponent = game.p1.get()
            if game.status == 'p1 move':
                raise endpoints.BadRequestException('Error: It is ' +
                                                    opponent.name +
                                                    '\'s turn!')

        ## coordinates
        x = int(request.x)
        y = int(request.y)

        if x not in range(BOARD_SIZE) or y not in range(BOARD_SIZE):
            raise endpoints.BadRequestException(
                'Attempted move is off the board.')

        # attempt move
        if Move.get_move(game, player, x, y):
            raise endpoints.BadRequestException('You already made that move')

        # we have determined player is making a valid move, so switch whose turn it is
        if game.status == 'p1 move':
            game.status = 'p2 move'
        else:
            game.status = 'p1 move'
        game.put()

        # create a Move object
        move = Move(parent=game.key, player=player.key, x=x, y=y)
        move.put()

        # check for hits
        ships = Ship.query(ancestor=game.key).filter(
            Ship.player == opponent.key).fetch()
        position = None  # position that was hit, if any
        ship = None  # ship that was hit, if any
        to_put = []
        for s in ships:
            position = Position.query(ancestor=s.key).filter(
                Position.x == x, Position.y == y).get()

            if position:
                position.hit = True
                position.put()
                positions = Position.query(ancestor=s.key).fetch()
                hit_positions = [p for p in positions if p.hit == True]

                if positions == hit_positions:
                    s.sunk = True
                    s.put()
                    sunk_ships = [sunk for sunk in ships if sunk.sunk == True]

                    if sunk_ships == ships:
                        game.status = 'game over'
                        game.winner = player.key
                        game.put()

                        # send game-over email
                        message = '{} sunk {}! The game is over and {} won!'.format(
                            player.name, s.ship, player.name)
                        self.sendEmail(player, game, message)
                        self.sendEmail(opponent, game, message)

                        # return game over MoveResponse
                        return MoveResponse(
                            hit=True,
                            ship=s.ship,
                            sunk=True,
                            message='Hit! Sunk! Game over! You win!')

                    #return sunk ship message
                    message = 'Your turn! {} sunk your {}!'.format(
                        player.name, s.ship)
                    self.sendEmail(opponent, game, message)

                    return MoveResponse(hit=True,
                                        ship=s.ship,
                                        sunk=True,
                                        message="Hit! Sunk " + s.ship + "!")

                # hit message sent to opponent
                message = 'Your turn! {} hit your {}!'.format(
                    player.name, s.ship)
                self.sendEmail(opponent, game, message)
                # return hit message
                return MoveResponse(hit=True,
                                    ship=s.ship,
                                    sunk=False,
                                    message="Hit on " + s.ship + "!")

        message = 'Your turn! {} missed at {}, {}!'.format(player.name, x, y)
        self.sendEmail(opponent, game, message)
        # no match for a ship at x, y, so return a Miss message
        return MoveResponse(hit=False,
                            message='Miss at ' + str(x) + ' , ' + str(y) + '!')