Example #1
0
def make_univer(n_particles=int(10e6)):
    max_v = 1
    min_v = -1
    particles = [Particle(r=Vector2d(random.uniform(-box_size // 2, box_size // 2),
                                             random.uniform(-box_size // 2, box_size // 2)),
                                  v=Vector2d(random.uniform(min_v, max_v),
                                             random.uniform(min_v, max_v)))]
    # global box_size

    i = 1
    while True:
        # if i % (n_particles//100) == 0:
        #     print('box:', i // (n_particles//100) + 1)
        tmp_par = Particle(r=Vector2d(random.uniform(-box_size // 2, box_size // 2),
                                             random.uniform(-box_size // 2, box_size // 2)),
                                  v=Vector2d(random.uniform(min_v, max_v),
                                             random.uniform(min_v, max_v)))
        flag = 1
        # for particle1 in particles:
        #     tmp_e = particle1.r - tmp_par.r
        #     if abs(tmp_e) == 0:
        #         continue
        #     tmp_f = forces.base_force(particle1, tmp_par)
        #     if (tmp_f.x*tmp_e.x + tmp_f.y*tmp_e.y) < 0:
        #         flag = 0

        if flag == 1:
            particles.append(tmp_par)
            i += 1

        if i >= n_particles:
            break

        # print(i)
    return particles
Example #2
0
 def __init__(self, r, name='noname', v=Vector2d(0, 0), mass=1):
     self.r = r
     self.v = v
     self.name = name
     self.mass = mass
     self.force = Vector2d(0, 0)
     self.color = (1, 1, 1)
Example #3
0
 def _add_edges(self):
     for x, y in itertools.product(range(self.columns), range(self.rows)):
         node = Vector2d(x, y)
         right_neighbor = Vector2d((x + 1) % self.columns, y)
         top_neighbor = Vector2d(x, (y + 1) % self.rows)
         self._edges[node, right_neighbor] = Edges.State.unknown
         self._edges[right_neighbor, node] = Edges.State.unknown
         self._edges[node, top_neighbor] = Edges.State.unknown
         self._edges[top_neighbor, node] = Edges.State.unknown
Example #4
0
    def calculate_force(self, particle, node=None):
        if node is None:
            node = self.root

        force = Vector2d(0, 0)
        if len(node.particles) == 0:
            return force

        # if (node.type == 2) and (abs(node.particles[0].r - particle.r) != 0):
        if (node.type == 2) and (node.particles[0] != particle):
            tmp_f = forces.base_force(particle, node.particles[0])
            # print(particle.name, node.name, node.depth, len(node.particles))
            # if particle.name == constants.median:
            #     tmp_brute_f = Vector2d()
            #     for particle_brute in node.particles:
            #         tmp_brute_f += forces.base_force(particle, particle_brute)
            #
            #     len_error = (abs(tmp_f) - abs(tmp_brute_f)) / (abs(tmp_brute_f) + constants.epsilon)
            #     print(len_error, '|', tmp_f, '|', tmp_brute_f)
            force += tmp_f

        cm = node.get_cm()
        if (node.type == 1) and (mac.mac(particle, node)):
            # print(particle.name, node.name)
            # print(particle.name,  node.name, node.depth, len(node.particles))
            tmp_f = forces.base_force(
                particle,
                Particle(r=cm, v=node.get_mv(), mass=node.mass, name='aprox'))

            a = 0.1
            b = 0.8
            tmp_color = ((b - a) * np.random.random() + a,
                         (b - a) * np.random.random() + a,
                         (b - a) * np.random.random() + a)

            self.save_particles += len(node.particles) - 1
            for particle_color in node.particles:
                particle_color.color = tmp_color

            if particle.name == constants.median:
                tmp_brute_f = Vector2d()
                for particle_brute in node.particles:
                    tmp_brute_f += forces.base_force(particle, particle_brute)

                len_error = (abs(tmp_f) - abs(tmp_brute_f)) / (
                    abs(tmp_brute_f) + constants.epsilon)
                print(len_error, '|', tmp_f, '|', abs(tmp_f), '|', tmp_brute_f,
                      '|', abs(tmp_brute_f))
            force += tmp_f

        if (node.type == 1) and not (mac.mac(particle, node)):
            for child in node.children:
                force += self.calculate_force(particle, child)

        return force
Example #5
0
def make_net(n_particles=int(10e6)):
    particles = []
    n_rows = int(math.sqrt(n_particles))
    h = constants.box_size // n_rows
    for i in range(n_particles):
        particles.append(
            Particle(r=Vector2d(i % n_rows * h, i // n_rows * h),
                     v=Vector2d()))
        # print(particles[-1].r)

    return particles, h
Example #6
0
 def getImpulse(m1,m2):
   vr = m1.getVelocity().copy()
   vr.sub(m2.getVelocity())
   n = Vector2d.normal(m2.getPosition(),m1.getPosition())
   impulse = n.copy()
   #m1.getPosition().display()
   #m2.getPosition().display()
   #impulse.display()
   s = Vector2d.dotProduct(vr,n)*(1 + 0.5)
   impulse.mulScalar(s)
   return impulse
Example #7
0
 def __init__(self, x, y, width, hieght, image, isPlayer=False):
     self.position = Vector2d(x, y)
     self.sprite = image
     self.velocity = Vector2d(0, 0)
     self.isPlayer = isPlayer
     self.width = width
     self.height = hieght
     self.radius = width / 2
     self.mass = self.radius * ATOM_MASS_PER_PER_PIXEL
     self.isVisible = True
     self.font = pygame.font.Font('freesansbold.ttf', 10) 
     self.colliding = False
Example #8
0
 def _handle_walls(self, walls):
     """Remove edges where there are walls."""
     for w in walls:
         tile1 = w.position
         tile2 = None
         if w.orientation == Wall.Orientation.horizontal:
             tile2 = w.position - Vector2d(0, 1)
         if w.orientation == Wall.Orientation.vertical:
             tile2 = w.position - Vector2d(1, 0)
         tile1 = self.grid.normalize(tile1)
         tile2 = self.grid.normalize(tile2)
         self.edges[tile1, tile2] = Edges.State.absent
Example #9
0
    def apply_player_direction(self, delta):
        direction = Vector2d(0, 0)

        if self.moveDOWN:
            direction += Vector2d(0, PLAYER_ACCELERATION)
        if self.moveUP:
            direction += Vector2d(0, -PLAYER_ACCELERATION)
        if self.moveRIGHT:
            direction += Vector2d(PLAYER_ACCELERATION, 0)
        if self.moveLEFT:
            direction += Vector2d(-PLAYER_ACCELERATION, 0)

        self.playerAtom.velocity += direction
Example #10
0
def make_hex_2(r, center):
    particles = [Particle(r=center, v=Vector2d(), name=0)]

    for i in range(r):
        tmp_par = []
        for angle in [j * math.pi / 3 for j in range(6)]:
            tmp_par.append(
                Particle(r=center + Vector2d(
                    (i + 1) * constants.a * math.sin(angle),
                    (i + 1) * constants.a * math.cos(angle)),
                         v=Vector2d(),
                         name=len(particles)))

        for j, particle in enumerate(tmp_par[:-1]):
            particles.append(particle)

            # fig, ax1 = plt.subplots(figsize=(4, 4))
            # x = [particle.r.x for particle in particles]
            # y = [particle.r.y for particle in particles]
            # ax1.scatter(x=x, y=y, marker='o', c='r', edgecolor='b')
            # ax1.set_title('Scatter: $x$ versus $y$')
            # ax1.set_xlabel('$x$')
            # ax1.set_ylabel('$y$')
            # plt.show()

            e_tmp = particle.r - tmp_par[j + 1].r
            e_tmp = e_tmp * (1 / abs(e_tmp))
            for k in range(i):
                particles.append(
                    Particle(r=particle.r - e_tmp * constants.a,
                             v=Vector2d(),
                             name=len(particles)))

                # fig, ax1 = plt.subplots(figsize=(4, 4))
                # x = [particle.r.x for particle in particles]
                # y = [particle.r.y for particle in particles]
                # ax1.scatter(x=x, y=y, marker='o', c='r', edgecolor='b')
                # ax1.set_title('Scatter: $x$ versus $y$')
                # ax1.set_xlabel('$x$')
                # ax1.set_ylabel('$y$')
                # plt.show()

        particles.append(tmp_par[-1])
        e_tmp = tmp_par[-1].r - tmp_par[0].r
        e_tmp = e_tmp * (1 / abs(e_tmp))
        for k in range(i):
            particles.append(
                Particle(r=particle.r - e_tmp * constants.a,
                         v=Vector2d(),
                         name=len(particles)))
    return particles
Example #11
0
 def _setup_walls(self):
     for w in self.puzzle.walls:
         self.grid.add_widget(WallWidget(w))
         # Double the walls on the board's borders
         if w.position.x == 0 and w.orientation == Wall.Orientation.vertical:
             w2 = Wall(Vector2d(w.position.x + self.columns, w.position.y),
                       w.orientation)
             # noinspection PyTypeChecker
             self.grid.add_widget(WallWidget(w2))
         if w.position.y == 0 and w.orientation == Wall.Orientation.horizontal:
             w2 = Wall(Vector2d(w.position.x, w.position.y + self.rows),
                       w.orientation)
             # noinspection PyTypeChecker
             self.grid.add_widget(WallWidget(w2))
Example #12
0
  def step(self,step):
    for mobile in self.mobiles:
      mobile.applyStep(step)
      grav = self.gravity.copy()
      grav.mulScalar(mobile.getMass())
      #grav.rotate(mobile.getAngle())
      mobile.applyForce(step,grav)
      for mobile2 in self.mobiles:
        if mobile != mobile2:
          if mobile.isBound(mobile2.getPosition(),mobile2.getRadius()) == 1:
            n = Vector2d.normal(mobile2.getPosition(),mobile.getPosition())
            vn = Vector2d.dotProduct(mobile.getVelocity(),n)
            if vn < 0:
              #mobile.getVelocity().display()
              #n.display()    
              Mobile.solveCollide(mobile,mobile2)
	      mobile.applyStep(step)
              mobile2.applyStep(step)
      for plane in self.planes:
        #d = plane.distancePoint(mobile.getPosition())
        #vn = Vector2d.dotProduct(mobile.getVelocity(),plane.getNormal())
        #if d < 0 and vn < 0:
        #  plane.reflective(mobile)
        
        for submobile in mobile.getMobiles():
          d = plane.distancePoint(submobile.getPhysicalPosition())
          vn = Vector2d.dotProduct(submobile.getVelocity(),plane.getNormal())
          if d < submobile.getRadius() and vn < 0:
            #ADDED CONDITION OVER PHYSICAL POINTS
            if submobile.getUpdatedPhysicalPoints().count > 0:
              ppcollide = 0
              for point in submobile.getUpdatedPhysicalPoints():
                if plane.distancePoint(point) < 0:
                  self.groundcollider.collideEvent(point)
                  n = plane.getNormal().copy()
                  n.normalize()
                  n.mulScalar(-plane.distancePoint(point))
                  #n.display()
                  mobile.getPosition().add(n)
                  mobile.updateMobiles()
                  
                  ppcollide = 1
                  
              if ppcollide == 1:
                plane.reflective(submobile)
                for submobile2 in mobile.getMobiles():
                  v = submobile2.getVelocity()
                  v.set(0.0,v.getY())
                mobile.angularVelocity = mobile.angularVelocity * 0.8
Example #13
0
def make_univer(n_particles=int(10e6)):
    particles = []
    # global box_size
    max_v = 1
    min_v = -1
    for i in range(n_particles):
        if i % (n_particles // 100) == 0:
            print(i // (n_particles // 100) + 1)
        particles.append(
            Particle(r=Vector2d(random.randint(-box_size // 2, box_size // 2),
                                random.randint(-box_size // 2, box_size // 2)),
                     v=Vector2d(random.randint(min_v, max_v),
                                random.randint(min_v, max_v))))

    return particles
Example #14
0
def create_sphere2(radii, lengths, num_sumples=2000, mass=1):
    attempts = 100
    # particles = [Particle(r=Vector3d(), mass=10)]
    particles = []
    num = 100
    for i in range(0, len(lengths) // num):
        cur_num_particles = 0
        while True:
            u = np.random.uniform(0, 2 * np.pi)
            tmp_z = np.random.uniform(0, 1)

            mul = tmp_z**(1 / 3)
            # mul = (mul * lengths[i*num + num-1]) + (lengths[i*num + num-1] - lengths[i*num])
            mul = lengths[i * num] + mul * (lengths[i * num + num - 1] -
                                            lengths[i * num])
            r1 = radii[0] * mul
            r2 = radii[1] * mul

            tmp = [r1 * np.cos(u), r2 * np.sin(u)]
            if criterion(tmp, particles):
                [x, y] = [tmp[0], tmp[1]]
                particles.append(Particle(r=Vector2d(x, y), mass=mass))

                cur_num_particles += 1
            # if cur_num_particles % 1 == 0:
            #     print(cur_num_particles)
            if cur_num_particles == num // 10:
                break
    return particles
Example #15
0
 def collides_with(self, entity):
     retVal = False
     if self.isVisible and entity.isVisible:
         myPosition = Vector2d( self.position.x - self.radius, 
                                self.position.y - self.radius)
         entityPosition = Vector2d( entity.position.x - entity.radius, 
                                        entity.position.y - entity.radius)   
         
         totalRadiuses = self.radius + entity.radius
         distance = myPosition - entityPosition
         
         if distance.length() < totalRadiuses:
             retVal = True
             self.colliding = True
         
     return retVal
Example #16
0
    def calculate_force(self, particle, node=None):
        if node is None:
            node = self.root

        force = Vector2d(0, 0)
        if len(node.particles) == 0:
            return force

        if (node.type == 2) and (node.particles[0] != particle):
            tmp_f = forces.base_force(particle, node.particles[0])
            # print(particle.name, node.name, node.depth, len(node.particles))
            force += tmp_f

        cm = node.get_cm()
        if (node.type == 1) and (mac.mac(particle, node)):
            # print(particle.name, node.name)
            # print(particle.name,  node.name, node.depth, len(node.particles))
            tmp_f = forces.base_force(particle, Particle(r=cm, v=node.get_mv(), mass=node.mass))

            force += tmp_f

        if (node.type == 1) and not(mac.mac(particle, node)):
            for child in node.children:
                force += self.calculate_force(particle, child)

        return force
Example #17
0
 def run(self):
     """Run the solver. This might take some time."""
     all_tiles = deque(n for n in self.grid)
     initial_state = Solver.State(self.tiles, self.edges)
     self._handle_simple_tiles(initial_state)
     work_stack = [Solver.WorkItem(initial_state, all_tiles)]
     while work_stack:
         item = work_stack.pop()
         state = item.state
         work = item.work
         investigate = self._forward_inference(state, work)
         if not investigate:
             continue  # Pop next state from stack
         # Choose tile with least amount of possible orientations left
         minimum = None
         min_pos = Vector2d(0, 0)
         for node in self.grid:
             orientations = len(state.tiles[node].possible_orientations)
             if orientations >= 2 and (minimum is None or orientations < minimum):
                 minimum = orientations
                 min_pos = node
         assert minimum is not None
         for o in state.tiles[min_pos].possible_orientations:
             neighbors = deque(self.grid.neighbors(min_pos))
             child_state = state.clone()
             child_state.tiles[min_pos].possible_orientations = [o]
             self._inspect_tile(min_pos, child_state)  # apply this orientation to edges
             work_stack.append(Solver.WorkItem(child_state, neighbors))
     print("Found {} solution(s)".format(len(self.solutions)))
Example #18
0
    def _inspect_tile(self, node, state):
        """Inspect a single tile/node and try to reduce the number of possible orientations left by trying one after
        another.
        """
        tile = state.tiles[node]

        if len(tile.possible_orientations) <= 0:
            return len(tile.possible_orientations)

        tile.possible_orientations = [o for o in tile.possible_orientations if self._valid_orientation(node, o, state)]

        # noinspection PyTypeChecker
        for i, d in enumerate(Direction):
            collected_edges = []
            for o in tile.possible_orientations:
                connectors = tile_connectors[tile.link][o]
                collected_edges.append(connectors[i])
            # Reduce: check all edges are the same, either all True or all False
            if collected_edges and collected_edges.count(collected_edges[0]) == len(collected_edges):
                edge_state = collected_edges[0]
            else:
                continue
            child = node + d.vector
            child = Vector2d(child.x % self.columns, child.y % self.rows)
            # edge_state is either True or False
            if state.edges[node, child] is not Edges.State.unknown:
                assert ((edge_state is True and state.edges[node, child] is Edges.State.present) or
                        (edge_state is False and state.edges[node, child] is Edges.State.absent))
            state.edges[node, child] = Edges.State.present if edge_state is True else Edges.State.absent
Example #19
0
def criterion(tmp, particles):
    tmp_particle = Particle(r=Vector2d(*tmp))
    for particle in particles:
        # print((tmp_particle.r - particle.r).dot(forces.base_force(tmp_particle, particle)))
        # if (tmp_particle.r - particle.r).dot(forces.base_force(tmp_particle, particle)) > -0.3:
        if abs(tmp_particle.r - particle.r) < 1 * constants.a:
            return False
    return True
Example #20
0
def main():
    print("correct vector:")
    correct_vector = Vector2d(-6.9, 42)
    correct_vector.print_vector()
    print("length:", correct_vector.vector_length())
    print()

    print("multiplied vector:")
    multiplied_vector1 = correct_vector.multiply_vector(5)
    multiplied_vector1.print_vector()
    print()

    print("vector multiplied by wrong factor:")
    multiplied_vector2 = correct_vector.multiply_vector('f')
    multiplied_vector2.print_vector()
    print()

    print("vector multiplied by nothing:")
    multiplied_vector2 = correct_vector.multiply_vector()
    multiplied_vector2.print_vector()
    print()

    print("wrong argument vector:")
    wrong_argument_vector = Vector2d(-6.9, 'f')
    wrong_argument_vector.print_vector()
    print(wrong_argument_vector.vector_length())
    print

    print("not enough arguments vector:")
    not_enough_arguments_vector = Vector2d(65)
    not_enough_arguments_vector.print_vector()
    print(not_enough_arguments_vector.vector_length())
    print()

    print("no arguments vector:")
    no_arguments_vector = Vector2d()
    no_arguments_vector.print_vector()
    print no_arguments_vector.vector_length()
    print()

    print("to much arguments vector:")
    to_much_arguments_vector = Vector2d(2, 3, 4)
    to_much_arguments_vector.print_vector()
    print(to_much_arguments_vector.vector_length())
    print()
Example #21
0
def read(read_path):
    particles = []
    with open(read_path, 'r') as inputfile:
        s_tmp = inputfile.read()
        for el in s_tmp.split('\n')[2:]:
            if el != '':
                rx, ry, cr, cg, cb = el.split()
                particles.append(Particle(r=Vector2d(float(rx), float(ry)), name=len(particles)))
    return particles
Example #22
0
def make_hex(k=10, l=10):
    # k количество рядов до середины
    # l количество в крайнем ряду
    particles = []
    for i in range(k):
        for j in range(i + l):
            particles.append(
                Particle(r=Vector2d(constants.a * i * math.sqrt(3) / 2,
                                    constants.a * j - constants.a * 0.5 * i),
                         v=Vector2d(),
                         name=len(particles)))
    for i in range(k, 2 * k - 1):
        for j in range(l + k - 2 - (i - k)):
            particles.append(
                Particle(r=Vector2d(
                    constants.a * i * math.sqrt(3) / 2,
                    constants.a * j + constants.a * 0.5 * (i - 2 * k + 2)),
                         v=Vector2d(),
                         name=len(particles)))
    return particles
Example #23
0
    def run(self):
        """Execute the builder

        :return: The created puzzle
        :rtype: Puzzle
        """
        self._source = Vector2d(self.columns // 2, self.rows // 2)
        grid = self._create_tree()
        walls = self._create_walls()
        rotated_tiles = self._rotate(grid)
        return Puzzle(grid, walls, self._source, rotated_tiles, self.wrap)
Example #24
0
  def isBound(self,point,radius):
    d = Vector2d.distance(self.position,point)
    if d < 0:
	d = -d
    d = d - radius - self.radius
    #print "distance: %f\n"%d
    #d = d - self.radius
    if d < 0:
      return 1
    else:
      return 0
Example #25
0
    def _create_walls(self, percent=0.06, rsd=0.2):
        """Randomly place some walls

        The actual number of walls is drawn from a normal distribution.

        :param float percent: Mean percent of walls to be created
        :param float rsd: Relative standard deviation
        """
        walls = set()  # collect all possible walls
        for x, y in itertools.product(range(self.columns), range(self.rows)):
            if (self.wrap
                    or y != 0) and not self._nodes[x, y].edges[Direction.down]:
                walls.add(Wall(Vector2d(x, y), Wall.Orientation.horizontal))
            if (self.wrap
                    or x != 0) and not self._nodes[x, y].edges[Direction.left]:
                walls.add(Wall(Vector2d(x, y), Wall.Orientation.vertical))
        mean = len(walls) * percent
        count = clamp(int(random.gauss(mean, rsd * mean)), 0, len(walls))
        walls = random.sample(walls, count)
        return walls
Example #26
0
def get_and_plot_density(particles, radii, rotation, center, num=100):
    cm = Vector2d()
    particles_ = copy.deepcopy(particles)

    derotation = np.linalg.inv(rotation)

    for particle in particles_:
        particle.r.x -= center[0]
        particle.r.y -= center[1]

        tmp = np.dot(np.array([particle.r.x, particle.r.y]), derotation)
        particle.r = Vector2d(tmp[0], tmp[1])

        cm += particle.r
    cm = cm * (1 / len(particles_))

    for i in range(len(particles)):
        particles_[i].r.x *= 1 / radii[0]
        particles_[i].r.y *= 1 / radii[1]

    lengths = sorted([abs(particle.r) for particle in particles_])
    density = []
    l = []
    # particles = sorted(particles, key=lambda particle: abs(particle.r - cm))

    for i in range(len(lengths) // num):
        density.append(num * particles_[0].mass /
                       (np.pi *
                        (lengths[i * num + num - 1]**2 - lengths[i * num]**2)))
        # l.append(lengths[i*num] + 0.5*(lengths[i*num + num-1] - lengths[i*num]))
        l.append(lengths[i * num])

    ig, ax1 = plt.subplots(figsize=(4, 4))

    ax1.scatter(x=l, y=density, marker='o', c='r', edgecolor='b')
    ax1.set_title('Scatter: $x$ versus $y$')
    ax1.set_xlabel('$x$')
    ax1.set_ylabel('$y$')
    plt.show()

    return density, lengths
Example #27
0
 def example(cls):
     """A simple example puzzle"""
     grid = GridContainer(Grid(3, 3))
     grid[0, 2] = Tile(LinkType.dead_end, Direction.down)
     grid[1, 2] = Tile(LinkType.t_intersection, Direction.right)
     grid[2, 2] = Tile(LinkType.corner, Direction.left)
     grid[0, 1] = Tile(LinkType.dead_end, Direction.down)
     grid[1, 1] = Tile(LinkType.t_intersection, Direction.down)
     grid[1, 1].entity = EntityType.source
     grid[2, 1] = Tile(LinkType.straight, Direction.right)
     grid[0, 0] = Tile(LinkType.dead_end, Direction.down)
     grid[1, 0] = Tile(LinkType.corner, Direction.up)
     grid[2, 0] = Tile(LinkType.dead_end, Direction.right)
     walls = {
         Wall(Vector2d(0, 2), Wall.Orientation.horizontal),
         Wall(Vector2d(2, 1), Wall.Orientation.vertical)
     }
     return Puzzle(grid,
                   walls,
                   source=Vector2d(1, 1),
                   expected_moves=7,
                   wrap=False)
Example #28
0
 def _valid_orientation(self, node, orientation, state):
     """Check if for a given node/tile, the given orientation is possible, i.e. compatible with the surrounding
     tiles.
     """
     connectors = tile_connectors[state.tiles[node].link][orientation]
     for d in Direction:
         child = node + d.vector
         child = Vector2d(child.x % self.columns, child.y % self.rows)
         if state.edges[node, child] is Edges.State.unknown:
             continue
         elif ((connectors[d.index] is True and state.edges[node, child] is Edges.State.absent) or
               (connectors[d.index] is False and state.edges[node, child] is Edges.State.present)):
             return False
     return True
Example #29
0
  def applyStep(self,step):
    v = self.getVelocity()
    v.set(0.0,0.0)
    #self.angularVelocity = 0.0
    for mobile in self.mobiles:
      vmobile = mobile.getVelocity().copy()
      v.add(vmobile)

      #vmobile = mobile.getVelocity()

      om = mobile.getPhysicalPosition().copy()
      om.sub(self.getPosition())
      #om.display()
      vmobile.mulScalar(mobile.getMass())
      if om.length() != 0.0 :
        av = Vector2d.vtangent(om,vmobile) / om.length()
        av = -av
      else :
       av = 0.0

      if om.getX() < 0.0:
        av = -av
      if vmobile.getY() > 0.0:
        av = -av
      #print "ANGULAR VELOCITY AV=%f OM=%f MASS=%f"%(av,om.length(),mobile.getMass())
      self.angularVelocity += av * 0.5

    v.mulScalar(step)
    self.getPosition().add(v)
    #print "ANGULAR VELOCITY=%f"%(self.angularVelocity)
    
    self.angle += self.angularVelocity * step*0.001   
    #self.angularVelocity = self.angularVelocity / 2.0
    self.updateMobiles()
 
    #print 'TOTO: %d %d'%(self.stablecount,self.stable)
    #print '%f - %f'%(self.angle,self.oldangle)
    #print '%d'%int(fabs(self.getPosition().getX()-self.oldposition.getX()))
    #print '%d - %f - %f'%(int(fabs(self.getPosition().getY()-self.oldposition.getY())),self.getPosition().getY(),self.oldposition.getY())
    if int(self.angle) == int(self.oldangle) and int(fabs(self.getPosition().getX()-self.oldposition.getX())) < 1 and int(fabs(self.getPosition().getY()-self.oldposition.getY())) < 1 :
      self.stablecount += 1
      if self.stablecount > 180:
        self.stable = 1
    else :
      self.stablecount = 0

    self.oldposition.set(self.getPosition().getX(),self.getPosition().getY())
    self.oldangle = self.angle
Example #30
0
    def get_vertex(self, x, y=None):
        """Get a vertex from the polygon, if extant.
        
        :param x: x coordinate of the vertex, or optionally a list of coordinates.
        :keyword y: y coordinate of the vertex.

        XXX: this is currently very slow!
        """
        if not isinstance(x, Vector2d):
            x = Vector2d(x, y)

        for v in self.vertices:
            if v == x:
                return v

        return None
Example #31
0
    def _create_tree(self):
        """Create the underlying tree.

        The algorithm starts with a source in the center and chooses an already visited tile at random to extend the
        tree to a random unvisited tile.
        """
        self._nodes = GridContainer(Grid(self.columns, self.rows))
        nodes = self._nodes  # alias
        for x, y in itertools.product(range(self.columns), range(self.rows)):
            nodes[x, y] = Builder.Node()
        visited = GridContainer(Grid(self.columns, self.rows), False)
        visited[self._source] = True
        boundary = {self._source}
        while True:
            new_boundary = set()
            moves = []  # [(parent, child, direction), ...]  FIXME namedtuple
            for parent in boundary:
                for direction in Direction:
                    child = parent + direction.vector
                    if self.wrap:
                        child = Vector2d(child.x % self.columns,
                                         child.y % self.rows)
                    if 0 <= child.x < self.columns and 0 <= child.y < self.rows and not visited[
                            child]:
                        moves.append((parent, child, direction))
                        new_boundary.add(parent)
            if not moves:
                break
            weights = []
            for p, _, d in moves:
                nodes[p].edges[d] = True
                link = nodes[p].to_tile().link
                nodes[p].edges[d] = False
                weights.append(self.difficulties[self.difficulty][link])
            parent, child, direction = weighted_choice(moves, weights)
            new_boundary.add(child)
            visited[child] = True
            nodes[parent].edges[direction] = True
            nodes[child].edges[-direction] = True
            boundary = new_boundary

        # Transform nodes/edges into tiles with link type and orientation
        tiles = GridContainer(Grid(self.columns, self.rows))
        for x, y in itertools.product(range(self.columns), range(self.rows)):
            tiles[x, y] = nodes[x, y].to_tile()
        tiles[self._source].entity = EntityType.source
        return tiles
Example #32
0
 def check_power(self):
     """Check which tile is connected to the power source"""
     power = GridContainer(Grid(self.columns, self.rows), False)
     work = {self.puzzle.source}
     while work:
         parent = work.pop()
         power[parent] = True
         for direction in Direction:
             proto_child = parent + direction.vector
             if not self.puzzle.wrap and not self.board.grid.valid(
                     proto_child):
                 continue
             child = Vector2d(proto_child.x % self.columns,
                              proto_child.y % self.rows)
             # noinspection PyTypeChecker
             if (not power[child]
                     and self._connected(parent, child, direction)
                     and not self._blocking_wall(parent, proto_child)):
                 work.add(child)
     for x, y in itertools.product(range(self.columns), range(self.rows)):
         self.board[x, y].powered = power[x, y]
Example #33
0
def main():
    from vector2d import Vector2d

    def f(t, x):
        return Vector2d(-1.9 * x[0] - 1.7 * x[1], x[0])

    t = 0
    dt = 0.05
    x = Vector2d(20, 10)
    data1 = []
    data2 = []
    for i in range(300):
        t, x = Integrator.rk4(t, dt, x, f)
        # vel
        data1.append((t, x[0]))
        #pos
        data2.append((t, x[1]))

    from pylab import plot, show, legend
    p1, = plot([i for i, j in data1], [j for i, j in data1], 'k--')
    p2, = plot([i for i, j in data2], [j for i, j in data2], 'k-')
    legend([p1, p2], ["Velocity", "Position"])
    show()
Example #34
0
  def follow(self,p1):
    target = p1.getPosition().copy()
    current = self.screenToWorld(self.screenw/2.0,self.screenh/2.0)
    distance = Vector2d.distance(target,current)
    target.sub(current)
    target.mulScalar(1.0/distance)
    p = self.screenToWorld(0,0)
    p2 = self.screenToWorld(self.screenw,self.screenh)
    x = target.getX()
    y = target.getY()
    currentp = self.position.copy()
    currentp.add(target)
    if p.getX() < 0.0 and target.getX() < 0.0 :
      x = 0.0
    if p2.getX() > self.screenw and target.getX() > 0.0 :
      x = 0.0 
    if p.getY() < 0.0 and target.getY() < 0.0 : 
      y = 0.0
    if p2.getY() > self.screenh and target.getY() > 0.0 :
     y = 0.0

    #p2.display()
    target.set(x,y)
    self.position.add(target)  
Example #35
0
 def __init__(self, x, y, screen):
     Vector2d.__init__(self, x, y)
     self.screen = screen
     self.screenHalfWidth = screen.get_width() / 2
     self.screenHalfHeight = screen.get_height() / 2
     self.entity = None
Example #36
0
 def __init__(self, *args, **kwargs):
     Vector2d.__init__(self, *args, **kwargs)
     PointBase.__init__(self)
Example #37
0
 def distancePoint(self,point):
   return Vector2d.dotProduct(point,self.normal) + self.distance
Example #38
0
 def reflective(self,mobile):
   velocity = mobile.getVelocity()
   n = self.normal.copy()
   s = Vector2d.dotProduct(velocity,n) * (1 + 0.0)
   n.mulScalar(s)
   velocity.sub(n)
Example #39
0
 def _handle_boundary(self):
     """Initialize edges, depending on the 'wrapping' option of the game."""
     for x in range(self.columns):
         self.edges[Vector2d(x, 0), Vector2d(x, self.rows - 1)] = Edges.State.absent
     for y in range(self.rows):
         self.edges[Vector2d(0, y), Vector2d(self.columns - 1, y)] = Edges.State.absent