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))
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())
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
class WaterAction(Action): def __init__(self): super().__init__() self._world = World() def do_action(self, robot, args): '''Waters the square robot stands on. @param robot: Instance of `objects.robot.Robot'. ''' if len(args) != 1: raise InvalidArgumentsError("`water' action takes no arguments.") if not robot.get_has_water(): raise RobotHaveNoWaterError("Robot does not carry water.") try: square = self._world.get_square(robot.get_location(), for_update=True) except LockAlreadyAquiredError: # Waiting a little, and trying one more time. time.sleep(0.02) square = self._world.get_square(robot.get_location(), for_update=True) # Note: we don't raise an exception if there's no plant. A robot can waste its water. plant = square.get_plant() if plant is not None: plant.set_water_level(100) robot.set_honor(robot.get_honor() + 1) robot.set_has_water(False)
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()
class SenseAction(Action): def __init__(self): super().__init__() self._world = World() def do_action(self, robot, args): '''Gathers and sends information about robot's surrendering. @param robot: Instance of `objects.robot.Robot'. ''' result = {} for square_x, square_y in SquareInterator(robot.get_location(), self._world.get_size(), max_radios=1): square_object = self._world.get_square((square_x, square_y)) is_there_a_robot = square_object.get_robot_id() is not None plant_info = None plant = square_object.get_plant() if plant is not None: plant_info = {'water_level': plant.get_water_level(), 'matured': plant.is_matured(), 'age': plant.get_age()} result["{0},{1}".format(square_x, square_y)] = {"surface_type": square_object.get_type(), "robot": is_there_a_robot, "plant": plant_info} return result
class EatAction(Action): def __init__(self): super().__init__() self._world = World() self._plant_energy = Configs().get_plant_energy() def do_action(self, robot, args): '''Makes robot eat the plant on the current location. @param robot: Instance of `objects.robot.Robot'. ''' if len(args) != 1: raise InvalidArgumentsError("`eat' action takes no arguments.") try: current_square = self._world.get_square(robot.get_location(), for_update=True) except LockAlreadyAquiredError: # Trying one more time. time.sleep(0.02) current_square = self._world.get_square(robot.get_location(), for_update=True) plant = current_square.get_plant() if plant is None: raise NoPlantToEat("There's no plant on {0}".format(robot.get_location())) if plant.is_matured(): robot.set_energy(robot.get_energy() + self._plant_energy) # Plant will be removed from the world, regardless of its maturity. current_square.set_plant(None)
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()
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)
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()
class MUDServer(object): client_pool: list = [] socket_server = None world: World.SingleWorld = None 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 serve(self): worker_thread = Thread(target=self.tick) worker_thread.daemon = True worker_thread.start() while True: connection, address = self.socket_server.accept() connection.settimeout(const.SERVER_CONNECTION_TIMEOUT) log(f"Server - {address} connected") thread = ClientThread(connection, address, self) thread.daemon = True self.client_pool.append(thread) thread.start() def tick(self): """ Server tick functions, handles changes in the world and to the clients """ while True: # TODO: World tick stuff self.world.tick() sleep(const.SERVER_TICK_RATE) def send_all(self, message): for c in self.client_pool: try: c.send(message) except ConnectionAbortedError: self.client_pool.remove(c) log(f"Attempted to send_all to an expired client {c}") def send_hero(self, hero_name, message): for c in self.client_pool: if c.hero and c.hero.name == hero_name: c.send(message) return True return False
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()
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))
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
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
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_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))
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() }
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 __init__(self, master, world: World, agent: Agent): super(GUI, self).__init__(master) self.__world_width = world.get_width() self.__world_height = world.get_height() self.__agent = agent self.__world = world self.__master = master self.__canvas_width = self.__world_width * FIELD_WIDTH self.__canvas_height = self.__world_height * FIELD_HEIGHT self.__create_widgets() self.pack() self.__draw_world()
class MoveAction(Action): DIRECTIONS = { "N": (0, -1), "NE": (1, -1), "E": (1, 0), "SE": (1, 1), "S": (0, 1), "SW": (-1, 1), "W": (-1, 0), "NW": (-1, -1) } def __init__(self): self._world = World() self._logger = Logger() def do_action(self, robot, args): '''Move the robot in the specified direction.. @param robot: Instance of `objects.robot.Robot'. ''' # Validating arguments. if len(args) != 2: raise InvalidArgumentsError( "Move action takes exactly two argument. {0} given.".format( len(args))) direction = args[1] if not isinstance(direction, str) or direction not in MoveAction.DIRECTIONS: raise InvalidArgumentsError( "Invalid direction passed to Move action.") robot_location = robot.get_location() direction_points = MoveAction.DIRECTIONS[direction] destination = (robot_location[0] + direction_points[0], robot_location[1] + direction_points[1]) try: self._do_move(robot, destination) except LockAlreadyAquiredError: # Waiting for a moment, and trying one more time. # Client shouldn't receive an error if, for example, someone updating a plant on these squares. self._logger.info("Concurrency when trying to move a robot.") time.sleep(0.02) self._do_move(robot, destination) def _do_move(self, robot, destination): '''Actually moves the robot to the new location.''' self._world.move_robot(robot, destination)
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))
def test_info(self): '''Test received information.''' action = InfoAction() world = World() configs = Configs() robot = Robot("test_info_action_1293", "123") info = action.do_action(robot, [robot.get_id()]) self.assertEqual(info['world_size'], '{0},{1}'.format(*world.get_size())) self.assertEqual(info['plant_max_age'], configs.get_plant_max_age()) self.assertEqual(info['plant_matured_age'], configs.get_plant_matured_age()) self.assertEqual(info['action_delay'], configs.get_robots_actions_delay()) self.assertEqual(info['birth_required_honor'], configs.get_robots_birth_required_honor())
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_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())
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()
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())
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())
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)
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)
def test_lock(self): '''Tests if location is locked.''' robot_id = "test_move_lock_76120" robot = Robot(robot_id, "123") world = World() action_manager = ActionManager() database = MemcachedDatabase() world.add_robot(robot, (13, 6)) database.commit() database.get_square((13, 7), for_update=True) with self.assertRaises(LockAlreadyAquiredError): action_manager.do_action("123", "move", [robot_id, "S"]) database.rollback()
class MoveAction(Action): DIRECTIONS = {"N": (0, -1), "NE": (1, -1), "E": (1, 0), "SE": (1, 1), "S": (0, 1), "SW": (-1, 1), "W": (-1, 0), "NW": (-1, -1)} def __init__(self): self._world = World() self._logger = Logger() def do_action(self, robot, args): '''Move the robot in the specified direction.. @param robot: Instance of `objects.robot.Robot'. ''' # Validating arguments. if len(args) != 2: raise InvalidArgumentsError("Move action takes exactly two argument. {0} given.".format(len(args))) direction = args[1] if not isinstance(direction, str) or direction not in MoveAction.DIRECTIONS: raise InvalidArgumentsError("Invalid direction passed to Move action.") robot_location = robot.get_location() direction_points = MoveAction.DIRECTIONS[direction] destination = (robot_location[0] + direction_points[0], robot_location[1] + direction_points[1]) try: self._do_move(robot, destination) except LockAlreadyAquiredError: # Waiting for a moment, and trying one more time. # Client shouldn't receive an error if, for example, someone updating a plant on these squares. self._logger.info("Concurrency when trying to move a robot.") time.sleep(0.02) self._do_move(robot, destination) def _do_move(self, robot, destination): '''Actually moves the robot to the new location.''' self._world.move_robot(robot, destination)
def test_one_cycle(self): '''Tests if plant updates correctly after one cycle.''' plant = Plant() world = World() database = MemcachedDatabase() world.plant(plant, (3, 8)) database.commit() # Sleeping one cycle. time.sleep(0.031) square = world.get_square((3, 8), for_update=False) plant = square.get_plant() self.assertEqual(plant.get_age(), 1) self.assertEqual(plant.get_water_level(), 90)
class PlantAction(Action): def __init__(self): super().__init__() self._world = World() def do_action(self, robot, args): '''Plant a plant where robot stands. @param robot: Instance of `objects.robot.Robot'. ''' if len(args) > 1: raise InvalidArgumentsError("`plant' action takes no arguments.") plant = Plant() self._world.plant(plant, robot.get_location())
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()}
def test_maximum_age(self): '''Tests if plant die after maximum age.''' plant = Plant() world = World() database = MemcachedDatabase() world.plant(plant, (11, 8)) database.commit() square = world.get_square((11, 8), for_update=True) plant = square.get_plant() plant.set_age(40) database.commit() # Sleeping one cycle. time.sleep(0.031) square = world.get_square((11, 8), for_update=False) self.assertIsNone(square.get_plant())
def test_no_cycle_passed(self): '''Tests if plant not changed if no cycle passed.''' world = World() database = MemcachedDatabase() plant = Plant() plant.set_age(2) plant.set_water_level(70) world.plant(plant, (6, 8)) database.commit() # Waiting just a little. time.sleep(0.01) square = world.get_square((6, 8), for_update=False) received_plant = square.get_plant() self.assertEqual(received_plant.get_age(), plant.get_age()) self.assertEqual(received_plant.get_water_level(), plant.get_water_level()) self.assertEqual(received_plant.get_last_update(), plant.get_last_update())
def test_eating_not_matured(self): '''Tests when robot eat a non matured plant.''' world = World() database = MemcachedDatabase() action_manager = ActionManager() plant = Plant() plant.set_age(1) world.plant(plant, TestEatAction.LOCATION) database.commit() robot = database.get_robot(TestEatAction.ROBOT_ID, for_update=True) robot.set_energy(10) database.commit() action_manager.do_action("123", "eat", [TestEatAction.ROBOT_ID]) database.commit() updated_robot = database.get_robot(TestEatAction.ROBOT_ID) self.assertEqual(updated_robot.get_energy(), robot.get_energy() - 1)
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}})
def test_locked_square(self): '''Tests updating a locked square.''' plant = Plant() world = World() database = MemcachedDatabase() world.plant(plant, (7, 8)) database.commit() # Locking the square. world.get_square((7, 8), for_update=True) # Sleeping one cycle. time.sleep(0.031) with self.assertRaises(LockAlreadyAquiredError): world.get_square((7, 8), for_update=False)