Пример #1
0
 def test_planet_owner_ship_arrival(self):
     user = User('user', Color.RED)
     planet = Planet(1, 25, 25, 20, user, None)
     units_count = planet.units.count
     planet.arrival(user)
     self.assertEqual(planet.units.count, units_count + 1)
     self.assertEqual(planet.owner, user)
Пример #2
0
 def test_planet_last_ship_to_cap_arrival(self):
     user = User('user', Color.RED)
     planet = Planet(1, 25, 25, 1, user, None)
     user2 = User('user2', Color.BLUE)
     planet.arrival(user2)
     self.assertEqual(planet.owner, user2)
     self.assertEqual(planet.units.count, 1)
Пример #3
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)
Пример #4
0
 def test_planet_cap(self):
     user1 = User('user', Color.RED)
     planet = Planet(1, 25, 25, 20, user1, None)
     user2 = User('user', Color.BLUE)
     planet.cap(user2)
     self.assertNotEqual(planet.owner, user1)
     self.assertEqual(planet.owner, user2)
Пример #5
0
def db_seed():
    mercury = Planet(planet_name='Mercury',
                     planet_type='Class D',
                     home_star='sol',
                     mass=3.258e23,
                     radius=1516,
                     distance=35.98e6)

    venus = Planet(planet_name='Venus',
                   planet_type='Class k',
                   home_star='sol',
                   mass=4.867e24,
                   radius=3760,
                   distance=67.24e6)

    earth = Planet(planet_name='Earth',
                   planet_type='Class M',
                   home_star='sol',
                   mass=5.972e24,
                   radius=3959,
                   distance=92.96e6)

    db.session.add(mercury)
    db.session.add(venus)
    db.session.add(earth)

    test_user = User(first_name='William',
                     last_name='Herschel',
                     email='*****@*****.**',
                     password='******')

    db.session.add(test_user)
    db.session.commit()
    print('Database Seeded!')
Пример #6
0
 def test_create_action(self):
     state = State(
         planets={
             0: Planet(x=-10, y=1),
             1: Planet(x=10, y=2),
             2: Planet(x=0, y=10),
         },
         hyperlanes={
             (0, 1): Hyperlane(origin=0, target=1),
             (1, 0): Hyperlane(origin=1, target=0),
         },
     )
     valid_actions = {
         (-10, 1, 10, 2),
         (10, 2, -10, 1),
     }
     invalid_actions = {
         (-10, 1, 0, 10),
         (0, 10, -10, 1),
         (0, 10, 10, 2),
         (10, 2, 0, 10),
     }
     self.assertFalse(valid_actions.intersection(invalid_actions))
     for _ in range(100):
         action = create_action(state, correct=True)
         self.assertIn(action, valid_actions)
     for _ in range(100):
         action = create_action(state, correct=False)
         self.assertIn(action, invalid_actions)
Пример #7
0
 def test_send_ships(self):
     planet = Planet(1, 100, 100, 20, User('user', Color.RED), None)
     destination_planet = Planet(2, 300, 300, 20, User('user', Color.RED),
                                 None)
     game = GameView(20, 20, None, User('user', Color.RED), None)
     num_ships = planet.units.count // 2
     units_start = planet.units.count
     planet.send_ships(game, destination_planet, 1 / 2)
     self.assertEqual(planet.units.count, units_start - num_ships)
Пример #8
0
    def generate_mocked_planets(self, player, enemies):
        planets = []
        # for current player
        planets.append(Planet(1, 100, 100, randint(30, 60), player, self))
        planets.append(Planet(2, 400, 200, randint(30, 60), player, self))

        # for enemies
        planets.append(Planet(3, 720, 200, randint(30, 100), enemies[0], self))
        planets.append(Planet(3, 850, 600, randint(30, 100), enemies[1], self))

        return planets
Пример #9
0
 def get(self):
     if 'terrain' in request.args:
         planets = Planet.objects(
             terrain__iexact=request.args.get('terrain'))
     elif 'climate' in request.args:
         planets = Planet.objects(
             climate__iexact=request.args.get('climate'))
     else:
         planets = Planet.objects
     # print(planets)
     response = Planet.schema(many=True).dump(planets)
     return response
Пример #10
0
def add_planet():

    # recibir info del request
    request_body = request.get_json()
    print(request_body)

    new_planet = Planet(name=request_body["name"], climate=request_body["climate"], diameter=request_body["diameter"],
        gravity=request_body["gravity"], population=request_body["population"], terrain=request_body["terrain"])

    db.session.add(new_planet)
    db.session.commit()

    return jsonify("All good, added: ", new_planet.serialize()), 200
Пример #11
0
def create_planet():
    request_body = request.get_json()
    planet = Planet(name=request_body["name"], climate=request_body["climate"], orbital_period=request_body["orbita_period"], population=request_body["population"], rotation_period=request_body["rotation_period"], gravity=request_body["gravity"])
    db.session.add(planet)
    db.session.commit()
    print("Planet created: ", request_body)
    return jsonify(request_body), 200
Пример #12
0
    def initialize_planets_2d(self, ratio):
        num_planets = self.size**2 / ratio
        planet_locations = set([])
        planets = []

        while len(planets) < num_planets:
            coords = (random.randrange(0, self.size),
                      random.randrange(0, self.size))
            coords_str = "{},{}".format(*coords)
            if coords_str in planet_locations:
                continue

            planet = Planet(self.get_random_name(), random.randrange(10, 1000),
                            coords[0], coords[1])
            planets.append({'obj': planet, 'location': coords})

        with self.app.app_context():
            for planet in planets:
                db.session.add(planet['obj'])
            db.session.commit()

            for planet in planets:
                location_dict = {
                    'planet': planet['obj'].id,
                    'ships': [],
                }
                key = self._build_coordinate_key(planet['location'])
                self.redis.set(key, json.dumps(location_dict))
            self.planets = {
                p['obj'].id: {
                    'location': p['location']
                }
                for p in planets
            }
        self.redis.set(self.planets_key, json.dumps(self.planets))
Пример #13
0
def list_addAll():
    body = request.get_json()
    people = body['character']
    planet = body['planet']
    vehicles = body['starship']

    for c in character:
        character1 = Character(name=c["Character Name"],
                               heigth=c["Character heigth"],
                               mass=c["Character mass"],
                               hair_color=c["Character hair color"],
                               skin_color=c["Character skin color"],
                               gender=c["Character Gender"])
        db.session.add(character1)

    for p in planet:
        planet1 = Planet(name=p["Name"],
                         diameter=p["Diameter"],
                         climate=p["Climate"],
                         gravity=p["Gravity"],
                         population=p["Population"])
        db.session.add(planet1)

    for s in starship:
        starships1 = Starship(name=s["Vehicle name"],
                              model=s["Model"],
                              passengers=serialize["Passengers"],
                              consumable=s["consumable"],
                              cargo_capacity=s["Cargo capacity"],
                              hyperdrive_rating=s["Hyperdrive rating"])
        db.session.add(starship1)

        db.session.commit()
Пример #14
0
def add_planet():
    planet_name = request.form['planet_name']
    test = Planet.query.filter_by(planet_name=planet_name).first()
    if test:
        return jsonify(message='That planet already exists'), 409
    else:
        # below line commented since it's already requested above
        # planet_name = request.form['planet_name']
        planet_type = request.form['planet_type']
        home_star = request.form['home_star']
        mass = float(request.form['mass'])
        radius = float(request.form['radius'])
        distance = float(request.form['distance'])

        # SQLAlchemy
        new_planet = Planet(planet_name=planet_name,
                            planet_type=planet_type,
                            home_star=home_star,
                            mass=mass,
                            radius=radius,
                            distance=distance)

        db.session.add(new_planet)
        db.session.commit()
        return jsonify(message='You added a planet!'), 201
Пример #15
0
def get_planets():
    count = get_count('planets')
    for planet_id in range(1, count + 1):
        url = SWAPI_URL.format('planets') + '{}/'.format(planet_id)
        planet = None
        try:
            planet = DB.open().query(Planet).filter(
                Planet.api_url == url).one()
        except:
            obj = get_request(url)
            if 'name' in obj:
                planet = Planet()
                planet.parse_json(obj)
                DB.save(planet)
        if planet:
            print(planet.name)
            print('+++++++++++++++++')
Пример #16
0
 def test_planet_units_genetation(self):
     user = User('user', Color.RED)
     planet = Planet(1, 25, 25, 2, user, None)
     unit_count = planet.units.count
     planet.units.update()
     self.assertEqual(
         planet.units.count,
         unit_count + planet.radius * planet.units.generation_coef)
Пример #17
0
    def test_planet_get_species_2(self):
        p = Planet.get("Kashyyyk")
        species = p.get_species()
        expected = ["Wookiee"]

        # comparing the two list elements ignoring order
        result = not set(species).isdisjoint(expected)

        self.assertEqual(result, True)
Пример #18
0
    def test_planet_get_species_3(self):
        p = Planet.get("Tatooine")
        species = p.get_species()
        expected = ["Jawa", "Human"]

        # comparing the two list elements ignoring order
        result = not set(species).isdisjoint(expected)

        self.assertEqual(result, True)
Пример #19
0
def create_planet():

    request_body_planet = request.get_json()

    newPlanet = Planet(planet_name=request_body_planet["planet_name"], population=request_body_planet["population"], terrain=request_body_planet["terrain"])
    db.session.add(newPlanet)
    db.session.commit()

    return jsonify(request_body_planet), 200
Пример #20
0
 def test_planet_creation(self):
     user = User('user', Color.RED)
     planet = Planet(1, 25, 25, 20, user, None)
     self.assertTrue(planet.units is not None)
     self.assertEqual(planet.spawnRate, 4)
     self.assertEqual(planet.owner, user)
     self.assertEqual(planet.capped, False)
     self.assertNotEqual(planet.img, None)
     self.assertNotEqual(planet.rect, None)
Пример #21
0
    def test_planet_get_characters_2(self):
        p = Planet.get("Kashyyyk")
        characters = p.get_characters()
        char_name = [characters[i].name for i in range(len(characters))]
        expected = ["Chewbacca", "Lowbacca"]

        # comparing the two list elements ignoring order
        result = not set(char_name).isdisjoint(expected)

        self.assertEqual(result, True)
Пример #22
0
    def test_planet_get_characters_3(self):
        p = Planet.get("Tatooine")
        characters = p.get_characters()
        char_name = [characters[i].name for i in range(len(characters))]
        expected = ["C-3PO", "Tusken Raiders", "Het Nkik", "Darth Vader", "Luke Skywalker", "Biggs Darklighter"]

        # comparing the two list elements ignoring order
        result = not set(char_name).isdisjoint(expected)

        self.assertEqual(result, True)
Пример #23
0
    def test_sent(self):
        init_state = State(hyperlanes={
            (0, 1): Hyperlane(origin=0, target=1),
            (1, 0): Hyperlane(origin=1, target=0)
        },
                           planets={
                               0:
                               Planet(owner=1,
                                      ships=(1, 2, 3),
                                      production=(1, 5, 6)),
                               1:
                               Planet()
                           })

        state = attach_action(init_state, 'send 0 1 1 3 2\n')

        self.assertEqual(state.planets, init_state.planets)
        self.assertEqual(
            state.hyperlanes, {
                (0, 1): Hyperlane(origin=0, target=1, action=(1, 3, 2)),
                (1, 0): Hyperlane(origin=1, target=0)
            })
Пример #24
0
def seed():
    mercury = Planet(planet_name="Mercury",
                     planet_type="Class D",
                     home_star="Sol",
                     mass=3.258e23,
                     radius=1516,
                     distance=35.98e6)

    venus = Planet(planet_name="Venus",
                   planet_type="Class K",
                   home_star="Sol",
                   mass=4.867e24,
                   radius=3760,
                   distance=67.24e6)

    earth = Planet(planet_name="Earth",
                   planet_type="Class M",
                   home_star="Sol",
                   mass=5.972e24,
                   radius=3959,
                   distance=92.96e6)

    john = User(fname='John',
                lname='Smith',
                email='*****@*****.**',
                password='******')
    leon = User(fname='Leaon',
                lname='Eric',
                email='*****@*****.**',
                password='******')
    session.add(mercury)
    session.add(venus)
    session.add(earth)
    session.add(john)
    session.add(leon)
    session.commit()  # saving changes to db
    print("Rows added successfully to db")
Пример #25
0
    def test_get_all_planets(self):
        planets = Planet.get_all()
        char_name = [planets[i].name for i in range(len(planets))]
        expected = ['Kashyyyk', 'Tatooine', 'Ando', 'Rindao', 'Omwat', 'Ithor', 'Gamorr', 'Kubindi', 'Kiffex',
                    'Coruscant', 'Honoghr', 'Csilla', 'Anzat', 'Deyer', 'Corellia', 'Bakura', 'Chandrila',
                    'Nar Shaddaa', 'Dac', 'Kinyen', 'Wayland', 'Vinsoth', 'Toola', 'Firrerre', 'Kothlis', 'Ator',
                    'Yavin 4', 'Commenor', 'Ylix', 'Sullust', 'Chad', 'Alzoc III', 'Klatooine', 'Eriadu', 'Nal Hutta',
                    'Endor', 'Rodia', 'Stewjon', 'Devaron', 'Ryloth', 'Hapes', 'Dathomir', 'Gand', 'Alderaan',
                    'Trandosha', 'Khomm', 'Irmenu', "Clak'dor VII", 'Lwhekk', 'Kamino', 'Sriluur', 'Kowak', 'Naboo',
                    'Bespin', 'Socorro']

        # comparing the two list elements ignoring order
        result = not set(char_name).isdisjoint(expected)

        self.assertEqual(result, True)
Пример #26
0
 def setUp(self):
     self.planets = {
         1:
         Planet(owner=1,
                x=2,
                y=3,
                ships=(3, 2, 1),
                production=(6, 5, 1),
                production_rounds_left=2),
         0:
         Planet(owner=0, x=4, y=6, ships=(4, 5, 6))
     }
     self.fleets = [
         Fleet(  # The only and the one
             owner=2,
             origin=1,
             target=0,
             ships=(3, 2, 1),
             eta=5),
     ]
     self.hyperlanes = {
         (1, 0): Hyperlane(origin=1, target=0, fleets=(self.fleets[0], )),
         (0, 1): Hyperlane(origin=0, target=1),
     }
Пример #27
0
def Planet_agregar():
    name = request.json.get("name", None)
    diametro = request.json.get("diametro", None)
    rotation = request.json.get("rotation", None)
    poblacion = request.json.get("poblacion", None)
    terreno = request.json.get("terreno", None)
    planet = Planet(name=name,
                    diametro=diametro,
                    rotation=rotation,
                    poblacion=poblacion,
                    terreno=terreno)
    db.session.add(planet)
    db.session.commit()
    #user=json.loads(name, color_ojos, color_cabello,gender)
    return jsonify({"planet": "ok"})
Пример #28
0
    def test_get_planet_serialize_1(self):
        expected = {
            "description": "Tatooine (pronounced/t\u00e6tu'in/; Jawaese: Tah doo Een e) was a desert world and the first planet in the binary Tatoo star system. It was part of the Arkanis sector in the Outer Rim Territories. It was inhabited by poor locals who mostly farmed moisture for a living. Other activities included used equipment retailing and scrap dealing. The planet was on the 5709-DC Shipping Lane, a spur of the Triellus Trade Route, which itself connected to the Sisar Run.",
            "image": "http://img2.wikia.nocookie.net/__cb20130226044533/starwars/images/thumb/1/18/Tatooine3.png/500px-Tatooine3.png",
            "name": "Tatooine",
            "region": "Outer Rim Territories",
            "system": "Tatoo system"
        }
        actual = Planet.get("Tatooine").serialize
        bool_result = actual["description"] == expected["description"] and \
                        actual["image"] == expected["image"] and \
                        actual["name"] == expected["name"] and \
                        actual["region"] == expected["region"] and \
                        actual["system"] == expected["system"]

        self.assertEqual(True, bool_result)
Пример #29
0
    def test_get_planet_serialize_2(self):        
        expected = {
            "description": "Kamino (pronounced/k\u0259'mino\u028a/), also known as the Planet of Storms, was the watery world where the Clone Army of the Galactic Republic was created, as well as the Kamino Home Fleet. It was inhabited by a race of tall, elegant beings called the Kaminoans, who kept to themselves and were known for their cloning technology. Kamino was located just south of the Rishi Maze, and was governed by the Ruling Council, headed by the Prime Minister.",
            "image": "http://img2.wikia.nocookie.net/__cb20090527045541/starwars/images/thumb/a/a9/Eaw_Kamino.jpg/500px-Eaw_Kamino.jpg",
            "name": "Kamino",
            "region": "Wild Space\nExtra-galactic",
            "system": "Kamino system"
        }
        actual = Planet.get("Kamino").serialize
        bool_result = actual["description"] == expected["description"] and \
                        actual["image"] == expected["image"] and \
                        actual["name"] == expected["name"] and \
                        actual["region"] == expected["region"] and \
                        actual["system"] == expected["system"]

        self.assertEqual(True, bool_result)
Пример #30
0
def list_addAll():
    body = request.get_json()
    people = body["people"]
    planet = body["planet"]
    vehicle = body["vehicle"]

    for p in people:
        people1 = People(
            name=p["Character name"],
            height=p["Character height"],
            mass=p["Character mass"],
            hair_color=p["Character hair_color"],
            skin_color=p["Character skin color"],
            eye_color=p["Character eye color"],
            birth_year=p["Character birth year"],
            gender=p["Character gender"],
        )
        db.session.add(people1)

    for pl in planet:
        planet1 = Planet(
            planet_name=pl["Planet name"],
            rotation_period=pl["Rotation period"],
            orbital_period=pl["Orbital period"],
            diameter=pl["Diameter"],
            climate=pl["Climate"],
            gravity=pl["Gravity"],
            terrain=pl["Terrain"],
            population=pl["Population"],
        )
        db.session.add(planet1)

    for v in planet:
        vehicle1 = Vehicle(
            vehicle_name=v["Vehicle name"],
            model=v["Model"],
            passenger=v["Passenger"],
            consumable=v["Consumable"],
            starship_class=v["Starship class"],
            lenght=v["Lenght"],
            cargo_capacity=v["Cargo capacity"],
            hyperdrive_rating=v["Hyperdrive rating"],
        )
        db.session.add(vehicle1)

        db.session.commit()
Пример #31
0
def seed():
    if os.getenv('env') == "docker":
        db = connect('planets', host="mongo")
    else:
        db = connect('planets')

    db.drop_database('planets')  # CLEARS DATABASE FOR TESTING

    # POPULATING DATA WITH EXAMPLES

    tatooine = Planet(name='dagobah', terrain='swamp', climate='murky',
        appearances=3)
    tatooine.save()

    hoth = Planet(name='hoth', terrain='tundra', climate='cold',
        appearances=1)
    hoth.save()

    print('examples added to the database')
Пример #32
0
    def post(self):
        try:
            result = PlanetSchema().load(request.json)
            newplanet = Planet(**result)
            if Planet.objects(name__iexact=newplanet.name):
                return ApiResponseBuilder.error(
                    'this planet is already in the database', 404)
            newplanet.get_appearances()
            newplanet.save()

        except ma_exc.ValidationError as err:
            return ApiResponseBuilder.error(err.messages, 400)

        return ApiResponseBuilder.success(
            f'planet named {newplanet.name} was added successfully',
            newplanet.serialized, 201)
Пример #33
0
def add_planet():
    planet_name = request.json['planet_name']
    test = Planet.query.filter_by(planet_name=planet_name).first()
    if test:
        return jsonify("There is already planet by that name."), 409
    else:
        planet_type = request.json['planet_type']
        home_star = request.json['home_star']
        mass = float(request.json['mass'])
        radius = float(request.json['radius'])
        distance = float(request.json['distance'])

        new_planet = Planet(planet_name=planet_name,
                            planet_type=planet_type,
                            home_star=home_star,
                            mass=mass,
                            radius=radius,
                            distance=distance)
        db.session.add(new_planet)
        db.session.commit()
        return jsonify(message="You added a planet"), 201
Пример #34
0
def addAll():
    body = request.get_json()
    people = body['people']
    planet = body['planet']
    vehicle = body['vehicle']

    for p in people:
        people1 = People(name=p["Character Name"],
                         height=p["Character height"],
                         mass=p["Character mass"],
                         hair_color=p["Character hair color"],
                         skin_color=p["Character skin color"],
                         eye_color=p["Character eye color"],
                         birth_year=p["Character birth year"],
                         gender=p["Character gender"])
        db.session.add(people1)

    for p in planet:
        planet1 = Planet(planet_name=pl["Planet name"],
                         rotation_period=pl["rotation period"],
                         orbital_period=pl["orbital period"],
                         diameter=pl["diameter"],
                         climate=pl["climate"],
                         gravity=pl["gravity"],
                         terrain=pl["terrain"],
                         population=pl["population"])
        db.session.add(planet1)

    for p in vehicle:
        vehicle1 = Vehicle(vehicle_name=v["vehicle name"],
                           model=v["model"],
                           passenger=v["passenger"],
                           consumable=v["consumable"],
                           starship_class=v["starship class"],
                           lenght=v["lenght"],
                           cargo_capacity=v["cargo capacity"],
                           hyperdrive_rating=v["hyperdrive rating"])
        db.session.add(vehicle1)

        db.session.commit()
Пример #35
0
def add_planets():
    all_planets = []
    for i in range(1, 11):
        planets = requests.get(f"https://www.swapi.tech/api/planets/{i}").json(
        )["result"]["properties"]
        all_planets.append(planets)

    for request_body in all_planets:
        planet = Planet(name=request_body["name"],
                        climate=request_body["climate"],
                        population=request_body["population"],
                        orbital_period=request_body["orbital_period"],
                        rotation_period=request_body["rotation_period"],
                        diameter=request_body["diameter"],
                        gravity=request_body["gravity"],
                        terrain=request_body["terrain"],
                        surface_water=request_body["surface_water"],
                        edited=request_body["edited"],
                        created=request_body["created"],
                        url=request_body["url"])
        db.session.add(planet)
        db.session.commit()

    return jsonify({"msg": "Planets added"}), 200
Пример #36
0
def main():
    exit = False
    planet = Planet()
    robots = planet.robots
    buildings = planet.buildings
    news_channel = []

    inventory = {'fuel': 1000, 'steel': 1000, 'exploration_points': 0}

    print('Welcome Colonist.')
    print('You have been assigned to a {} distant planet known as: {}'.format(
        planet.TYPES_NAME[planet.planet_type], planet.planet_id))
    print(
        'After carefull analysis, this is are the metrics that we could figure out... {}'
        .format(planet.properties))

    print(
        'Hint: Robots use a certain amount of "Fuel" for each minute they are "in service"'
    )
    print('########################## - MENU - ############################')
    print('ROBOTS:')
    print('1) Build robot to extract steel (Cost: {} steel)'.format(
        Robot.TYPES_COST[Robot.STEEL]))
    print('2) Build robot to extract fuel (Cost: {} steel)'.format(
        Robot.TYPES_COST[Robot.FUEL]))
    print('3) Build robot to find new resources (Cost: {} steel)'.format(
        Robot.TYPES_COST[Robot.EXPLORER]))
    print('4) Build robot to defend our installations (Cost: {} steel)'.format(
        Robot.TYPES_COST[Robot.DEFENSE]))
    print('5) Upgrade robot (Cost: {} steel)'.format(Robot.UPGRADE_COST))
    print('BUILDINGS & SPACESHIPS:')
    print('6) Construct Warehouse to store steel (Cost: {} steel)'.format(
        Building.TYPES_COST[Building.WAREHOUSE]))
    print('7) Construct Fuel Tank to store fuel (Cost: {} steel)'.format(
        Building.TYPES_COST[Building.FUEL_TANK]))
    print('8) Construct Factory to process steel (Cost: {} steel)'.format(
        Building.TYPES_COST[Building.FACTORY]))
    print('9) Construct Refinery to process full (Cost: {} steel)'.format(
        Building.TYPES_COST[Building.REFINERY]))
    print('STATUS:')
    print('10) Inventory')
    print('11) Discovered Resources')
    print('12) Robots')
    print('13) Buildings')
    print('14) Planets')
    print('15) News Channel')
    print('16) Exit')
    print('################################################################')
    print('Now is your turn, please select one of the listed actions:')
    while (not exit):
        action = input('--> ')
        try:
            update_discovered_resources(inventory, robots, planet,
                                        news_channel)
            update_inventory(inventory, robots, planet)
            update_robots(inventory, robots, planet)
            create_status_intervals(robots)
            if action == '1':
                print('INFO: Building robot to extract STEEL...')
                robot = build_robot(Robot.STEEL, inventory)
                robots.append(robot)
                print('INFO: Done. Robot {} created and in service.'.format(
                    robot.robot_id))
            elif action == '2':
                print('INFO: Building robot to extract FUEL...')
                robot = build_robot(Robot.FUEL, inventory)
                robots.append(robot)
                print('INFO: Done. Robot {} created and in service.'.format(
                    robot.robot_id))
            elif action == '3':
                print('INFO: Building robot to discover new resources...')
                robot = build_robot(Robot.EXPLORER, inventory)
                robots.append(robot)
                print('INFO: Done. Robot {} created and in service.'.format(
                    robot.robot_id))
            elif action == '4':
                print('INFO: Building robot to defend our installations...')
                robot = build_robot(Robot.DEFENSE, inventory)
                robots.append(robot)
                print('INFO: Done. Robot {} created and in service.'.format(
                    robot.robot_id))
            elif action == '5':
                robot_id = input(
                    'Upgrading robot. Please type the "Robot ID" (e.g RO1742): \n'
                )
                upgrade_robot(robot_id, robots)
                print('INFO: Done. Robot {} Upgraded.'.format(robot_id))
            elif action == '6':
                print('INFO: Construct Warehouse to store steel...')
                building = construct_building(Building.WAREHOUSE, inventory)
                buildings.append(building)
                print('INFO: Done. Building {} created and operative.'.format(
                    building.building_id))

            elif action == '10':
                print('INFO: Inspecting Inventory...')
                print(inventory)
            elif action == '11':
                print('INFO: Inspecting Discovered Resources...')
                for resource in planet.discovered_resources:
                    print('\t {}'.format(resource))
            elif action == '12':
                print('INFO: Inspecting Robots...')
                for robot in robots:
                    print(robot)
            elif action == '13':
                print('INFO: Inspecting Buildings...')
                for building in buildings:
                    print(building)
            elif action == '14':
                print('INFO: Inspecting Planets...')
                print(planet)
            elif action == '15':
                print('INFO: Broadcasting from the News Channel...')
                for news in news_channel:
                    print('\t [N] {}'.format(news))
            elif action == '16':
                print('Exiting...')
                exit = True
            else:
                print('That\'s not a valid option!')
        except Exception as e:
            #print(str(e))
            raise e
Пример #37
0
def create_planet():
    name = request.json.get('name')
    diameter = request.json.get('diameter')
    rotation_period = request.json.get('rotation_period')
    orbital_period = request.json.get('orbital_period')
    gravity = request.json.get('gravity')
    population = request.json.get('population')
    climate = request.json.get('climate')
    terrain = request.json.get('terrain')
    surface_water = request.json.get('surface_water')
    created = request.json.get('created')
    edited = request.json.get('edited')

    if not name:
        return jsonify({"Mensaje": "El nombre no puede estar vacio"})

    new_planet = Planet()
    new_planet.name = name
    new_planet.diameter = diameter
    new_planet.rotation_period = rotation_period
    new_planet.orbital_period = orbital_period
    new_planet.gravity = gravity
    new_planet.population = population
    new_planet.climate = climate
    new_planet.terrain = terrain
    new_planet.surface_water = surface_water

    db.session.add(new_planet)
    db.session.commit()

    return jsonify({"Mensaje": "Planeta creado exitosamente"}), 201
Пример #38
0
 def test_planet_repr_1(self):
     actual = str(Planet.get("Kashyyyk"))
     self.assertEqual(actual, "<name Kashyyyk>")
Пример #39
0
 def test_planet_repr_2(self):
     actual = str(Planet.get("Tatooine"))
     self.assertEqual(actual, "<name Tatooine>")
Пример #40
0
 def test_get_planet_3(self):
     p = Planet.get("Tatooine")
     self.assertEqual(p.name, "Tatooine")
     self.assertEqual(p.region, "Outer Rim Territories")
     self.assertEqual(p.system, "Tatoo system")
Пример #41
0
 def test_get_planet_2(self):
     p = Planet.get("Kashyyyk")
     self.assertEqual(p.name, "Kashyyyk")
     self.assertEqual(p.region, "Mid Rim")
     self.assertEqual(p.system, "Kashyyyk system")
Пример #42
0
 def test_get_planet_1(self):
     p = Planet.get("Kamino")
     self.assertEqual(p.name, "Kamino")
     self.assertEqual(p.region, "Wild Space\nExtra-galactic")
     self.assertEqual(p.system, "Kamino system")