def setUpClass(cls):
        row = [MapSquare(MapSquareTypes.WATER, (0, 18)),
               MapSquare(MapSquareTypes.SOIL, (1, 18)),
               MapSquare(MapSquareTypes.SAND, (2, 18))]

        database = MemcachedDatabase()
        database.add_square_row(row)
    def setUpClass(cls):
        row = [
            MapSquare(MapSquareTypes.WATER, (0, 18)),
            MapSquare(MapSquareTypes.SOIL, (1, 18)),
            MapSquare(MapSquareTypes.SAND, (2, 18))
        ]

        database = MemcachedDatabase()
        database.add_square_row(row)
Ejemplo n.º 3
0
    def test_duplicate_add(self):
        '''Tests adding two squares at the same location. Should raise exception.'''
        database = MemcachedDatabase()

        row = [MapSquare(MapSquareTypes.SOIL, (0, 998))]

        database.add_square_row(row)

        with self.assertRaises(DatabaseException):
            database.add_square_row(row)
    def test_ok(self):
        '''Tests a good scenario.'''
        row = [MapSquare(MapSquareTypes.SOIL, (0, 17))]
        database = MemcachedDatabase()
        database.add_square_row(row)

        plant_action = PlantAction()

        robot = Robot("18873.182873.1123", "123")
        robot.set_location((0, 17))

        plant_action.do_action(robot, ["18873.182873.1123"])
    def test_ok(self):
        '''Tests a good scenario.'''
        row = [MapSquare(MapSquareTypes.SOIL, (0, 17))]
        database = MemcachedDatabase()
        database.add_square_row(row)

        plant_action = PlantAction()

        robot = Robot("18873.182873.1123", "123")
        robot.set_location((0, 17))

        plant_action.do_action(robot, ["18873.182873.1123"])
Ejemplo n.º 6
0
    def test_ok(self):
        '''Tests an OK scenario.'''
        database = MemcachedDatabase()

        row = [
            MapSquare(MapSquareTypes.SOIL, (0, 999)),
            MapSquare(MapSquareTypes.WATER, (1, 999)),
            MapSquare(MapSquareTypes.ROCK, (2, 999)),
            MapSquare(MapSquareTypes.SAND, (3, 999))
        ]

        database.add_square_row(row)

        self.assertEqual(
            database.get_square((0, 999)).get_type(), MapSquareTypes.SOIL)
        self.assertEqual(
            database.get_square((1, 999)).get_type(), MapSquareTypes.WATER)
        self.assertEqual(
            database.get_square((2, 999)).get_type(), MapSquareTypes.ROCK)
        self.assertEqual(
            database.get_square((3, 999)).get_type(), MapSquareTypes.SAND)
    def test_robot_simulation(self):
        '''This test simulates a full game scenario.'''
        database = MemcachedDatabase()
        world = World()
        configs = Configs()

        print()
        print("Simulating a robot playing the game. This may take a while.")

        # Creating a world for the robot to live in.
        # The world map is:
        #
        #    000000
        #    000222
        #    000144
        #    000144

        row01 = [
            MapSquare(MapSquareTypes.SOIL, (0, 30)),
            MapSquare(MapSquareTypes.SOIL, (1, 30)),
            MapSquare(MapSquareTypes.SOIL, (2, 30)),
            MapSquare(MapSquareTypes.SOIL, (3, 30)),
            MapSquare(MapSquareTypes.SOIL, (4, 30)),
            MapSquare(MapSquareTypes.SOIL, (5, 30))
        ]
        row02 = [
            MapSquare(MapSquareTypes.SOIL, (0, 31)),
            MapSquare(MapSquareTypes.SOIL, (1, 31)),
            MapSquare(MapSquareTypes.SOIL, (2, 31)),
            MapSquare(MapSquareTypes.ROCK, (3, 31)),
            MapSquare(MapSquareTypes.ROCK, (4, 31)),
            MapSquare(MapSquareTypes.ROCK, (5, 31))
        ]
        row03 = [
            MapSquare(MapSquareTypes.SOIL, (0, 32)),
            MapSquare(MapSquareTypes.SOIL, (1, 32)),
            MapSquare(MapSquareTypes.SOIL, (2, 32)),
            MapSquare(MapSquareTypes.SAND, (3, 32)),
            MapSquare(MapSquareTypes.WATER, (4, 32)),
            MapSquare(MapSquareTypes.WATER, (5, 32))
        ]
        row04 = [
            MapSquare(MapSquareTypes.SOIL, (0, 33)),
            MapSquare(MapSquareTypes.SOIL, (1, 33)),
            MapSquare(MapSquareTypes.SOIL, (2, 33)),
            MapSquare(MapSquareTypes.SAND, (3, 33)),
            MapSquare(MapSquareTypes.WATER, (4, 33)),
            MapSquare(MapSquareTypes.WATER, (5, 33))
        ]

        database.add_square_row(row01)
        database.add_square_row(row02)
        database.add_square_row(row03)
        database.add_square_row(row04)

        # Creating parent of our robot.
        parent_robot = Robot("parent_robot_1982.345", "123", name="Parent")
        parent_robot.set_honor(configs.get_robots_birth_required_honor() + 1)
        world.add_robot(parent_robot, (2, 31))
        database.commit()

        # Giving birth to our hero.
        result = self.post_request({
            'command': 'give_birth',
            'password': '******',
            'args': ["parent_robot_1982.345"]
        })
        self.assertEqual(result['status'], 200, result)
        born_password = result['result']

        # Robot requests a born.
        result = self.post_request({
            'command': 'born',
            'password': born_password,
            'args': [parent_robot.get_id()]
        })
        self.assertEqual(result['status'], 200)
        robot_id = result['result']['robot_id']
        password = result['result']['password']

        # Getting status.
        result = self.post_request({
            'command': 'status',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)
        self.assertTrue(result['result']['alive'])
        self.assertFalse(result['result']['has_water'])
        self.assertEqual(result['result']['location'], "2,30")

        # Moving somewhere to plan a corp.
        # Note that parent robot is on the south. So, we have to turn around it.
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'W']
        })
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'S']
        })
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'S']
        })
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'E']
        })
        self.assertEqual(result['status'], 200, result)

        # We are at the location. Checking if its correct.
        result = self.post_request({
            'command': 'status',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)
        self.assertEqual(result['result']['location'], "2,32")

        # Planting a corp here.
        result = self.post_request({
            'command': 'plant',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)

        # Checking if it is planted.
        result = self.post_request({
            'command': 'sense',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)
        self.assertEqual(result['result']['2,32']['surface_type'],
                         MapSquareTypes.SOIL)
        self.assertIsNotNone(result['result']['2,32']['plant'])

        # Going to pick water.
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'E']
        })
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'E']
        })
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({
            'command': 'pick_water',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({
            'command': 'status',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)
        self.assertTrue(result['result']['has_water'])

        # Getting back to the plant location.
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'W']
        })
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'W']
        })
        self.assertEqual(result['status'], 200, result)

        # Watering
        result = self.post_request({
            'command': 'water',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)

        # Checking
        result = self.post_request({
            'command': 'sense',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)
        # It lost some water already.
        self.assertGreater(result['result']['2,32']['plant']['water_level'],
                           70)

        # Plant should be matured by now. Eating!
        result = self.post_request({
            'command': 'status',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)
        previous_energy = result['result']['energy']

        result = self.post_request({
            'command': 'eat',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({
            'command': 'status',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 200, result)
        self.assertGreater(result['result']['energy'], previous_energy)

        # Now, trying some bad moves!

        # Trying to plant on a sand.
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'E']
        })
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({
            'command': 'plant',
            'password': password,
            'args': [robot_id]
        })
        self.assertEqual(result['status'], 500, result)
        self.assertEqual(result['error_code'], 'CannotPlantHereError')

        # Trying to move to a rock.
        result = self.post_request({
            'command': 'move',
            'password': password,
            'args': [robot_id, 'N']
        })
        self.assertEqual(result['status'], 500, result)
        self.assertEqual(result['error_code'], 'LocationIsBlockedError')
    def test_robot_simulation(self):
        '''This test simulates a full game scenario.'''
        database = MemcachedDatabase()
        world = World()
        configs = Configs()

        print()
        print("Simulating a robot playing the game. This may take a while.")

        # Creating a world for the robot to live in.
        # The world map is:
        #
        #    000000
        #    000222
        #    000144
        #    000144

        row01 = [MapSquare(MapSquareTypes.SOIL, (0, 30)),
                 MapSquare(MapSquareTypes.SOIL, (1, 30)),
                 MapSquare(MapSquareTypes.SOIL, (2, 30)),
                 MapSquare(MapSquareTypes.SOIL, (3, 30)),
                 MapSquare(MapSquareTypes.SOIL, (4, 30)),
                 MapSquare(MapSquareTypes.SOIL, (5, 30))]
        row02 = [MapSquare(MapSquareTypes.SOIL, (0, 31)),
                 MapSquare(MapSquareTypes.SOIL, (1, 31)),
                 MapSquare(MapSquareTypes.SOIL, (2, 31)),
                 MapSquare(MapSquareTypes.ROCK, (3, 31)),
                 MapSquare(MapSquareTypes.ROCK, (4, 31)),
                 MapSquare(MapSquareTypes.ROCK, (5, 31))]
        row03 = [MapSquare(MapSquareTypes.SOIL, (0, 32)),
                 MapSquare(MapSquareTypes.SOIL, (1, 32)),
                 MapSquare(MapSquareTypes.SOIL, (2, 32)),
                 MapSquare(MapSquareTypes.SAND, (3, 32)),
                 MapSquare(MapSquareTypes.WATER, (4, 32)),
                 MapSquare(MapSquareTypes.WATER, (5, 32))]
        row04 = [MapSquare(MapSquareTypes.SOIL, (0, 33)),
                 MapSquare(MapSquareTypes.SOIL, (1, 33)),
                 MapSquare(MapSquareTypes.SOIL, (2, 33)),
                 MapSquare(MapSquareTypes.SAND, (3, 33)),
                 MapSquare(MapSquareTypes.WATER, (4, 33)),
                 MapSquare(MapSquareTypes.WATER, (5, 33))]

        database.add_square_row(row01)
        database.add_square_row(row02)
        database.add_square_row(row03)
        database.add_square_row(row04)

        # Creating parent of our robot.
        parent_robot = Robot("parent_robot_1982.345", "123", name="Parent")
        parent_robot.set_honor(configs.get_robots_birth_required_honor() + 1)
        world.add_robot(parent_robot, (2, 31))
        database.commit()

        # Giving birth to our hero.
        result = self.post_request({'command': 'give_birth',
                                    'password': '******',
                                    'args': ["parent_robot_1982.345"]})
        self.assertEqual(result['status'], 200, result)
        born_password = result['result']

        # Robot requests a born.
        result = self.post_request({'command': 'born',
                                    'password': born_password,
                                    'args': [parent_robot.get_id()]})
        self.assertEqual(result['status'], 200)
        robot_id = result['result']['robot_id']
        password = result['result']['password']

        # Getting status.
        result = self.post_request({'command': 'status',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)
        self.assertTrue(result['result']['alive'])
        self.assertFalse(result['result']['has_water'])
        self.assertEqual(result['result']['location'], "2,30")

        # Moving somewhere to plan a corp.
        # Note that parent robot is on the south. So, we have to turn around it.
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'W']})
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'S']})
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'S']})
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'E']})
        self.assertEqual(result['status'], 200, result)

        # We are at the location. Checking if its correct.
        result = self.post_request({'command': 'status',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)
        self.assertEqual(result['result']['location'], "2,32")

        # Planting a corp here.
        result = self.post_request({'command': 'plant',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)

        # Checking if it is planted.
        result = self.post_request({'command': 'sense',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)
        self.assertEqual(result['result']['2,32']['surface_type'], MapSquareTypes.SOIL)
        self.assertIsNotNone(result['result']['2,32']['plant'])

        # Going to pick water.
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'E']})
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'E']})
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({'command': 'pick_water',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({'command': 'status',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)
        self.assertTrue(result['result']['has_water'])

        # Getting back to the plant location.
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'W']})
        self.assertEqual(result['status'], 200, result)
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'W']})
        self.assertEqual(result['status'], 200, result)

        # Watering
        result = self.post_request({'command': 'water',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)

        # Checking
        result = self.post_request({'command': 'sense',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)
        # It lost some water already.
        self.assertGreater(result['result']['2,32']['plant']['water_level'], 70)

        # Plant should be matured by now. Eating!
        result = self.post_request({'command': 'status',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)
        previous_energy = result['result']['energy']

        result = self.post_request({'command': 'eat',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({'command': 'status',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 200, result)
        self.assertGreater(result['result']['energy'], previous_energy)

        # Now, trying some bad moves!

        # Trying to plant on a sand.
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'E']})
        self.assertEqual(result['status'], 200, result)

        result = self.post_request({'command': 'plant',
                                    'password': password,
                                    'args': [robot_id]})
        self.assertEqual(result['status'], 500, result)
        self.assertEqual(result['error_code'], 'CannotPlantHereError')

        # Trying to move to a rock.
        result = self.post_request({'command': 'move',
                                    'password': password,
                                    'args': [robot_id, 'N']})
        self.assertEqual(result['status'], 500, result)
        self.assertEqual(result['error_code'], 'LocationIsBlockedError')
Ejemplo n.º 9
0
class World(Singleton):

    def _initialize(self):
        self._size = (-1, -1)
        self._database = MemcachedDatabase()

        self._database.register_hook(ObjectUpdater())

    def get_size(self):
        '''Returns size of the world.'''
        if self._size == (-1, -1):
            # Reading the size from database, and caching it.
            # Although `load_from_file' method sets this variable,
            # after forking this variable will be reset. So we need
            # to load the size from database again.
            self._size = self._database.get_world_size()

        return self._size

    def add_robot(self, robot, location):
        '''Adds a robot to the world.
        It tries to find the nearest empty point to the specified point.

        @param robot: Instance of objects.robot.Robot.
        @param location: Location to try to add the robot. (x, y)
        '''
        for square_x, square_y in SquareInterator(location, self._size):
            try:
                square_object = self.get_square((square_x, square_y), for_update=True)

                # Checking if something blocked this square.
                if not square_object.is_blocking():
                    robot.set_location((square_x, square_y))
                    self._database.add_robot(robot, (square_x, square_y))
                    # Done.
                    return

            except LockAlreadyAquiredError:
                # If this square was locked, go to the next one.
                continue

        raise exceptions.WorldIsFullError("No free location is remained in the world!") # pragma: no cover

    def move_robot(self, robot, destination):
        '''Moves a robot to the specified location.

        @param destination: A tuple of (x, y)
        '''
        # Locking both origin and destination.
        origin = robot.get_location()

        origin_square = self.get_square(origin, for_update=True)
        destination_square = self.get_square(destination, for_update=True)

        if destination_square.is_blocking():
            raise exceptions.LocationIsBlockedError("Destination location {0} is blocked.".format(destination))

        origin_square.set_robot_id(None)
        destination_square.set_robot_id(robot.get_id())

        robot.set_location(destination)

    def plant(self, plant, location):
        '''Plant a plant on the specified location.'''
        square = self.get_square(location, for_update=True)

        if square.get_type() != MapSquareTypes.SOIL:
            raise exceptions.CannotPlantHereError("Cannot plant on {0} square type.".format(square.get_type()))

        if square.get_plant() is not None:
            raise exceptions.AlreadyPlantError("There's already a plant on {0}".format(location))

        square.set_plant(plant)

    def get_square(self, location, for_update=False):
        '''Gets the square object of the specified location.

        @param location: Location to get.
        @param for_update: If you want to update this square (store its
            changes back to the database) you should set this flag.
            Note that it automatically updates the changes if transaction commits.
        '''
        return self._database.get_square(location, for_update=for_update)

    def load_from_file(self, file_path):
        '''Loads a world from the specified file.'''
        with open(file_path, 'r') as world_file:
            file_lines = world_file.readlines()

        row_length = None
        line_number = 0

        for line in file_lines:
            line = line.replace('\r', '').replace('\n', '')

            if line.startswith("#") or line.isspace():
                continue

            line_number += 1

            # Keeping length of the first line, so we can validate that all
            # the lines have same length.
            if row_length is None:
                row_length = len(line)

            if len(line) != row_length:
                raise exceptions.InvalidWorldFileError("Length of line {0} is invalid.".format(line_number))

            row = []
            column_number = 0
            for square_type in line:
                column_number += 1
                square_type = int(square_type)

                if square_type not in (0, 1, 2, 3):
                    raise exceptions.InvalidWorldFileError(
                        "Found invalid square in line {0} column {1}.".format(line_number, column_number))

                row.append(MapSquare(square_type, (column_number - 1, line_number - 1)))

            self._database.add_square_row(row)

        self._size = (row_length, line_number)
        self._database.set_world_size(self._size)
Ejemplo n.º 10
0
class World(Singleton):
    def _initialize(self):
        self._size = (-1, -1)
        self._database = MemcachedDatabase()

        self._database.register_hook(ObjectUpdater())

    def get_size(self):
        '''Returns size of the world.'''
        if self._size == (-1, -1):
            # Reading the size from database, and caching it.
            # Although `load_from_file' method sets this variable,
            # after forking this variable will be reset. So we need
            # to load the size from database again.
            self._size = self._database.get_world_size()

        return self._size

    def add_robot(self, robot, location):
        '''Adds a robot to the world.
        It tries to find the nearest empty point to the specified point.

        @param robot: Instance of objects.robot.Robot.
        @param location: Location to try to add the robot. (x, y)
        '''
        for square_x, square_y in SquareInterator(location, self._size):
            try:
                square_object = self.get_square((square_x, square_y),
                                                for_update=True)

                # Checking if something blocked this square.
                if not square_object.is_blocking():
                    robot.set_location((square_x, square_y))
                    self._database.add_robot(robot, (square_x, square_y))
                    # Done.
                    return

            except LockAlreadyAquiredError:
                # If this square was locked, go to the next one.
                continue

        raise exceptions.WorldIsFullError(
            "No free location is remained in the world!")  # pragma: no cover

    def move_robot(self, robot, destination):
        '''Moves a robot to the specified location.

        @param destination: A tuple of (x, y)
        '''
        # Locking both origin and destination.
        origin = robot.get_location()

        origin_square = self.get_square(origin, for_update=True)
        destination_square = self.get_square(destination, for_update=True)

        if destination_square.is_blocking():
            raise exceptions.LocationIsBlockedError(
                "Destination location {0} is blocked.".format(destination))

        origin_square.set_robot_id(None)
        destination_square.set_robot_id(robot.get_id())

        robot.set_location(destination)

    def plant(self, plant, location):
        '''Plant a plant on the specified location.'''
        square = self.get_square(location, for_update=True)

        if square.get_type() != MapSquareTypes.SOIL:
            raise exceptions.CannotPlantHereError(
                "Cannot plant on {0} square type.".format(square.get_type()))

        if square.get_plant() is not None:
            raise exceptions.AlreadyPlantError(
                "There's already a plant on {0}".format(location))

        square.set_plant(plant)

    def get_square(self, location, for_update=False):
        '''Gets the square object of the specified location.

        @param location: Location to get.
        @param for_update: If you want to update this square (store its
            changes back to the database) you should set this flag.
            Note that it automatically updates the changes if transaction commits.
        '''
        return self._database.get_square(location, for_update=for_update)

    def load_from_file(self, file_path):
        '''Loads a world from the specified file.'''
        with open(file_path, 'r') as world_file:
            file_lines = world_file.readlines()

        row_length = None
        line_number = 0

        for line in file_lines:
            line = line.replace('\r', '').replace('\n', '')

            if line.startswith("#") or line.isspace():
                continue

            line_number += 1

            # Keeping length of the first line, so we can validate that all
            # the lines have same length.
            if row_length is None:
                row_length = len(line)

            if len(line) != row_length:
                raise exceptions.InvalidWorldFileError(
                    "Length of line {0} is invalid.".format(line_number))

            row = []
            column_number = 0
            for square_type in line:
                column_number += 1
                square_type = int(square_type)

                if square_type not in (0, 1, 2, 3):
                    raise exceptions.InvalidWorldFileError(
                        "Found invalid square in line {0} column {1}.".format(
                            line_number, column_number))

                row.append(
                    MapSquare(square_type,
                              (column_number - 1, line_number - 1)))

            self._database.add_square_row(row)

        self._size = (row_length, line_number)
        self._database.set_world_size(self._size)