コード例 #1
0
def read_graph(graph_file):
    # read graph from file
    graph = Graph()
    original_graph = Graph()
    with open(graph_file, 'r') as h:
        for line in h:
            line = line.strip()
            if not line:
                continue

            line_type, line = line[:2].strip(), line[2:]

            # process new node or new edge
            if line_type == 'n':
                node_id, values = line.split(' ', 1)
                if node_id not in graph:
                    graph.add_node(node_id, Vector(*list(map(float, values.split()))))
                    original_graph.add_node(node_id, Vector(*list(map(float, values.split()))))
            elif line_type == 'e':
                node_id_1, node_id_2 = line.split()

                node_1, node_2 = graph[node_id_1], graph[node_id_2]
                node_1.add_neighbor(node_2)
                node_2.add_neighbor(node_1)

                node_1, node_2 = original_graph[node_id_1], original_graph[node_id_2]
                node_1.add_neighbor(node_2)
                node_2.add_neighbor(node_1)

    return graph, original_graph
コード例 #2
0
def update_ball(state,dt):
    # TODO: add better surface normal selection and bounce conditions
    normal = Vector(0,0,1)
    point = Vector(state.ball.location.x,state.ball.location.y,0)
    dist_perp = (state.ball.location-point).scalar_project(normal)
    vel_perp = state.ball.velocity.scalar_project(normal)
    if dist_perp <= R and vel_perp < 0:
        # wall bounce
        vel_perp = normal*vel_perp
        vel_tang = state.ball.velocity-vel_perp
        vel_surf = vel_tang+copy(normal).cross(state.ball.angular_velocity)*R
        Jperp = -vel_perp*(1+CR)
        Jtang = vel_surf if vel_surf.mag()==0 else -vel_surf*min(1,Y*vel_perp.mag()/vel_surf.mag())*mu
        state.ball.velocity += Jperp+Jtang
        state.ball.angular_velocity += Jtang.cross(normal)*R
    else:
        # gravity
        state.ball.velocity.z -= g*dt
    # get car collisions
    for i in state.drones:
        car_ball_collision(state.ball,state.drones[i])
    for i in state.enemies:
        car_ball_collision(state.ball,state.enemies[i])
    # update states
    state.ball.velocity = state.ball.velocity.mag_normalize(VB_MAX)
    state.ball.angular_velocity = state.ball.angular_velocity.mag_normalize(OMEGAB_MAX)
    state.ball.location += state.ball.velocity*dt
コード例 #3
0
ファイル: main.py プロジェクト: Maerig/advent_of_code_2017
def navigate(diagram):
    x = diagram[0].index('|')
    current = Vector(x, 0)
    prev = Vector(x, -1)

    while current:
        yield current
        prev, current = current, get_next_pos(diagram, current, prev)
コード例 #4
0
def test_setters():
    """vector property setters"""
    v = Vector(1,2,3)
    v.x = 4
    assert v.x==4 and v.y==2 and v.z==3
    v.y = 5
    assert v.x==4 and v.y==5 and v.z==3
    v.z = 6
    assert v.x==4 and v.y==5 and v.z==6
コード例 #5
0
def test_init():
    """vector initialization"""
    # scalar initialization
    v = Vector(1,2,3)
    assert v.x==1 and v.roll==1
    assert v.y==2 and v.pitch==2
    assert v.z==3 and v.yaw==3
    # vector initialization
    v = Vector([1,2,3])
    assert v.x==1 and v.roll==1
    assert v.y==2 and v.pitch==2
    assert v.z==3 and v.yaw==3
コード例 #6
0
def test_magnitude():
    """vector magnitude"""
    assert Vector(0,0,0).mag()==0
    assert Vector(1,0,0).mag()==1
    assert Vector(0,1,0).mag()==1
    assert Vector(0,0,1).mag()==1
    assert Vector(1,0,1).mag()==2**0.5
    assert Vector(1,1,0).mag()==2**0.5
    assert Vector(0,1,1).mag()==2**0.5
    assert Vector(1,1,1).mag()==3**0.5
    assert Vector(1,2,3).mag()==14**0.5
コード例 #7
0
def vertex_cover_cost(first_node, second_node):
    return {
        'headers': [first_node, second_node],
        0: ResultSet((Vector(*(inf for _ in range(len(first_node.cost)))), )),
        1: ResultSet((first_node.cost, )),
        2: ResultSet((second_node.cost, )),
        3: ResultSet((first_node.cost + second_node.cost, )),
    }
コード例 #8
0
def test_to_list():
    """vector to list"""
    # list generation
    assert list(Vector(1,2,3))==[1,2,3]
    assert list(Vector(-1,0,1))==[-1,0,1]
    assert list(Vector(-1,-2,-3))==[-1,-2,-3]
    # tuple generation
    x,y,z = Vector(1,2,3)
    assert x==1 and y==2 and z==3
    assert tuple(Vector(1,2,3))==(1,2,3)
    assert tuple(Vector(-1,0,1))==(-1,0,1)
    assert tuple(Vector(-1,-2,-3))==(-1,-2,-3)
    x1,x2,x3,x4,x5,x6 = (*Vector(1,2,3),*Vector(4,5,6))
    assert x1==1 and x2==2 and x3==3 and x4==4 and x5==5 and x6==6
コード例 #9
0
    def move(self, gamestate):

        current_vector = gamestate.me.current_direction
        if current_vector != noop:
            return current_vector

        head = gamestate.me.head
        l_wall = Vector(0, head.y)
        r_wall = Vector(gamestate.board_width - 1, head.y)
        t_wall = Vector(head.x, 0)
        b_wall = Vector(head.x, gamestate.board_width - 1)
        farthest = head.farthest([l_wall, r_wall, t_wall, b_wall])
        return {
            l_wall: left,
            r_wall: right,
            t_wall: up,
            b_wall: down,
        }.get(farthest, up)
コード例 #10
0
def part_2(cmds):
    ship = Vector(0, 0)
    waypoint = Vector(10, 1)
    for dir, steps in cmds:

        if dir == "F":
            ship += waypoint * steps

        elif dir in NESW_VEC:
            waypoint += NESW_VEC[dir] * steps
        elif dir == "R":
            waypoint = waypoint.rotate_degree(steps)
        elif dir == "L":
            waypoint = waypoint.rotate_degree(-steps)
        else:
            raise Exception(f"Unknown instruction {(dir, steps)}")

    return abs(ship.x) + abs(ship.y)
コード例 #11
0
ファイル: Player.py プロジェクト: davidovski/platformer-game
    def __init__(self, asset_manager: AssetManager, game):
        self.game = game
        self.asset_manager = asset_manager
        self.rect = pygame.Rect((64, 0, 28, 63))
        GameObject.__init__(self, rect=self.rect, game=game)
        self.type = "player"
        sheet = spritesheet("playerwalking.png", asset_manager)
        self.images_walking_right = [
            sheet.image_at((0, 0, 32, 64)),
            sheet.image_at((32, 0, 32, 64)),
            sheet.image_at((64, 0, 32, 64)),
            sheet.image_at((96, 0, 32, 64))
        ]

        self.images_standing_right = [sheet.image_at((0, 64, 32, 64))]
        self.images_ducking_right = [sheet.image_at((32, 64, 32, 32))]
        self.images_sliding_right = [sheet.image_at((0, 64, 32, 64))]

        self.images_walking_left = [
            pygame.transform.flip(sheet.image_at((0, 0, 32, 64)), True, False),
            pygame.transform.flip(sheet.image_at((32, 0, 32, 64)), True,
                                  False),
            pygame.transform.flip(sheet.image_at((64, 0, 32, 64)), True,
                                  False),
            pygame.transform.flip(sheet.image_at((96, 0, 32, 64)), True, False)
        ]

        self.images_standing_left = [
            pygame.transform.flip(sheet.image_at((0, 64, 32, 64)), True, False)
        ]
        self.images_ducking_left = [
            pygame.transform.flip(sheet.image_at((32, 64, 32, 32)), True,
                                  False)
        ]
        self.images_sliding_left = [
            pygame.transform.flip(sheet.image_at((0, 64, 32, 64)), True, False)
        ]

        self.speed = 4
        self.on_ground = False
        self.velocity = Vector(0, 0)

        self.jumps = 0
        self.max_jumps = 999
        self.ducked = False

        self.state = PlayerState.STANDING
        self.looking = Looking.MIDDLE

        self.sliding = False

        self.gun = Gun()

        self.crosshair_image = asset_manager.get_asset("crosshair.png")

        self.mp = [0, 0]
コード例 #12
0
ファイル: hive.py プロジェクト: TrumanHeberle/OptBot
    def choose_action(self, state: State) -> List[Dict[int, Action]]:
        """Returns a dictionary of predicted enemy and bot actions."""
        # select worst possible action per enemy
        enemy_actions = {}
        for i in self.enemy_indices:
            enemy_actions[i] = C.NOTHING
        # select best possible action per drone
        drone_actions = {}
        for i in self.drone_indices:
            # instantiate decision tree
            def brancher(state, action):
                # predict next state for a drone assuming remaining drone inputs remain constant
                for j in self.drone_indices:
                    state.drones[
                        j].current_action = action if i == j else state.drones[
                            j].last_action
                for j in self.enemy_indices:
                    state.enemies[j].current_action = state.enemies[
                        j].last_action
                return self.predictor.predict(state)

            dtree = DecisionTree(state, C.ACTIONS, brancher, self.scorer.score)
            # determine best case action
            dtree.branch()
            for _ in range(C.TIMESTEPS - 1):
                dtree.prune(C.NUM_RETAIN)
                if dtree.is_determined():
                    # break from loop if all the best paths stem from a single action
                    # (saves computation time)
                    dtree.prune(1)
                dtree.branch()
            # set best case action
            drone_actions[i] = dtree.ideal_key()
        # render prediction
        self.renderer.begin_rendering()
        last = state
        for s in dtree.ideal_path():
            bll = last.ball.location - 2
            bls = s.ball.location - 2
            cll = last.drones[0].location - 2
            cls = s.drones[0].location - 2
            dir = (s.drones[0].location -
                   2) + Vector(1, 0, 0).rpy(s.drones[0].rotation) * 50
            self.renderer.draw_line_3d(tuple(bll), tuple(bls),
                                       self.renderer.white())
            self.renderer.draw_rect_3d(tuple(bls), 4, 4, True,
                                       self.renderer.white())
            self.renderer.draw_line_3d(tuple(cll), tuple(cls),
                                       self.renderer.white())
            self.renderer.draw_rect_3d(tuple(cls), 4, 4, True,
                                       self.renderer.white())
            self.renderer.draw_line_3d(tuple(cls), tuple(dir),
                                       self.renderer.red())
            last = s
        self.renderer.end_rendering()
        return drone_actions, enemy_actions
コード例 #13
0
 def create_cost_table(self, headers):
     cost_table = {'headers': list(headers)}
     for i in range(2**len(headers)):
         # sum costs of chosen nodes
         total_cost = Vector.add_vectors(
             *(node.cost for count, node in enumerate(headers)
               if i & (1 << count)),
             dimensions=self.dimensions)
         cost_table[i] = ResultSet((total_cost, ))
     return cost_table
コード例 #14
0
ファイル: PIDcontroller.py プロジェクト: duncanwedig/PIDsim
 def draw(self, screen):
     pointx = pygame_utils.scale_point(self.current_time, 5, 0)
     pointy = pygame_utils.scale_point(self.error, -5, 500)
     # point = pygame_utils.scale_points((self.current_time-100, -self.error), 5, 500)
     print(pointx, pointy)
     self.points.append(Vector((pointx, pointy), vectortype.XY))
     xy = self.points[-1].xy
     x = int(xy[0])
     y = int(xy[1])
     pygame.draw.circle(screen, (255, 0, 0), (x, y), 2)
コード例 #15
0
def car_ball_collision(ball,car):
    # TODO: make collision condition better
    if (car.location-ball.location).mag() > R: return
    f = Vector(1,0,0).rpy(car.rotation)
    n = ball.location-car.location
    n.z *= 0.35
    n = (n-f*0.35*(n).dot(f)).normalize()
    vmag = (ball.velocity-car.velocity).mag()
    Jcol = n*vmag*car_ball_scale(vmag)
    ball.velocity += Jcol
コード例 #16
0
ファイル: main.py プロジェクト: Maerig/advent_of_code_2017
def read_input():
    return [
        Particle(*[
            Vector(*(
                int(n)
                for n in group.split(',')
            ))
            for group in PARTICLE_REGEX.search(line).groups()
        ])
        for line in open('input.txt')
    ]
コード例 #17
0
ファイル: main.py プロジェクト: Maerig/advent_of_code_2017
def get_neighbours(diagram, x, y):
    return [
        Vector(i, j)
        for i, j in [
            (x - 1, y),
            (x + 1, y),
            (x, y - 1),
            (x, y + 1)
        ]
        if get_segment(diagram, i, j)
    ]
コード例 #18
0
def test_copy():
    """vector deep copying"""
    v = Vector(1,2,3)
    vcopy = copy(v)
    assert v.x==vcopy.x
    assert v.y==vcopy.y
    assert v.z==vcopy.z
    vcopy.x = 4
    vcopy.y = 5
    vcopy.z = 6
    assert v.x != vcopy.x
    assert v.y != vcopy.y
    assert v.z != vcopy.z
コード例 #19
0
def part_1(cmds):
    ship = Vector(0, 0)
    face = "E"
    for dir, steps in cmds:

        if dir == "F":
            dir = face

        if dir in NESW_VEC:
            ship += NESW_VEC[dir] * steps
        elif dir == "R":
            for _ in range(steps // 90):
                face = TURN_RIGHT[face]
        elif dir == "L":
            for _ in range(steps // 90):
                face = TURN_LEFT[face]
        else:
            raise Exception(f"Unknown instruction {(dir, steps)}")

    return abs(ship.x) + abs(ship.y)
コード例 #20
0
    def _compute_cost_full(self, assignment):
        zipped = list(zip(assignment, self.original_order))
        total_cost = None
        nodes_included = {node for value, node in zipped if value}

        for count, (first_value, first_node) in enumerate(zipped):

            # check if any hard constraints violated
            for second_value, second_node in zipped[count:]:
                if not first_value and not second_value:
                    if second_node in first_node.neighbors:
                        return ResultSet(
                            (Vector(*(inf for _ in range(self.dimensions)),
                                    includes=nodes_included), )), None

            # add total cost from cost functions
            if first_value:
                total_cost = first_node.cost if total_cost is None else \
                    total_cost + first_node.cost

        return ResultSet((total_cost, )), None
コード例 #21
0
 def score(self, state):
     s = 0
     # reward for drones being closer
     for i in state.drones:
         car = state.drones[i]
         d1 = state.ball.location - car.location
         d2 = DRONE_NET - state.ball.location
         f = Vector(1, 0, 0).rpy(car.rotation)
         a = f.angle(d1)
         s -= (d1.mag() + d2.mag()) * a / sin(a)
     # reward for enemies being farther
     for i in state.enemies:
         car = state.enemies[i]
         d1 = state.ball.location - car.location
         d2 = ENEMY_NET - state.ball.location
         f = Vector(1, 0, 0).rpy(car.rotation)
         a = f.angle(d1)
         s += (d1.mag() + d2.mag()) * a / sin(a)
     # reward ball being farther from drone net
     s += (state.ball.location - ENEMY_NET).mag()
     # reward ball being closer to enemy net
     s -= (state.ball.location - DRONE_NET).mag()
     return s
コード例 #22
0
def test_ball_state():
    """ball state manipulation"""
    n_bs = 9
    # ball state setting
    bs = BallState([0, 1, 2, 3, 4, 5, 6, 7, 8])
    assert len(bs) == n_bs
    assert bs.location == Vector(0, 1, 2)
    assert bs.velocity == Vector(3, 4, 5)
    assert bs.angular_velocity == Vector(6, 7, 8)
    # single parameter setting
    bs.location = Vector(9, 10, 11)
    assert len(bs) == n_bs
    assert bs.location == Vector(9, 10, 11)
    assert bs.velocity == Vector(3, 4, 5)
    assert bs.angular_velocity == Vector(6, 7, 8)
    bs.velocity = Vector(12, 13, 14)
    assert len(bs) == n_bs
    assert bs.location == Vector(9, 10, 11)
    assert bs.velocity == Vector(12, 13, 14)
    assert bs.angular_velocity == Vector(6, 7, 8)
    bs.angular_velocity = Vector(15, 16, 17)
    assert len(bs) == n_bs
    assert bs.location == Vector(9, 10, 11)
    assert bs.velocity == Vector(12, 13, 14)
    assert bs.angular_velocity == Vector(15, 16, 17)
    # multiple parameter setting
    bs.location = Vector(-1, -2, -3)
    bs.velocity = Vector(-4, -5, -6)
    bs.angular_velocity = Vector(-7, -8, -9)
    assert len(bs) == n_bs
    assert bs.location == Vector(-1, -2, -3)
    assert bs.velocity == Vector(-4, -5, -6)
    assert bs.angular_velocity == Vector(-7, -8, -9)
    # inplace parameter setting
    bs.location += 2
    bs.velocity += 2
    bs.angular_velocity += 2
    assert len(bs) == n_bs
    assert bs.location == Vector(1, 0, -1)
    assert bs.velocity == Vector(-2, -3, -4)
    assert bs.angular_velocity == Vector(-5, -6, -7)
コード例 #23
0
def test_equality():
    """vector equality"""
    # exact equality
    v1 = Vector(1,2,3)
    v2 = Vector(1,2,3)
    assert v1==v2
    v2.z = 1
    assert v1!=v2
    v2.z = 3
    v2.y = 3
    assert v1!=v2
    v2.y = 2
    v2.x = 2
    assert v1!=v2
    v2.x = 1
    assert v1==v2
    # approximate equality
    v1 = Vector(1,2,3)
    v2 = Vector(1,2,3)
    assert v1.approx(v2)
    v2.z = 1
    assert not v1.approx(v2)
    v2.z = 3
    v2.y = 3
    assert not v1.approx(v2)
    v2.y = 2
    v2.x = 2
    assert not v1.approx(v2)
    v2.x = 1
    assert v1.approx(v2)
    # tolerance checking in all directions
    assert Vector(0,0,0).approx(Vector(0.000001,0,0),0.00001)
    assert Vector(0,0,0).approx(Vector(0,0.000001,0),0.00001)
    assert Vector(0,0,0).approx(Vector(0,0,0.000001),0.00001)
    # tolerance checking over multiple tolerances
    assert Vector(0,0,0).approx(Vector(0.000001,0,0),0.01)
    assert Vector(0,0,0).approx(Vector(0.000001,0,0),0.001)
    assert Vector(0,0,0).approx(Vector(0.000001,0,0),0.0001)
    assert Vector(0,0,0).approx(Vector(0.000001,0,0),0.00001)
    assert not Vector(0,0,0).approx(Vector(0.000001,0,0),0.000001)
    assert not Vector(0,0,0).approx(Vector(0.000001,0,0),0.0000001)
    assert not Vector(0,0,0).approx(Vector(0.000001,0,0),0.00000001)
コード例 #24
0
def test_project():
    """vector projection"""
    zero = Vector(0,0,0)
    x = Vector(1,0,0)
    y = Vector(0,1,0)
    z = Vector(0,0,1)
    xy = Vector(1,1,0)
    xyz = Vector(1,1,1)
    v = Vector(10,11,12)
    # zero vector cases
    assert x.project(zero)==Vector(0,0,0)
    assert y.project(zero)==Vector(0,0,0)
    assert z.project(zero)==Vector(0,0,0)
    assert zero.project(x)==Vector(0,0,0)
    assert zero.project(y)==Vector(0,0,0)
    assert zero.project(z)==Vector(0,0,0)
    assert x.scalar_project(zero)==0
    assert y.scalar_project(zero)==0
    assert z.scalar_project(zero)==0
    assert zero.scalar_project(x)==0
    assert zero.scalar_project(y)==0
    assert zero.scalar_project(z)==0
    # orthonormal cases
    assert xy.project(x)==Vector(1,0,0)
    assert xy.project(y)==Vector(0,1,0)
    assert xy.project(z)==Vector(0,0,0)
    assert xyz.project(x)==Vector(1,0,0)
    assert xyz.project(y)==Vector(0,1,0)
    assert xyz.project(z)==Vector(0,0,1)
    assert xy.scalar_project(x)==1
    assert xy.scalar_project(y)==1
    assert xy.scalar_project(z)==0
    assert xyz.scalar_project(x)==1
    assert xyz.scalar_project(y)==1
    assert xyz.scalar_project(z)==1
    # general cases
    p = xyz.project(xy)
    assert p.approx(Vector(1,1,0),TOLERANCE)
    assert isclose(xyz.scalar_project(xy),2**0.5,abs_tol=TOLERANCE)
    assert v.project(xy).approx(Vector(10.5,10.5,0),TOLERANCE)
    assert isclose(v.scalar_project(xy),(2*(10.5**2))**0.5,abs_tol=TOLERANCE)
コード例 #25
0
ファイル: test_day12.py プロジェクト: eruvanos/2020_AOC
def test_rotation():
    vec = Vector(1, 2)

    assert Vector(2, -1) == vec.rotate_degree(90)
    assert Vector(-1, -2) == vec.rotate_degree(180)
    assert Vector(-2, 1) == vec.rotate_degree(-90)
コード例 #26
0
ファイル: directions.py プロジェクト: eruvanos/2020_AOC
from utils.vector import Vector

# Directions
NORTH = "N"
SOUTH = "S"
EAST = "E"
WEST = "W"
LEFT = "L"
RIGHT = "R"
FORWARD = "F"

# Vectors for NESW
NESW_VEC = {
    "E": Vector(1, 0),
    "W": Vector(-1, 0),
    "N": Vector(0, 1),
    "S": Vector(0, -1),
}

# Turn maps for NESW
TURN_LEFT = {
    "E": "N",
    "W": "S",
    "N": "W",
    "S": "E",
}
TURN_RIGHT = {
    "E": "S",
    "W": "N",
    "N": "E",
    "S": "W",
コード例 #27
0
def test_rotation():
    """vector rotation"""
    # zero rotation case
    assert Vector(0,0,0).rpy(Vector(0,0,0))==Vector(0,0,0)
    assert Vector(1,0,0).rpy(Vector(0,0,0))==Vector(1,0,0)
    assert Vector(0,1,0).rpy(Vector(0,0,0))==Vector(0,1,0)
    assert Vector(0,0,1).rpy(Vector(0,0,0))==Vector(0,0,1)
    assert Vector(1,1,1).rpy(Vector(0,0,0))==Vector(1,1,1)
    assert Vector(-1,-1,-1).rpy(Vector(0,0,0))==Vector(-1,-1,-1)
    # rotations about parallel axis
    assert Vector(1,0,0).rpy(Vector(pi/4,0,0))==Vector(1,0,0)
    assert Vector(0,1,0).rpy(Vector(0,pi/4,0))==Vector(0,1,0)
    assert Vector(0,0,1).rpy(Vector(0,0,pi/4))==Vector(0,0,1)
    # full rotations about any axis
    assert Vector(1,1,1).rpy(Vector(2*pi,0,0)).approx(Vector(1,1,1),TOLERANCE)
    assert Vector(1,1,1).rpy(Vector(0,2*pi,0)).approx(Vector(1,1,1),TOLERANCE)
    assert Vector(1,1,1).rpy(Vector(0,0,2*pi)).approx(Vector(1,1,1),TOLERANCE)
    # half rotations about any axis
    assert Vector(1,1,1).rpy(Vector(pi,0,0)).approx(Vector(1,-1,-1),TOLERANCE)
    assert Vector(1,1,1).rpy(Vector(0,pi,0)).approx(Vector(-1,1,-1),TOLERANCE)
    assert Vector(1,1,1).rpy(Vector(0,0,pi)).approx(Vector(-1,-1,1),TOLERANCE)
    # rotations about orthogonal axis
    assert Vector(1,0,0).rpy(Vector(0,pi/2,0)).approx(Vector(0,0,1))
    assert Vector(1,0,0).rpy(Vector(0,0,pi/2)).approx(Vector(0,1,0))
    assert Vector(0,1,0).rpy(Vector(pi/2,0,0)).approx(Vector(0,0,-1))
    assert Vector(0,1,0).rpy(Vector(0,0,pi/2)).approx(Vector(-1,0,0))
    assert Vector(0,0,1).rpy(Vector(pi/2,0,0)).approx(Vector(0,1,0))
    assert Vector(0,0,1).rpy(Vector(0,pi/2,0)).approx(Vector(-1,0,0))
    # inverse rotations
    assert Vector(1,0,0).rpy(Vector(0,-pi/2,0)).approx(Vector(0,0,-1))
    assert Vector(1,0,0).rpy(Vector(0,0,-pi/2)).approx(Vector(0,-1,0))
    assert Vector(0,1,0).rpy(Vector(-pi/2,0,0)).approx(Vector(0,0,1))
    assert Vector(0,1,0).rpy(Vector(0,0,-pi/2)).approx(Vector(1,0,0))
    assert Vector(0,0,1).rpy(Vector(-pi/2,0,0)).approx(Vector(0,-1,0))
    assert Vector(0,0,1).rpy(Vector(0,-pi/2,0)).approx(Vector(1,0,0))
コード例 #28
0
def test_car_state():
    """car state manipulation"""
    n_cs = 30
    n_actions = 8
    # car state setting
    car_params = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
    last_action_params = [14, 15, 16, 17, 18, 19, 20, 21]
    current_action_params = [22, 23, 24, 25, 26, 27, 28, 29]
    cs = CarState(car_params + last_action_params + current_action_params)
    assert len(cs) == 30
    assert len(cs.last_action) == n_actions
    assert len(cs.current_action) == n_actions
    assert cs.location == Vector(0, 1, 2)
    assert cs.velocity == Vector(3, 4, 5)
    assert cs.rotation == Vector(6, 7, 8)
    assert cs.angular_velocity == Vector(9, 10, 11)
    assert cs.jumped == 12 and cs.double_jumped == 13
    assert all(cs.last_action == Action(last_action_params))
    assert all(cs.current_action == Action(current_action_params))
    # single parameter setting
    cs.location = Vector(-1, -2, -3)
    assert len(cs) == 30
    assert len(cs.last_action) == n_actions
    assert len(cs.current_action) == n_actions
    assert cs.location == Vector(-1, -2, -3)
    assert cs.velocity == Vector(3, 4, 5)
    assert cs.rotation == Vector(6, 7, 8)
    assert cs.angular_velocity == Vector(9, 10, 11)
    assert cs.jumped == 12 and cs.double_jumped == 13
    assert all(cs.last_action == Action(last_action_params))
    assert all(cs.current_action == Action(current_action_params))
    cs.velocity = Vector(-4, -5, -6)
    assert len(cs) == 30
    assert len(cs.last_action) == n_actions
    assert len(cs.current_action) == n_actions
    assert cs.location == Vector(-1, -2, -3)
    assert cs.velocity == Vector(-4, -5, -6)
    assert cs.rotation == Vector(6, 7, 8)
    assert cs.angular_velocity == Vector(9, 10, 11)
    assert cs.jumped == 12 and cs.double_jumped == 13
    assert all(cs.last_action == Action(last_action_params))
    assert all(cs.current_action == Action(current_action_params))
    cs.rotation = Vector(-7, -8, -9)
    assert len(cs) == 30
    assert len(cs.last_action) == n_actions
    assert len(cs.current_action) == n_actions
    assert cs.location == Vector(-1, -2, -3)
    assert cs.velocity == Vector(-4, -5, -6)
    assert cs.rotation == Vector(-7, -8, -9)
    assert cs.angular_velocity == Vector(9, 10, 11)
    assert cs.jumped == 12 and cs.double_jumped == 13
    assert all(cs.last_action == Action(last_action_params))
    assert all(cs.current_action == Action(current_action_params))
    cs.angular_velocity = Vector(-10, -11, -12)
    assert len(cs) == 30
    assert len(cs.last_action) == n_actions
    assert len(cs.current_action) == n_actions
    assert cs.location == Vector(-1, -2, -3)
    assert cs.velocity == Vector(-4, -5, -6)
    assert cs.rotation == Vector(-7, -8, -9)
    assert cs.angular_velocity == Vector(-10, -11, -12)
    assert cs.jumped == 12 and cs.double_jumped == 13
    assert all(cs.last_action == Action(last_action_params))
    assert all(cs.current_action == Action(current_action_params))
    cs.jumped = -13
    assert len(cs) == 30
    assert len(cs.last_action) == n_actions
    assert len(cs.current_action) == n_actions
    assert cs.location == Vector(-1, -2, -3)
    assert cs.velocity == Vector(-4, -5, -6)
    assert cs.rotation == Vector(-7, -8, -9)
    assert cs.angular_velocity == Vector(-10, -11, -12)
    assert cs.jumped == -13 and cs.double_jumped == 13
    assert all(cs.last_action == Action(last_action_params))
    assert all(cs.current_action == Action(current_action_params))
    cs.double_jumped = -14
    assert len(cs) == 30
    assert len(cs.last_action) == n_actions
    assert len(cs.current_action) == n_actions
    assert cs.location == Vector(-1, -2, -3)
    assert cs.velocity == Vector(-4, -5, -6)
    assert cs.rotation == Vector(-7, -8, -9)
    assert cs.angular_velocity == Vector(-10, -11, -12)
    assert cs.jumped == -13 and cs.double_jumped == -14
    assert all(cs.last_action == Action(last_action_params))
    assert all(cs.current_action == Action(current_action_params))
    last_action_params = [-15, -16, -17, -18, -19, -20, -21, -22]
    cs.last_action = Action(last_action_params)
    assert len(cs) == 30
    assert len(cs.last_action) == n_actions
    assert len(cs.current_action) == n_actions
    assert cs.location == Vector(-1, -2, -3)
    assert cs.velocity == Vector(-4, -5, -6)
    assert cs.rotation == Vector(-7, -8, -9)
    assert cs.angular_velocity == Vector(-10, -11, -12)
    assert cs.jumped == -13 and cs.double_jumped == -14
    assert all(cs.last_action == Action(last_action_params))
    assert all(cs.current_action == Action(current_action_params))
    current_action_params = [-23, -24, -25, -26, -27, -28, -29, -30]
    cs.current_action = Action(current_action_params)
    assert len(cs) == 30
    assert len(cs.last_action) == n_actions
    assert len(cs.current_action) == n_actions
    assert cs.location == Vector(-1, -2, -3)
    assert cs.velocity == Vector(-4, -5, -6)
    assert cs.rotation == Vector(-7, -8, -9)
    assert cs.angular_velocity == Vector(-10, -11, -12)
    assert cs.jumped == -13 and cs.double_jumped == -14
    assert all(cs.last_action == Action(last_action_params))
    assert all(cs.current_action == Action(current_action_params))
    # multiple parameter setting
    last_action_params = [15, 16, 17, 18, 19, 20, 21, 22]
    current_action_params = [23, 24, 25, 26, 27, 28, 29, 30]
    cs.location = Vector(1, 2, 3)
    cs.velocity = Vector(4, 5, 6)
    cs.rotation = Vector(7, 8, 9)
    cs.angular_velocity = Vector(10, 11, 12)
    cs.jumped = 13
    cs.double_jumped = 14
    cs.last_action = Action(last_action_params)
    cs.current_action = Action(current_action_params)
    assert len(cs) == 30
    assert len(cs.last_action) == n_actions
    assert len(cs.current_action) == n_actions
    assert cs.location == Vector(1, 2, 3)
    assert cs.velocity == Vector(4, 5, 6)
    assert cs.rotation == Vector(7, 8, 9)
    assert cs.angular_velocity == Vector(10, 11, 12)
    assert cs.jumped == 13 and cs.double_jumped == 14
    assert all(cs.last_action == Action(last_action_params))
    assert all(cs.current_action == Action(current_action_params))
コード例 #29
0
def test_example():
    assert Grid().walk_and_flip("esew").tiles == {Vector(1, -1)}
    assert Grid().walk_and_flip("nwwswee").tiles == {Vector(0, 0)}
コード例 #30
0
def test_to_string():
    """vector to string"""
    v = Vector(1,2,3)
    assert str(v)==f"({v.x},{v.y},{v.z})"
    assert repr(v)==str(v)