def test_bad_direction(self):
        '''Sends an invalid direction as arguments.'''
        robot_id = "test_bad_direction_18445"
        robot = Robot(robot_id, "123")
        world = World()
        action_manager = ActionManager()
        database = MemcachedDatabase()

        world.add_robot(robot, (12, 6))
        database.commit()

        with self.assertRaises(InvalidArgumentsError):
            action_manager.do_action("123", "move", [robot_id, "U"])

        database.rollback()

        with self.assertRaises(InvalidArgumentsError):
            action_manager.do_action("123", "move", [robot_id, 988])

        database.rollback()

        with self.assertRaises(InvalidArgumentsError):
            action_manager.do_action("123", "move", [robot_id, None])

        database.rollback()

        with self.assertRaises(InvalidArgumentsError):
            action_manager.do_action("123", "move", [robot_id])

        database.rollback()
예제 #2
0
 def setUpClass(cls):
     # Creating a robot that all the tests will use.
     database = MemcachedDatabase()
     world = World()
     robot = Robot(TestGiveBirth.ROBOT_ID, "123")
     world.add_robot(robot, (0, 14))
     database.commit()
예제 #3
0
 def get_static_map(self):
     message = self.get_byte_message(Action.MAP, {"layer": 0})
     self.sock.send(message)
     code, answer = self.get_response(Response.FULL, 10)
     if code == Result.OKEY:
         self.world = World(answer)
     return code, answer
예제 #4
0
    def test_bad_location(self):
        '''Tests planting on an invalid location.'''
        world = World()

        new_plant = Plant()
        with self.assertRaises(InvalidLocationError):
            world.plant(new_plant, (1881, 1998))
예제 #5
0
    def test_water_level(self):
        '''Tests if water level increases after watering.'''
        database = MemcachedDatabase()
        world = World()

        robot = Robot("198.1287.fkdfjei", "123")
        robot.set_location((5, 0))
        robot.set_has_water(True)

        plant = Plant()
        plant.set_water_level(30)

        world.plant(plant, (5, 0))

        database.commit()

        action = WaterAction()
        action.do_action(robot, ["198.1287.fkdfjei"])

        database.commit()

        updated_square = world.get_square((5, 0))
        plant = updated_square.get_plant()

        # Checking if honor increased.
        self.assertEqual(robot.get_honor(), 1)

        self.assertEqual(plant.get_water_level(), 100)
        self.assertFalse(robot.get_has_water())
예제 #6
0
    def test_plant(self):
        '''Tests sensing a plant.'''
        world = World()
        database = MemcachedDatabase()

        new_robot = Robot("poeiekfm98871", "123")

        plant = Plant()
        plant.set_age(12)
        plant.set_water_level(60)

        world.plant(plant, (11, 4))
        database.commit()
        world.add_robot(new_robot, (11, 4))
        database.commit()

        action_manager = ActionManager()
        info = action_manager.do_action(new_robot.get_password(), "sense",
                                        [new_robot.get_id()])

        self.assertEqual(
            info["11,4"], {
                "surface_type": MapSquareTypes.SOIL,
                "robot": True,
                "plant": {
                    "age": 12,
                    "water_level": 60,
                    "matured": True
                }
            })
예제 #7
0
    def configureWorld(self, ):
        """Configures the world.
        """
        # Create a new world
        self._world = World(self)

        # Fill the world with data from the configuration file
        self._world.readConfigurationFile(self._filename)
예제 #8
0
def main2():
    world_height, world_width = 15, 15
    world = World(world_width, world_height)
    agent = Agent(world)
    world.place_agent(agent)

    app = Application(world, agent)
    app.start()
    def setUpClass(cls):
        # Addin a robot to the world. All the tests would use this robot.
        robot = Robot(cls.ROBOT_ID, "123")
        world = World()

        world.add_robot(robot, cls.LOCATION)

        database = MemcachedDatabase()
        database.commit()
예제 #10
0
    def test_non_soil_location(self):
        '''Tests planting on a non-soil location.'''
        world = World()

        new_plant = Plant()
        with self.assertRaises(CannotPlantHereError):
            world.plant(new_plant, (2, 16))

        with self.assertRaises(CannotPlantHereError):
            world.plant(new_plant, (3, 16))
예제 #11
0
def test_world_init_cell_in_correct_state2():
    rows = []
    rows.append([1, 0, 0, 1])
    rows.append([0, 0, 1, 1])
    board = []
    board.append(rows[0])
    board.append(rows[1])
    world = World(board)
    cell = world.cell_at(1, 2)
    assert cell.alive == True
예제 #12
0
def create_world(world_id):
    # world_json = json_message_converter.convert_json_to_ros_message(world_req)
    # world_data = json.loads(world_json)

    if world_id.data in worlds:
        return
    rospy.loginfo('Creating world: {}'.format(world_id.data))

    worlds[world_id.data] = World(world_id=world_id.data,
                                  world_init_prop="stub")
예제 #13
0
    def init(self):
        parser = argparse.ArgumentParser()
        parser.add_argument('--width', type=int)
        parser.add_argument('--height', type=int)
        self.dimensions = parser.parse_args()

        self.clear_pixel_map()

        self.world = World(self.dimensions)
        self.world.create_world()
예제 #14
0
    def __init__(self):
        pg.init()
        pg.mouse.set_cursor(*CURSOR)

        self._camera = Camera()
        self._hotbar = Hotbar()
        self._world = World()
        self._main_player = Player("main_player",
                                   spawn_pos=PLAYER_DEFAULT_SPAWN_POS)

        self._action = GameAction.play
예제 #15
0
    def __init__(self):
        self._world = World()
        configs = Configs()

        self._result = {
            'world_size': '{0},{1}'.format(*self._world.get_size()),
            'plant_max_age': configs.get_plant_max_age(),
            'plant_matured_age': configs.get_plant_matured_age(),
            'action_delay': configs.get_robots_actions_delay(),
            'maximum_energy': configs.get_robots_maximum_energy(),
            'birth_required_honor': configs.get_robots_birth_required_honor()
        }
예제 #16
0
    def test_duplicate(self):
        '''Tests planting twice on a location.'''
        world = World()

        new_plant = Plant()

        world.plant(new_plant, (4, 16))

        MemcachedDatabase().commit()

        with self.assertRaises(AlreadyPlantError):
            world.plant(new_plant, (4, 16))
예제 #17
0
    def __init__(self):
        log("Building world...")
        self.world = World()  # This warning is bunk, we want the autocomplete

        log("Initializing server...")
        self.socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
                                      1)
        self.socket_server.bind((const.SERVER_HOST, const.SERVER_PORT))
        self.socket_server.listen(const.SERVER_NUM_CONNECTIONS)

        log("Server's listening!")
    def test_blocking_object(self):
        '''Tests moving toward a blocking object.'''
        robot_id = "test_invalid_location_8765112"
        robot = Robot(robot_id, "123")
        world = World()
        action_manager = ActionManager()
        database = MemcachedDatabase()

        world.add_robot(robot, (11, 6))
        database.commit()

        with self.assertRaises(LocationIsBlockedError):
            action_manager.do_action("123", "move", [robot_id, "W"])
    def test_directions(self):
        '''Tests if moving in different directions works correctly.'''
        robot_id = "test_directions_154332"
        robot = Robot(robot_id, "123")
        world = World()
        database = MemcachedDatabase()

        world.add_robot(robot, (10, 2))
        database.commit()

        action_manager = ActionManager()

        action_manager.do_action("123", "move", [robot_id, "N"])
        database.commit()
        robot = database.get_robot(robot_id)
        self.assertEqual(robot.get_location(), (10, 1))

        action_manager.do_action("123", "move", [robot_id, "NE"])
        database.commit()
        robot = database.get_robot(robot_id)
        self.assertEqual(robot.get_location(), (11, 0))

        action_manager.do_action("123", "move", [robot_id, "E"])
        database.commit()
        robot = database.get_robot(robot_id)
        self.assertEqual(robot.get_location(), (12, 0))

        action_manager.do_action("123", "move", [robot_id, "SE"])
        database.commit()
        robot = database.get_robot(robot_id)
        self.assertEqual(robot.get_location(), (13, 1))

        action_manager.do_action("123", "move", [robot_id, "S"])
        database.commit()
        robot = database.get_robot(robot_id)
        self.assertEqual(robot.get_location(), (13, 2))

        action_manager.do_action("123", "move", [robot_id, "SW"])
        database.commit()
        robot = database.get_robot(robot_id)
        self.assertEqual(robot.get_location(), (12, 3))

        action_manager.do_action("123", "move", [robot_id, "W"])
        database.commit()
        robot = database.get_robot(robot_id)
        self.assertEqual(robot.get_location(), (11, 3))

        action_manager.do_action("123", "move", [robot_id, "NW"])
        database.commit()
        robot = database.get_robot(robot_id)
        self.assertEqual(robot.get_location(), (10, 2))
예제 #20
0
class Simulator():
    def __init__(self, x, y):
        self.board = board_creator.randomstate(x,y)

    def get_board_size(self):
        return [len(self.board), len(self.board[0])]

    if __name__ == '__main__':
        board = board_creator.randomstate(40,150)
        world = World(board)
        while True:
            board_creator.render_world(world.world)
            world.next_day()
            print('-----------------------------------------------------------------------------------------------------')
    def extract(self) -> None:
        """Extract the worlds data"""
        tbody = self._extract_tbody(self._text)
        parser = WorldListParser()
        parser.feed(tbody)
        parser.close()
        worlds_data = parser.get_results()
        worlds = []

        for world_data in worlds_data:
            world = World(world_data)
            worlds.append(world)

        self._worlds = worlds
예제 #22
0
    def generate(self) -> World:
        _log.info("Starting world generation...")
        zones = []
        zones_left = self.count

        while zones_left > 0:
            if not zones:
                gen_bottom_left = v2(
                    _worldgen_round(-self.min_size.x * 0.75, self.round_to),
                    _worldgen_round(-self.min_size.y * 0.75, self.round_to))
                gen_top_right = v2(
                    _worldgen_round(self.min_size.x * 0.75, self.round_to),
                    _worldgen_round(self.min_size.y * 0.75, self.round_to))
                generated_zone = Zone("starting-room", gen_bottom_left,
                                      gen_top_right)
            else:
                gen_width = _worldgen_round(
                    randint(self.min_size.x, self.max_size.x), self.round_to)
                gen_height = _worldgen_round(
                    randint(self.min_size.y, self.max_size.y), self.round_to)
                # legacy docs below: pypy doesn't have a 3.6 version, so choices() doesn't exist
                # choices() allows weighting
                # by default, k=1, so choices() will only have 1 element (safe to just use [0])
                # the weighting I chose to use was just using the amount of open neighbors to the 10th
                # why to the 10th? I want a significantly less chance of it picking a zone with 3 neighbors as opposed
                # to one with just 1 neighbor. obviously, I should probably just use squared or something
                # but I really _really_ don't want 4-way corridors.
                random_parent_zone = choice(zones)
                open_directions = random_parent_zone.get_open_directions()
                if not open_directions:
                    continue
                random_direction = choice(open_directions)
                offset_func = choice(_WORLDGEN_OFFSET[random_direction])
                bottom_left, top_right = offset_func(random_parent_zone,
                                                     gen_width, gen_height, 0)

                generated_zone = Zone("zone-%d" % (self.count - zones_left),
                                      bottom_left, top_right)
                # if we generated an overlap, just discard it and generate another one
                if _worldgen_has_collision(zones, generated_zone):
                    continue
                random_parent_zone.neighbors[random_direction] = generated_zone
                generated_zone.neighbors[
                    ~random_direction] = random_parent_zone

            zones.append(generated_zone)
            zones_left -= 1

        _log.info("Finished world generation!")
        return World(zones)
예제 #23
0
    def test_invalid_square(self):
        '''Tries to load a file which contains an invalid square number.'''
        with NewWorld():
            map_data = ("00122\n"
                        "11332\n"
                        "12400\n"
                        "00112\n")

            temp_map_fd, temp_map_file_path = tempfile.mkstemp()
            os.write(temp_map_fd, map_data.encode('utf-8'))
            os.close(temp_map_fd)

            with self.assertRaises(InvalidWorldFileError):
                world = World()
                world.load_from_file(temp_map_file_path)
    def test_moving_outside(self):
        '''Tests moving a robot to outside of the world.'''
        robot_id = "test_moving_outside_981165"
        robot = Robot(robot_id, "123")
        world = World()
        action_manager = ActionManager()
        database = MemcachedDatabase()

        world.add_robot(robot, (14, 2))
        database.commit()

        with self.assertRaises(InvalidLocationError):
            action_manager.do_action("123", "move", [robot_id, "E"])

        database.rollback()
예제 #25
0
    def test_out_of_water(self):
        '''Tests if plant die after running out of water.'''
        plant = Plant()
        world = World()
        database = MemcachedDatabase()

        world.plant(plant, (4, 8))
        database.commit()

        # Waiting for 11 cycles.
        time.sleep(11 * 0.03)

        square = world.get_square((4, 8), for_update=False)

        self.assertIsNone(square.get_plant())
예제 #26
0
    def test_invalid_length(self):
        '''Tests with a file that one of it's row's length is invalid.'''

        with NewWorld():
            map_data = ("00122\n"
                        "11332\n"
                        "123000\n"
                        "00112\n")

            temp_map_fd, temp_map_file_path = tempfile.mkstemp()
            os.write(temp_map_fd, map_data.encode('utf-8'))
            os.close(temp_map_fd)

            with self.assertRaises(InvalidWorldFileError):
                world = World()
                world.load_from_file(temp_map_file_path)
예제 #27
0
    def test_locked(self):
        '''Tests with a locked square.'''
        database = MemcachedDatabase()
        world = World()

        robot = Robot("test_locked_robot_190083", "123")
        # Setting the energy to zero, so the updater tries to update the square too.
        robot.set_energy(0)

        world.add_robot(robot, (5, 9))
        database.commit()

        world.get_square((5, 9), for_update=True)

        with self.assertRaises(LockAlreadyAquiredError):
            database.get_robot(robot.get_id(), for_update=True)
예제 #28
0
    def test_out_of_life_robot(self):
        '''Tests when a robot ran out of life.'''
        database = MemcachedDatabase()
        world = World()

        robot = Robot("test_out_of_life_robot_9022", "123")
        robot.set_life(0)

        world.add_robot(robot, (0, 9))
        database.commit()

        received_robot = database.get_robot("test_out_of_life_robot_9022",
                                            for_update=False)
        self.assertFalse(received_robot.get_alive())

        square = world.get_square((0, 9))
        self.assertIsNone(square.get_robot_id())
예제 #29
0
    def test_out_of_energy_robot(self):
        '''Tests when a robot ran out of energy.'''
        database = MemcachedDatabase()
        world = World()

        robot = Robot("test_out_of_energy_robot_18773", "123")
        robot.set_energy(0)

        world.add_robot(robot, (1, 9))
        database.commit()

        got_robot = database.get_robot("test_out_of_energy_robot_18773",
                                       for_update=False)
        self.assertFalse(got_robot.get_alive())

        square = world.get_square((1, 9))
        self.assertIsNone(square.get_robot_id())
async def wshandler(request):
    app = request.app
    ws = web.WebSocketResponse()
    await ws.prepare(request)

    # auth here
    # print(request.headers)
    if app['state']['game_is_running'] == False:
        app['state']['game_is_running'] = True
        app['world'] = World()
        asyncio.ensure_future(game_loop(app))
    player = Player(ws)
    player.fov_needs_update = True

    app['world'].add_player(player)
    app['players'].append(player)

    await ws.send_str(
        json.dumps({
            'type': 'init',
            'data': player.get_client_init_data()
        }))

    try:
        async for msg in ws:
            if msg.type == web.WSMsgType.text:
                packet = json.loads(msg.data)
                logger.debug(json.dumps(packet, indent=2))
                if packet['type'] == 'actions':
                    player.update(packet['data'])
                print("Got message %s" % msg.data)
                # await ws.send_str("Pressed key code: {}".format(msg.data))
            elif msg.type == web.WSMsgType.close or \
                    msg.type == web.WSMsgType.error:
                print("Closed connection")
                break
            else:
                print(msg)

    except Exception as e:
        logger.error(e, exc_info=True)

    finally:
        await remove_player(app, player)

    return ws