Ejemplo n.º 1
0
    def get_all_possible_states(self, num_proc):
        size = self.terrain_map.width * self.terrain_map.height
        professor_surroundings = self.get_surroundings()
        x = Array('i', size)
        y = Array('i', size)
        direction = Array('i', size)
        proc = [Process] * num_proc
        for i in range(num_proc):
            proc[i] = Process(target=self.fill_states,
                              args=(
                              int(i * self.terrain_map.height / num_proc), int(self.terrain_map.height / num_proc),
                              int(size * i / num_proc), x, y, direction, professor_surroundings))
            proc[i].start()
        for i in range(num_proc):
            proc[i].join()
        states = []
        i = 0
        while i < size:
            if direction[i] is not 0:
                point = Point(x[i],y[i])
                dir = Directions(direction[i])
                state = State(point,dir)
                states.append(state)
                i += 1
            else:
                index = int(i / int(size / num_proc))
                i = (index + 1) * int(size / num_proc)

        return states
Ejemplo n.º 2
0
 def __init__(self, rows=10, cols=10):
     self.map = Map(rows=rows, cols=cols)
     self.snake = Snake(rows=rows, cols=cols)
     self.directions = Directions()
     self.displaySize = 12
     # self.myDisplay=pygame.display.set_mode((cols*self.displaySize,rows*self.displaySize))
     self.waitTime = 0.03
     self.score = 0
Ejemplo n.º 3
0
def get_random_professor_state(map, width, height):
    x = randint(0, width - 1)
    y = randint(0, height - 1)
    while not TerrainTile(TerrainTypes(map[y * height + x])).is_traversable():
        x = randint(0, width - 1)
        y = randint(0, height - 1)
    random_direction = Directions(randint(1, len(Directions)))
    return State(Point(x, y), random_direction)
Ejemplo n.º 4
0
    def __init__(self, rows=10, cols=10):

        self.directions = Directions()

        self.rows = rows
        self.cols = cols

        # Location of Food
        self.food = (int(self.cols / 3), int(self.rows / 3))
Ejemplo n.º 5
0
    def __init__(self,rows,cols):
        self.directions = Directions()

        # Body Locations
        self.head = [int(cols/2),int(rows/2)]
        self.bodyLocations = [[int(cols/2),int(rows/2+1)]]#,[int(cols/2),int(rows/2+2)],[int(cols/2),int(rows/2+3)]]
        # self.bodyLocations = [[5,6]]
        self.bodySize = 3

        # Orientations
        self.bodyDirections= [self.directions.NORTH,self.directions.NORTH,self.directions.NORTH]
        # self.orientation = self.directions.NORTH
        self.turningPoints = {}
Ejemplo n.º 6
0
def get_professor_state(map, width, height):
    for i in range(width):
        map[height * (height - 1) + i] = "#"
        # TerrainTypes.ROADWAY.value
    professor_point_index = width * (height - 1) + randint(0, width)
    move_count = int(height * .75)
    while move_count > 0:
        move_count -= 1
        professor_point_index += get_random_move(professor_point_index, width, height)
        map[professor_point_index] = "#"
    professor_point = Point(professor_point_index % width, professor_point_index / width)
    random_direction = Directions(randint(1, len(Directions)))
    return State(professor_point, random_direction)
Ejemplo n.º 7
0
    def __init__(self,game=None):
        if game == None:
            self.game = SnakeGame(rows=10,cols=10)
        else:
            self.game = game
        self.directions = Directions()
        self.moves = []
        self.directionArray = [self.directions.NORTH,self.directions.SOUTH,self.directions.EAST,self.directions.WEST]
        self.tempBodyLocations = copy.deepcopy(self.game.snake.bodyLocations)
        self.tempDirections = copy.deepcopy(self.game.snake.bodyDirections)

        # self.displaySize = 12

        self.myDisplay=pygame.display.set_mode((self.game.map.cols*self.game.displaySize,self.game.map.rows*self.game.displaySize))
Ejemplo n.º 8
0
 def __init__(self, file_name, map_array=None, height=None, width=None, professor_state=None):
     # type: (String) -> self
     if map_array == None:
         array = TerrainMap.read_file(file_name)
         professor_x = int(array[0])
         professor_y = int(array[1])
         professor_direction = Directions(int(array[2]))
         self.professor_start_state = State(Point(professor_x,professor_y), professor_direction)
         array = array[3:] #Removes the first two lines which represent the prof state
         height = len(array)
         width = len(array[0])
         array = TerrainMap.flatten_array(array)
         terrain_array = [TerrainTile(TerrainTypes(int(type))) for type in array]
         super(TerrainMap, self).__init__(terrain_array, width, height)
     else:
         self.professor_start_state = professor_state
         terrain_array = [TerrainTile(TerrainTypes(int(type))) for type in map_array]
         super(TerrainMap, self).__init__(terrain_array, width, height)
Ejemplo n.º 9
0
    def Network_playermove(self, data):
        if not self._server.can_move(self.id):
            self.Send({
                "action": "system_message",
                "message": "You can not move yet."
            })
            return

        print("[Server] Player \"" + self.player_name +
              "\" moved to Direction \"" + Directions(data['direction']).name +
              "\".")

        dx, dy = ClientChannel.player_movements[data['direction']]
        if wall_check(self.x + dx, self.y + dy, self.z):
            self.Send({
                "action": "system_message",
                "message": "You bumped into the incredible wall."
            })
            dx, dy = 0, 0
        elif self.player_check(self.x + dx, self.y + dy, self.z):
            self.Send({
                "action":
                "system_message",
                "message":
                "You bumped into the other player, he hates ya now."
            })
            dx, dy = 0, 0
        elif monster_check(self.x + dx, self.y + dy, self.z):
            monster = monster_check(self.x + dx, self.y + dy, self.z)
            monster.fight_against(self)
            # MONSTER HIER
        elif get_items_at(self.x + dx, self.y + dy, self.z):
            items = get_items_at(self.x + dx, self.y + dy, self.z)
            for item in items:
                item.pickup(self.char)
                chars = ["a", "e", "i", "o", "u"]
                for char in chars:
                    if item.name.lower().startswith(char):
                        self.Send({
                            "action":
                            "system_message",
                            "message":
                            "You found an: {}.".format(item.name)
                        })
                        break
                else:
                    self.Send({
                        "action": "system_message",
                        "message": "You found a: {}.".format(item.name)
                    })
        elif staircase_check(self.x + dx, self.y + dy, self.z):
            if ClientChannel.dungeon[self.z][self.y + dy][self.x + dx] == "/":
                print("Player \"" + self.player_name +
                      "\" walked a staircase up, is now at z: " + str(self.z) +
                      ".")
                self.Send({
                    "action": "system_message",
                    "message": "You walked the stair up"
                })
                self.z += 1
            elif ClientChannel.dungeon[self.z][self.y + dy][self.x +
                                                            dx] == "\\":
                print("Player \"" + self.player_name +
                      "\" walked a staircase down, is now at z: " +
                      str(self.z) + ".")
                self.Send({
                    "action": "system_message",
                    "message": "You walked the stair down"
                })
                self.z -= 1
            self.update_dungeon_for_players()
        self.x += dx
        self.y += dy

        print(
            "[Server] Player \"" + self.player_name +
            "\" got new coordinates. dx: " + str(dx) + ", dy: " + str(dy),
            "x: " + str(self.x) + ", y: " + str(self.y) + ", z: " +
            str(self.z))
        self._server.player_moved(self.id)
Ejemplo n.º 10
0
my_logger.addHandler(handler)

try:
    config = Config().get()

    engine = create_engine(config['sql_connection_string'])
    Session = sessionmaker(bind=engine)

    session = Session()

    api_key = config['google_api_key']

    forward_route_id = 1
    backward_route_id = 2

    forward_directions = Directions(session, api_key, forward_route_id)
    backward_directions = Directions(session, api_key, backward_route_id)

    my_logger.addHandler(handler)

    my_logger.info('Forward Seconds: ' + str(forward_directions.get_seconds()))
    my_logger.info('Backward Seconds: ' +
                   str(backward_directions.get_seconds()))

    my_logger.debug('Inserting data')

    session.add_all([
        Transit(route_id=forward_route_id,
                duration=forward_directions.get_seconds(),
                all_data=forward_directions.get_all_data()),
        Transit(route_id=backward_route_id,
Ejemplo n.º 11
0
 def get_random_neighbors(self, weight):
     return [(self.get_neighbor(i), i) for i in Directions.get_all_random(weight) if self.get_neighbor(i)]
Ejemplo n.º 12
0
 def __init__(self, x, y, grid):
     self.coordinates = x, y
     self.open = False
     self.active = False
     self.grid = grid
     self.walls = dict(zip(Directions.get_all(), [True for _ in Directions.get_all()]))
Ejemplo n.º 13
0
 def get_neighbors(self):
     return [(self.get_neighbor(i), i) for i in Directions.get_all() if self.get_neighbor(i)]
Ejemplo n.º 14
0
def test_easter_bunny(input, part2, result):
    directions = Directions(input)
    assert (directions.easter_bunny_hq(part2) == result)
Ejemplo n.º 15
0
def gen_script_for_each_xml_local(root_path,
                                  robot_xml_path,
                                  xml_name,
                                  built_binary_path,
                                  gen_scripts_path,
                                  result_path,
                                  model_path=None):
    robot_ori_quat = [1, 0, 0, 0]
    # robot_ori_tran = [1000, 0, 0]
    '''
        Randomly generating directions. when res=5, 98 directions are generated.
    '''
    dirs = Directions(res=2, dim=3).dirs
    robot_ori_trans = np.array(dirs, dtype=np.float64) * 1000
    '''
    '''
    elements = re.split('/', xml_name)
    sub_path = gen_scripts_path + '/' + elements[len(elements) - 1]
    mkdir(root_path + '/' + sub_path)
    if os.path.exists(sub_path + '/run.sh'):
        print('Detected Script: ' + root_path + '/' + sub_path + '/run.sh')
    else:
        print('Generating Script: ' + root_path + '/' + sub_path + '/run.sh')

        f = open(root_path + '/' + sub_path + '/run.sh', 'w')

        script = ''
        sub_xmlFile = []
        for i in range(robot_ori_trans.shape[0]):
            robot_ori_tran = robot_ori_trans[i, :]
            for j in range(2):
                for k in range(2):
                    for m in range(2):
                        if os.path.exists(root_path + '/' + sub_path + '/' +
                                          elements[len(elements) - 1] + "_" +
                                          str(i) + '_' + str(j) + '_' +
                                          str(k) + '_' + str(m)):
                            print('Detected Filefold: ' + root_path + '/' +
                                  sub_path + '/' +
                                  elements[len(elements) - 1] + '_' + str(j) +
                                  '_' + str(k) + '_' + str(m))
                        else:
                            sub_file = root_path + '/' + sub_path + '/' + elements[
                                len(elements) - 1] + "_" + str(i) + '_' + str(
                                    j) + '_' + str(k) + '_' + str(m)
                            sub_xmlFile.append(sub_file)
                            mkdir(sub_file)

                        robot_zrot = math.pi / (j + 1)  # radians
                        robot_yrot = math.pi / (k + 1)
                        robot_xrot = math.pi / (m + 1)
                        # print(robot_xrot, robot_yrot, robot_zrot)
                        # print('--------------------------------')
                        robot_R = transforms3d.taitbryan.euler2mat(
                            robot_zrot, robot_yrot, robot_xrot)  # rotations
                        robot_coor_T_R = np.matmul(robot_R, robot_ori_tran)
                        robot_quat2mat = transforms3d.quaternions.quat2mat(
                            robot_ori_quat)
                        robot_quat2mat_R = np.matmul(robot_R, robot_quat2mat)
                        robot_mat2quat = transforms3d.quaternions.mat2quat(
                            robot_quat2mat_R)

                        # Note: random initial human hand generated by EBM (20dof)
                        script += root_path + '/' + built_binary_path + ' '
                        script += '--bodyFile=' + xml_name + ' '
                        script += '--bodyRot=1,0,0,0 '
                        script += '--bodyTrans=0,0,0 '
                        script += '--robotFile=' + root_path + '/' + robot_xml_path + ' '
                        script += '--robotRot=' + str(
                            robot_mat2quat[0]) + ',' + str(
                                robot_mat2quat[1]) + ',' + str(
                                    robot_mat2quat[2]) + ',' + str(
                                        robot_mat2quat[3]) + ' '
                        script += '--robotTrans=' + str(
                            robot_coor_T_R[0]) + ',' + str(
                                robot_coor_T_R[1]) + ',' + str(
                                    robot_coor_T_R[2]) + ' '
                        # Run a interface to compute a initial human hand by EBM
                        script += dof_ebm()
                        #script += '--robotDOF=0,0,0,0 '
                        script += '--resultFile=' + root_path + '/' + sub_path + '/' + elements[
                            len(elements) - 1] + "_" + str(i) + '_' + str(
                                j) + '_' + str(k) + '_' + str(m) + '/\n'

                        script += '--modelPath=' + model_path
                        script += 'cp -r ' + root_path + '/' + sub_path + '/' + elements[
                            len(elements) - 1] + "_" + str(i) + '_' + str(
                                j) + '_' + str(k) + '_' + str(m) + ' '
                        script += root_path + '/' + result_path + '\n\n'

        f.write(script)
        f.close()

    #Permission
    os.chmod(root_path + '/' + sub_path + '/run.sh',
             stat.S_IRWXO + stat.S_IRWXG + stat.S_IRWXU)

    #Generate grasp candidate for each initial human hand
    #print('cd ' + root_path + '/' + sub_path + '; ./run.sh;')
    # subprocess_cmd('cd ' + root_path + '/' + sub_path + '; ./run.sh;')
    os.system(root_path + '/' + sub_path + '/run.sh')