Exemplo n.º 1
0
 def init_moves(self):
     self._moves = [
         PeaceMove(self, self.dir * Vector(1, 0)),
         CaptureMove(self, self.dir * Vector(1, 1)),
         CaptureMove(self, self.dir * Vector(1, -1)),
         FirstMove(self, self.dir * Vector(1, 0), steps=2)
     ]
Exemplo n.º 2
0
def process_cand_inner(w, xi, n, rangebits):
    with open('./debug.txt', 'a') as f:
        for item in xi:
            f.write(str(item) + '\n')
    start = time()
    w_vec = Vector(w)
    xi_vec = Vector(xi)
    value = xi_vec.inner_product(w_vec)

    # rp = run_test_rangeproof(value, rangebits)
    print("Starting range proof prover: Generating proof")
    prf, negetive, rp = range_prover(value, rangebits)
    V = rp.V
    gamma = rp.gamma
    print("Lenght of Range Proof is :", len(prf))
    #with open('./result.txt', 'a') as f:
    #    f.write("Lenght of Range Proof is : " + str(len(prf)) + '\n')
    print("Starting Inner Product proof generation: Generating proof")
    prf2 = inner_product_prover(w, xi, n, V, gamma)
    final_pc, pc2, a, b, L, R, comm1 = prf2
    len2 = len(a) + len(b) + len(L) * len(L[0]) + len(R) * len(R[0]) + len(
        comm1) + len(final_pc) + len(pc2) + len(final_pc) + len(pc2)
    print("Generated Inner Product proof: len " + str(len2))
    #with open('./result.txt', 'a') as f:
    #    f.write("Generated Inner Product proof: len " + str(len2) + '\n')
    print("\n\n")
    print("Proof Generation complete: It's total length is " +
          str(len(prf) + len2))
    range_verifier(prf, negetive, V, rangebits)

    end = time()
    print("Proof Time is : ", end - start)
    return inner_product_verifier(n, V, prf2)
Exemplo n.º 3
0
def matrix_moves(figure, squares, Matrices):
    result = []
    pos = figure.pos
    try:
        size = Vector(len(squares), len(squares[0]))
    except:
        size = Vector(8, 8)
    mag = int(size.dist() + 1)
    for M in Matrices:
        for d in range(1, mag):
            added = pos.add(Vector(M[0] * d, M[1] * d))
            if (not added.in_ranges([0, size.x], [0, size.y])
                    or squares[added.x][added.y] == figure.color
                ):  #out of ranges or hit a fig. of the same color
                break
            if (added.in_ranges(
                [0, size.x],
                [0, size.y])):  #x and y in ranges of the gamespace
                result += [
                    Move(figure, pos, pos.add(Vector(M[0] * d, M[1] * d)))
                ]
            if (squares[added.x][added.y] !=
                    -1):  #out of ranges or hit a fig. of a different color
                break
    return result
Exemplo n.º 4
0
class PlatformerSettings:
    BG_COLOR = Color('black')
    PPU = 100
    BLOB_SIZE = 1
    PLATFORM_HEIGHT = 0.2
    PLATFORM_COLOR = Color('grey')
    GRAVITY = Vector(0, 5)
    RUN_SPEED = 2
    JUMP_SPEED = 3
    SOUND_RADIUS = 2
    SCROLL_MARGIN = 2
    JUMP_TIME = 0.5
    LEFT_KEYS = {pygame.K_LEFT, pygame.K_a}
    RIGHT_KEYS = {pygame.K_RIGHT, pygame.K_d}
    JUMP_KEYS = {pygame.K_UP, pygame.K_w, pygame.K_SPACE}
    TEXT_BGCOLOR = Color('black')
    TEXT_STYLE = {
        "text": {
            "margin": Vector(10, 5),
        },
        "paragraph": {
            "spacing": 10,
        },
        "font": {
            "family": 'Monospace',
            "size": 24,
            "color": Color('white'),
        }
    }
    OVERLAY_COLOR = Color(255, 255, 255, 127)
Exemplo n.º 5
0
def solve2():
    with open('./mace.json') as f:
        mace = json.load(f)
    mace = {Vector(x, y) for x, y in mace}

    graph = SetGraph(mace)

    queue = PriorityQueue()
    queue.put((0, Vector(16, 16)))

    max_distance = 0
    visited = set()
    while not queue.empty():
        distance, pos = queue.get()
        max_distance = max(max_distance, distance)

        visited.add(Vector(*pos))

        for n in graph.neighbors(pos):
            if n not in visited:
                queue.put((distance + 1, n))

    print(max_distance)

    canvas = ThisCanvas()


    for vec in mace:
        canvas.set(vec, 0)
    for vec in visited:
        canvas.set(vec, 2)

    arcade.run()
Exemplo n.º 6
0
 def getSafeZones(self):
     zones = []
     zones.append(SafeZone(Vector(.25, .25), .1))
     zones.append(SafeZone(Vector(.25, .75), .1))
     zones.append(SafeZone(Vector(.75, .25), .1))
     zones.append(SafeZone(Vector(.75, .75), .1))
     return zones
Exemplo n.º 7
0
 def sees(self, o):
     points = get_line_points(Vector(self.x, self.y), Vector(o.x, o.y))
     for point in points:
         # TODO access tiles, not grid
         if self.zone._grid[point.y][point.x] == '#':
             return False
     return True
Exemplo n.º 8
0
    def get_line_points(point_a: Vector, point_b: Vector):
        points = []
        grid = [list(['.']*WIDTH) for _ in range(HEIGHT)]
        
        point_b.x = min(WIDTH-3, max(0, point_b.x))
        point_b.y = min(HEIGHT-3, max(0, point_b.y))

        x1, y1 = point_a.x, point_a.x
        x2, y2 = point_b.x, point_b.y

        grid[y1][x1] = 'A'
        grid[y2][x2] = 'B'

        if y1 == y2: # horizontal line
            for x in range(min(x1, x2), max(x1, x2)):
                grid[y1][x] = '>'
                points.append(Vector(x, y1))
            print()
        elif x1 == x2: # vertical line
            for y in range(min(y1, y2), max(y1, y2)):
                grid[y][x1] = '^'
                points.append(Vector(x1, y))
            print()
        else:
            slope = (y2 - y1) / (x2 - x1)
            s = sign(slope)
            b = int(y2 - slope*x2)
            if abs(slope) < 1: # predominantly horizontal
                for x in range(min(x1, x2), max(x1, x2)):
                    y_curr = slope*x + b
                    y_next = slope*(x+s) + b
                    hyp = math.hypot(1, y_next-y_curr)
                    if x == 9:
                        print(y_curr, y_next, hyp)
                    if hyp > 1:
                        grid[int(y_curr)][x] = '#'
                        points.append(Vector(x, int(y_curr)))
                    # grid[int(y_curr+s)][x] = 'h'
            elif abs(slope) > 1: # predominantly vertical
                for y in range(min(y1, y2), max(y1, y2)):
                    x_curr = (y - b)/slope
                    x_next = (y+s - b)/slope
                    hyp = math.hypot(1, x_next-x_curr)
                    if y == 3:
                        print(x_curr, x_next, hyp)
                    if hyp > 1:
                        grid[y][int(x_curr)] = '#'
                        points.append(Vector(int(x_curr), y))
                    # grid[y+s][int(x_curr+s)] = 'v'
            else: # diagonal
                for x in range(min(x1, x2), max(x1, x2)+1):
                    y = int(slope*x + b)
                    grid[y][x] = 'd'
            print(f'B:({x2},{y2}), dy/dx:{slope}, b:{b}')

        print('\n'.join(''.join(row) for row in grid))

        return points
Exemplo n.º 9
0
 def get_child_pos(card, pos, size):
     quarter_size = size/4
     if card == Card.NORTHWEST:
         return Vector(pos.x - quarter_size, pos.y - quarter_size)
     elif card == Card.NORTHEAST:
         return Vector(pos.x + quarter_size, pos.y - quarter_size)
     elif card == Card.SOUTHWEST:
         return Vector(pos.x - quarter_size, pos.y + quarter_size)
     else:  # Card.SOUTHEAST
         return Vector(pos.x + quarter_size, pos.y + quarter_size)
Exemplo n.º 10
0
def main(args: List[str]) -> None:
    """
    Application entry point
    :param args: Argument list, should contain the file to load at index 1
    """

    asteroids: Set[Vector] = set()
    # File read stub
    with open(args[1], "r") as f:
        for y, line in enumerate(f):
            for x, c in enumerate(line.strip()):
                if c == "#":
                    asteroids.add(Vector(x, y))

    station: Vector = Vector(0, 0)
    best: int = 0
    for asteroid in asteroids:
        angles: Set[float] = set()

        for target in asteroids:
            if asteroid == target:
                continue

            angles.add(Vector.direction(target - asteroid))

        visible = len(angles)
        if visible > best:
            best = visible
            station = asteroid

    print(best)

    asteroids.remove(station)
    last_destroyed: Vector = Vector(0, 0)
    last_direction: Vector = Vector(-1E-6, -1)
    for _ in range(200):
        if len(asteroids) == 0:
            break
        smallest: float = 360.0
        to_destroy: Optional[Vector] = None
        for target in sorted(asteroids,
                             key=lambda a: Vector.distance(station, a)):
            angle = Vector.angle(last_direction, target - station)

            if smallest > angle > 0:
                smallest = angle
                to_destroy = target

        if to_destroy is None:
            to_destroy = next(iter(asteroids))
        asteroids.remove(to_destroy)
        last_destroyed = to_destroy
        last_direction = to_destroy - station

    print(last_destroyed.x * 100 + last_destroyed.y)
Exemplo n.º 11
0
        def __init__(self, parent=None, size=0, pos=Vector(0, 0)):
            self.children = {Card.NORTHWEST: None,
                             Card.NORTHEAST: None,
                             Card.SOUTHWEST: None,
                             Card.SOUTHEAST: None}
            self.parent = parent

            self.size = size
            self.pos = pos

            self.total_mass = 0
            self.center_of_mass = Vector(0, 0)
Exemplo n.º 12
0
def play(window: Tk, text: StringVar, score: StringVar, comp: IntcodeComp, grid: Grid[Block], cycles: int = 0) -> None:
    """
    Plays a frame of the Block Game in the Intcode VM
    :param window: Game window
    :param text: Grid text
    :param score: Score label
    :param comp: Intcode VM running the game
    :param grid: Game grid
    :param cycles: Empty cycles ran
    """

    # Check if there is anything new to display
    if len(comp.output_buffer) == 0:
        # If nothing new has been available to display for five frames, assume Game over
        if cycles == 5:
            # Print score and return
            print(score.get())
            return
        else:
            # Wait until next frame, and increment inactivity counter
            window.after(33, lambda: play(window, text, score, comp, grid, cycles + 1))

    # Position of the paddle and ball
    paddle: Vector = Vector(0, 0)
    ball: Vector = Vector(0, 0)

    # Pop out all the info in the output buffer
    while len(comp.output_buffer) >= 3:
        # Get position to write to
        pos: Vector = Vector(comp.next_output(), comp.next_output())
        # If score position, update score
        if pos == score_pos:
            score.set(comp.next_output())
        else:
            # Else get block type, and keep track if it's the paddle or ball
            block: Block = Block(comp.next_output())
            if block == Block.PADDLE:
                paddle = pos
            elif block == Block.BALL:
                ball = pos
            # Update the grid
            grid[pos] = block

    # Update the game label
    text.set(str(grid))
    # Input the new position of the paddle
    if ball.x != paddle.x:
        comp.add_input(-1 if ball.x < paddle.x else 1)
    else:
        comp.add_input(0)

    # Schedule the next update
    window.after(33, lambda: play(window, text, score, comp, grid))
Exemplo n.º 13
0
 def to_str_square(self, x, y, size=Vector(3, 3)):
     col = "#" * bool(0 == (x + y - 1) % 2) + " " * bool(1 ==
                                                         (x + y - 1) % 2)
     result = [col] * size.y * size.x
     fig_index = self.squares[x][y]
     if (fig_index != -1):
         fig = self.figures[fig_index]
         fig_pos = Vector(size.x // 2, size.y // 2)
         result[fig_pos.x * size.y + fig_pos.y] = fig.image
     return [
         "".join(result[k:k + size.y])
         for k in range(0, len(result), size.y)
     ]
Exemplo n.º 14
0
def std_figures():  #will just be referenced if saved as an array
    return [
        Figure(std_names[k], std_pos[k][0], std_movements[std_names[k]], 0,
               None, std_images[std_names[k]][0]) for k in range(8)
    ] + [
        Figure("Pawn", Vector(1, y), pawn_move, 0, None, "°") for y in range(8)
    ] + [
        Figure(std_names[k], std_pos[k][1], std_movements[std_names[k]], 1,
               None, std_images[std_names[k]][1]) for k in range(8)
    ] + [
        Figure("Pawn", Vector(6, y), std_movements["Pawn"], 1, None, "^")
        for y in range(8)
    ]
Exemplo n.º 15
0
def equation_moves(figure, squares, X, equation):
    result = []
    try:
        size = Vector(len(squares), len(squares[0]))
    except:
        size = Vector(8, 8)
    for x in X:
        for y in X:
            added = figure.pos.add(Vector(x, y))
            if (equation(x, y) and added.in_ranges([0, size.x], [0, size.y])
                    and squares[added.x][added.y] != figure.color):
                result += [Move(figure, figure.pos, added)]
    return result
Exemplo n.º 16
0
 def __init__(self,
              m00=0,
              m01=0,
              m02=0,
              m10=0,
              m11=0,
              m12=0,
              m20=0,
              m21=0,
              m22=0):
     #this may need some checking for row vs column major. stuff confuses me
     self.vectors.append(Vector(m00, m10, m20))
     self.vectors.append(Vector(m01, m11, m21))
     self.vectors.append(Vector(m02, m12, m22))
Exemplo n.º 17
0
 def physicsStep(self, entity):
     force = Vector()
     if not isinstance(self.root, Sprite):
         stack = [self.root]
         while len(stack) > 0:
             curr = stack.pop()
             d = curr.size/Vector.Distance(curr.center_of_mass, entity.pos)
             if d < THETA:
                 force += QuadTree.calc_force(curr.center_of_mass,
                                              entity.pos,
                                              curr.total_mass,
                                              entity.mass)
             else:
                 for c in curr.children.values():
                     if c is None or c is entity:
                         continue
                     elif isinstance(c, Sprite):
                         force += QuadTree.calc_force(c.pos, entity.pos,
                                                      c.mass, entity.mass)
                     else:
                         stack.append(c)
     entity.pos = entity.pos + entity.vel * DT
     entity.vel = entity.vel + (force / entity.mass) * DT
     if Vector.Length(entity.vel) > SPEED_LIMIT:
         entity.vel *= OVERSPEED_DAMP
     else:
         entity.vel *= NORMAL_DAMP
Exemplo n.º 18
0
    def _move(self, direction, steps):
        direction = self.DIRECTIONS.get(direction, direction)

        for i in range(0, steps):
            self._voxels.append(Vector(direction) + self._voxels[-1])

        self._transpose(self._to_origin())
Exemplo n.º 19
0
    def rob_controller():
        robot.start()
        ship = {
            Vector(0, 0): 1  # Part 2
        }

        while not robot.finished():
            robot.put(ship.get(robot.pos, 0))

            color = robot.get()
            turn = robot.get()

            # Painting

            canvas.new_paintings.append((robot.pos, COLORS[color]))
            ship[robot.pos] = color

            # Turn
            if turn == 0:
                robot.turn_left()
            elif turn == 1:
                robot.turn_right()

            robot.move()
            sleep(canvas.delay)

        print(len(ship))
        canvas.draw_sprites = False
Exemplo n.º 20
0
 def __init__(self, x, y, w, h):
     self.x = x
     self.y = y
     self.w = w
     self.h = h
     self.icon = '#'
     self.door = Vector()
Exemplo n.º 21
0
    def process_event(self, event):
        # Mouse
        if event.type == MOUSEBUTTONDOWN:
            coordinates = lambda p: Vector((p[0] - 100) / 600.,
                                           (p[1] - 100) / 400., 0)

            if self.dcel:
                face = self.dcel.find_face(coordinates(event.pos))
                if face:
                    self.selected = self.dcel.edges.index(face.edge)

        # Keyboard
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                self.stop()
            elif event.key == K_SPACE:
                e = self.dcel.edges[self.selected]
                if event.mod & KMOD_SHIFT > 0:
                    self.selected = self.dcel.edges.index(e.next)
                else:
                    self.selected = self.dcel.edges.index(e.prev)
            elif event.key == K_f:
                self.dcel.edges[self.selected].flip()

        # Varios
        elif event.type == QUIT:
            self.stop()
        elif event.type == VIDEORESIZE:
            self.resize(event.w, event.h)
Exemplo n.º 22
0
    def __init__(self,
                 size: Vector,
                 max_count: int,
                 reproduce_chance: float,
                 starting_point: Optional[Vector] = None,
                 quadratic: bool = False):
        self.size = size

        if starting_point is None:
            starting_point = Vector(size.x // 2, size.y // 2)
        elif not ((1 <= starting_point.x <= size.x) or
                  (1 <= starting_point.y <= size.y)):
            raise IndexError(
                'Starting point coordinate components must be less than or equal to the size of an image.'
            )
        self.starting_point = starting_point

        # The maximum allowable value of squares count
        if max_count is None:
            max_count = (size.x * size.y) // 2
        self.max_count = max_count

        self.reproduce_chance = reproduce_chance
        self.quadratic = quadratic

        # Current squares count
        self.count = 1
        self.current_generation = 1

        self.squares = [[None for y in range(self.size.y + 1)]
                        for x in range(self.size.x + 1)]
        self.__not_reproduced_squares = deque()
Exemplo n.º 23
0
def lup_solve(l, u, p, b):
    size = b.size
    n_b = p * b
    z = Vector(size)
    x = Vector(size)

    z[0] = n_b[0]
    for i in range(1, size):
        z[i] = n_b[i] - sum([l[i][j] * z[j] for j in range(0, i)])

    x[size - 1] = z[size - 1] / u[size - 1][size - 1]
    for i in range(size - 2, -1, -1):
        x[i] = (z[i] - sum([u[i][j] * x[j]
                            for j in range(i + 1, size)])) / u[i][i]

    return x
Exemplo n.º 24
0
def test(eigenvalue, v_matrix, matrix):
    print('Проверка')
    vectors = []

    for vector in zip(*v_matrix.matrix):
        v = Vector(v_matrix.size)
        v.vector = vector
        vectors.append(v)

        for i in range(0, len(vectors) - 1):
            print('v_{0}: '.format(i + 1), end='')
            vectors[i].print_vector()
            print('v_{0}: '.format(len(vectors)), end='')
            v.print_vector()
            print('(v_{0}, v_{1}): '.format(i + 1, len(vectors)), end='')
            res = sum([vectors[i][j] * v[j] for j in range(0, v.size)])
            print('{0:8.20f}'.format(res))
            print()

    print('Проверка A * x = a_k * x')

    for i in range(0, len(vectors)):
        print('a_k =  ', eigenvalue[i])
        print('x =  ', end='')
        vectors[i].print_vector()
        print('A * x =  ', end='')
        (matrix * vectors[i]).print_vector()
        print('a_k * x =  ', end='')
        (vectors[i] * eigenvalue[i]).print_vector()
        print('-------------------------------------------------------------')
Exemplo n.º 25
0
def method_jacobi_rotations(a, eps):
    n_iter = 0
    a_k = copy.copy(a)
    v = Matrix(a.size, single=True)

    while True:
        i_max, j_max = find_max(a_k)
        fi = 0.5 * math.atan(2 * a_k[i_max][j_max] /
                             (a_k[i_max][i_max] - a_k[j_max][j_max]))

        u = Matrix(a.size, single=True)
        u[i_max][i_max] = math.cos(fi)
        u[i_max][j_max] = -math.sin(fi)
        u[j_max][i_max] = math.sin(fi)
        u[j_max][j_max] = math.cos(fi)

        u_t = copy.copy(u)
        u_t.transpose()

        a_k = u_t * a_k * u
        v = v * u

        n_iter += 1

        if t(a_k) < eps:
            eigenvalue = Vector(a_k.size)
            eigenvalue.vector = [a_k[i][i] for i in range(0, a_k.size)]

            print('Итераций: ', n_iter)
            return eigenvalue, v
Exemplo n.º 26
0
    def find_face(self, point, suggested_face=None):
        if suggested_face:
            current_face = suggested_face
        else:
            current_face = self.faces[0]

        found = False
        while (not found) and current_face:
            vs = [
                Vector(v.coordinates.x, v.coordinates.y, 0)
                for v in current_face.vertices
            ]
            cps = [(vs[i] - point).crossprodZ(vs[(i + 1) % 3] - point)
                   for i in range(3)]
            if cps[0] < 0:
                adyacent = current_face.edges[0]
                current_face = adyacent.twin.face
            elif cps[1] < 0:
                adyacent = current_face.edges[1]
                current_face = adyacent.twin.face
            elif cps[2] < 0:
                adyacent = current_face.edges[2]
                current_face = adyacent.twin.face
            else:
                found = True

        return current_face
Exemplo n.º 27
0
    def intersects(self, b):
        #Rectangle collision detection (SAT Separating Axis Theorem)
        for rect in [self, b]:
            for i1 in range(len(rect.corners)):
                i2 = (i1 + 1) % len(rect.corners)
                p1 = rect.corners[i1]
                p2 = rect.corners[i2]

                normal = Vector(p2.y - p1.y, p1.x - p2.x)

                minA = maxA = minB = maxB = None

                for p in self.corners:
                    projected = normal.x * p.x + normal.y * p.y
                    if (minA == None or projected < minA):
                        minA = projected
                    if (maxA == None or projected > maxA):
                        maxA = projected

                for p in b.corners:
                    projected = normal.x * p.x + normal.y * p.y
                    if (minB == None or projected < minB):
                        minB = projected
                    if (maxB == None or projected > maxB):
                        maxB = projected

                if (maxA < minB or maxB < minA):
                    return False

        return True
Exemplo n.º 28
0
def solve(file):
    with open(file) as f:
        lines = f.readlines()

    cells = set()

    for y, line in enumerate(lines):
        for x, cell in enumerate(line):
            if cell == '#':
                cells.add(Vector(x, y))

    def neighbors(cells, current: Vector) -> List:
        x, y = current
        pos_neighbors = [
            (x, y - 1),
            (x - 1, y),
            (x + 1, y),
            (x, y + 1)
        ]
        return [(x, y) for x, y in pos_neighbors if (x, y) in cells]

    def round(cells):
        new_cells = set()

        for y in range(5):
            for x in range(5):
                cell = Vector(x, y)
                ns = neighbors(cells, cell)
                if cell in cells and len(ns) == 1:
                    new_cells.add(cell)
                elif cell not in cells and len(ns) in (1, 2):
                    new_cells.add(cell)

        return new_cells

    def print_cells(cells):
        diversity = sum(2 ** (y * 5 + x) for x, y in cells)

        for y in range(5):
            for x in range(5):
                print('#' if (x, y) in cells else '.', end='')
            print()
        print('Diversity of', diversity)
        print()

    print('Initial')
    print_cells(cells)

    history = list()
    history.append(cells)

    for r in range(4000):
        print('Round', r + 1)
        cells = round(cells)
        print_cells(cells)

        if cells in history:
            print('Restarting process')
            exit()
        history.append(cells)
Exemplo n.º 29
0
 def get_figure_by_pos(self, x, y):
     sq = self.squares[x][y]
     if (sq == -1):
         raise ValueError("There is no figure on this square (" +
                          Vector(x, y).chess_notation() + ").")
     else:
         return self.figures[sq]
Exemplo n.º 30
0
 def to_str_fancy(self, size=Vector(3, 3), auto_print=True):
     result = ""
     result_arr = [[
         self.to_str_square(x, y, size) for y in range(self.size.y)
     ] for x in range(self.size.x)]
     result += "  " + "".join([
         " " * (size.y // 2 + 1) + "ABCDEFGH"[i] + " " * (size.y // 2)
         for i in range(8)
     ]) + " \n"
     x_sep = "  +" + ("–" * size.y + "+") * self.size.y
     for big_x in range(self.size.x):
         result += x_sep + "\n"
         for x in range(size.x):
             if (x == size.x // 2):
                 result += str(big_x + 1) + " "
             else:
                 result += "  "
             for big_y in range(self.size.y):
                 result += "|"
                 for y in range(size.y):
                     result += result_arr[big_x][big_y][x][y]
             result += "|\n"
     result += x_sep + "\n"
     if (auto_print):
         print(result)
     return result