def make_particles(width,
                   height,
                   particles_count,
                   cut_off_distance,
                   velocity_mul=0):
    cols_count = int((particles_count * width / height)**0.5)
    rows_count = int(particles_count // cols_count)

    delta_w = width / cols_count
    delta_h = height / rows_count

    particles = []
    for i in range(rows_count):
        for j in range(cols_count):
            particle = Particle(center=Vector2D(delta_w * j + 0.5 * delta_w,
                                                delta_h * i + 0.5 * delta_h),
                                radius=0.5,
                                velocity=Vector2D(random() - 0.5,
                                                  random() - 0.5) *
                                velocity_mul)
            particles.append(particle)

    cells = ParticlesCells(width, height, cut_off_distance)
    cells.update_cells(particles)

    return cells
예제 #2
0
def click(event):
    global x, y, click_flag, vecs
    if click_flag:
        # Criar o vetor
        vec = Vector2D(x, y, event.x, event.y)
        vec.name = "v" + str(len(vecs) + 1)
        vec.color = "black"
        vecs.append(vec)

        # Desenhar o vetor na tela
        draw_vec(vec)

        # Desenha o vetor soma
        if (len(vecs) > 1):
            sum_vec = Vector2D(vecs[0].x1, vecs[0].y1, 0, 0)
            for vect in vecs:
                sum_vec += vect
            sum_vec.name = "vR"
            sum_vec.color = "#c314ce"
            remove_vec(
                sum_vec
            )  # Se achar um vetor já desenhado com essa tag, deleta ele
            draw_vec(sum_vec, False)

        # Setar ponto de origem para o próximo vetor
        x, y = event.x, event.y
    else:
        # Setar a origem
        x, y = event.x, event.y
        click_flag = True
    def randomise(self):
        # create points
        self.points = []
        for y in range(self.h + 1):
            for x in range(self.w + 1):

                vec = Vector2D((x * self.resolution), (y * self.resolution))
                vec.data["state"] = randint(0, 1)

                self.points.append(vec)

        # create squares
        self.grid = []
        for y in range(self.h + 1):
            for x in range(self.w + 1):
                vec = Vector2D((x * self.resolution) + self.resolution / 2,
                               (y * self.resolution) + self.resolution / 2)

                dist = []
                for point in self.points:
                    dist.append(int(point.dist(vec)))
                dist = min(dist)

                temp = []
                for point in self.points:
                    if int(point.dist(vec)) == dist: temp.append(point)

                if len(temp) == 4:
                    self.grid.append(temp)
 def __init__(self, position=(0, 0)):
     super(Player, self).__init__()
     self.animation = {
         "right":
         Animation((pygame.transform.rotate(sprite, -90)
                    for sprite in settings.SPRITES["pacman"]), 0.17),
         "left":
         Animation((pygame.transform.rotate(sprite, 90)
                    for sprite in settings.SPRITES["pacman"]), 0.17),
         "up":
         Animation((pygame.transform.rotate(sprite, 180)
                    for sprite in settings.SPRITES["pacman"]), 0.17),
         "down":
         Animation((pygame.transform.rotate(sprite, 0)
                    for sprite in settings.SPRITES["pacman"]), 0.17),
         "death":
         OneTimeAnimation(settings.SPRITES["death"], 0.17)
     }
     self.image = self.animation["right"].sprites[0]
     self.rect = self.image.get_rect(center=position)
     self.position = Vector2D(*position)
     self.tile_index = settings.get_tile_index(position)
     self.moving = False
     self.target = self.position
     self.direction = Vector2D(0, 0)
     self.radius = self.rect.width // 3
     self.energized = True
     self.dead = False
    def from_grid(self, grid):
        # create points
        self.points = []
        for y in range(self.h + 1):
            for x in range(self.w + 1):

                vec = Vector2D((x * self.resolution), (y * self.resolution))
                vec.data["state"] = not grid[y][x]

                self.points.append(vec)

        # create squares
        self.grid = []
        for y in range(self.h + 1):
            for x in range(self.w + 1):
                vec = Vector2D((x * self.resolution) + self.resolution / 2,
                               (y * self.resolution) + self.resolution / 2)

                dist = []
                for point in self.points:
                    dist.append(int(point.dist(vec, use_sqrt=False)))
                dist = min(dist)

                temp = []
                for point in self.points:
                    if int(point.dist(vec, use_sqrt=False)) == dist:
                        temp.append(point)

                if len(temp) == 4:
                    self.grid.append(temp)
예제 #6
0
 def tree(self, x, y, rootheight, depth):
     y2 = y - rootheight
     if self.isgrowdown:
         y2 = y + rootheight
     self.canvas.line((x, y, x, y - rootheight),
                     fill=self.rgb, width=self.lwidth)
     self.__branch(Vector2D(x, y), Vector2D(x, y - rootheight), depth)
예제 #7
0
파일: bug1.py 프로젝트: RIP2014/HW2_Team5
    def move_tangent_line(self):

        print "IN TANGENT LINE"
        slope_to_center = (
            -self.circumnavigation_obstacle.center.y + self.position.y) / (
                -self.circumnavigation_obstacle.center.x + self.position.x)
        tangent_line_slope = (-1 / slope_to_center)
        if (self.position.y > self.circumnavigation_obstacle.center.y):
            self.direction = Vector2D(1, tangent_line_slope)

        elif (self.position.y < self.circumnavigation_obstacle.center.y
              and self.position.x < self.circumnavigation_obstacle.center.x):
            self.direction = Vector2D(-1, abs(tangent_line_slope))

        else:
            self.direction = Vector2D(-1, -abs(tangent_line_slope))
        self.direction.normalize()
        self.visited_points.append(Point(self.position.x, self.position.y))
        self.distance_traveled += 1
        self.circumnavigation_travel += 1
        if (self.position.distance_to(self.goal) <
                self.circumnavigation_closest_point.distance_to(self.goal)):
            self.circumnavigation_closest_point = Point(
                self.position.x, self.position.y)
        self.position.x += self.direction.x
        self.position.y += self.direction.y
예제 #8
0
def init():
    canvas = document.getElementById("gl-canvas")
    global gl
    gl = WebGLUtils.setupWebGL(canvas)
    if not gl:
        alert("WebGL isn't available")

    vertices = [
        Vector2D(-1, -1).as_list(),
        Vector2D(1, 1).as_list(),
        Vector2D(1, -1).as_list(),
        Vector2D(-1, 1).as_list(),
    ]

    gl.viewport(0, 0, canvas.width, canvas.height)
    gl.clearColor(1.0, 1.0, 1.0, 1.0)

    program = initShaders(gl, "vertex-shader", "fragment-shader")
    gl.useProgram(program)

    vPositionLoc = gl.getAttribLocation(program, "vPosition")

    bufferId = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, bufferId)
    gl.bufferData(gl.ARRAY_BUFFER, flatten(vertices), gl.STATIC_DRAW)

    gl.enableVertexAttribArray(vPositionLoc)

    gl.vertexAttribPointer(vPositionLoc, 2, gl.FLOAT, False, 0, 0)

    render()
예제 #9
0
파일: ball.py 프로젝트: burenotti/pygame
 def draw(self, screen: pygame.Surface) -> None:
     screen.blit(self.image, tuple(self.top_left_point))
     scrrect = Rect(Color(0, 0, 0), Vector2D(0, 0), Vector2D(screen.get_width(), screen.get_height()), 0)
     radius = self.width / 2
     if self.center.x - radius < 0 or self.center.x + radius > screen.get_width():
         self.speed = Vector2D(-self.speed.x, self.speed.y)
     if self.center.y - radius < 0 or self.center.y + radius > screen.get_height():
         self.speed = Vector2D(self.speed.x, -self.speed.y)
예제 #10
0
def main():
    v1 = Vector2D(2, -2)
    print(v1)
    v2 = Vector2D(2, 3)
    print(v2)
    v3 = v1 + v2
    print(v3)
    print('Hello world')
예제 #11
0
def main():
    v1 = Vector2D(2, -2)
    print(v1)
    v2 = Vector2D(2, 3)
    print(v2)
    v3 = v1 + v2
    print(v3)
    print("Hello world")
    print("Another world!")
예제 #12
0
 def __init__(self, position, mass, radius):
     self.position = position
     self.velocity = Vector2D(0, 0)
     self.force = Vector2D(0, 0)
     self.mass = mass
     self.radius = radius
     self.collider_radius = self.radius * 0.5
     self.is_dynamic = True
     self.to_delete = False
     self.check_collisions = True
예제 #13
0
def main():
    app = Game(None)
    platform = Platform(Color(255, 0, 0), Vector2D(350, 550),
                        Vector2D(450, 600), 0)
    app.add_game_object(platform)
    app.add_handler(platform.left_down)
    app.add_handler(platform.left_up)
    app.add_handler(platform.right_down)
    app.add_handler(platform.right_up)
    app.run()
예제 #14
0
    def snowflake(self, x, y, r):
        center = Vector2D(x, y)
        radius = Vector2D(r, 0)

        points = [
                  center + radius.rotate(math.radians(-45)),
                  center + radius.rotate(math.radians(90)),
                  center + radius.rotate(math.radians(-135))
                 ]

        self.curve(points[0], points[2])
        self.curve(points[1], points[0])
        self.curve(points[2], points[1])
예제 #15
0
파일: world.py 프로젝트: Lavertis/snake
 def reset_game(self):
     if self.score > self.highScore:
         self.highScore = self.score
     self.score = 0
     self.snakeElementsToBeAdded = 0
     self.snakeElements.clear()
     self.pushedKeys.clear()
     center = self.mapSize // 2
     head = SnakeElement(self.snakeColour, Vector2D(center, center),
                         Vector2D(0, -1))
     self.snakeElements.append(head)
     for _ in range(2):
         add_next_element(self.snakeElements)
     place_egg(self)
예제 #16
0
    def __init__(self, center: Vector2D, radius: float, velocity: Vector2D = None, color=None):
        Particle.last_particle_id += 1
        self.id = Particle.last_particle_id

        self.radius = radius
        self.center = center

        if (velocity is None):
            velocity = Vector2D()
        self.velocity = velocity
        self.color = color

        self.acceleration = Vector2D()
        self.potential = 0.0
        self.mass = 1
예제 #17
0
파일: action.py 프로젝트: Lavertis/snake
def add_next_element(snakeElements):
    snakeElements.append(deepcopy(snakeElements[-1]))
    tail = snakeElements[-1]

    if tail.colour[2] < 255:
        tail.colour[2] = tail.colour[2] + 1

    if tail.velocity.x > 0:
        tail.position -= Vector2D(1, 0)
    elif tail.velocity.x < 0:
        tail.position += Vector2D(1, 0)
    elif tail.velocity.y > 0:
        tail.position -= Vector2D(0, 1)
    elif tail.velocity.y < 0:
        tail.position += Vector2D(0, 1)
예제 #18
0
 def __init__(self, color: Color, top_left: Vector2D,
              bottom_right: Vector2D, brush_width: int):
     super(Platform, self).__init__(color, top_left, bottom_right,
                                    brush_width)
     self.left_down = KeyboardHandler(self.on_left_key_down, pygame.KEYDOWN,
                                      [ord('a')])
     self.left_up = KeyboardHandler(self.on_left_key_up, pygame.KEYUP,
                                    [ord('a')])
     self.right_down = KeyboardHandler(self.on_right_key_down,
                                       pygame.KEYDOWN, [ord('d')])
     self.right_up = KeyboardHandler(self.on_right_key_up, pygame.KEYUP,
                                     [ord('d')])
     self.max_abs_speed = Vector2D(7, 0)
     self.current_shift = Vector2D(0, 0)
     self.current_speed = Vector2D(0, 0)
예제 #19
0
 def teleport(self, tile_map):
     """Teleports the ghost between one of the tiles outside the tunnel, depending on the current tile position."""
     row = -2 if self.tile_index[1] == 29 else 28
     self.handle_tile_content(tile_map[(self.tile_index[0], row)], tile_map)
     self.prev_tile_index = self.tile_index
     self.tile_index = (self.tile_index[0], row)
     self.position = Vector2D(*settings.get_position(self.tile_index))
예제 #20
0
 def __init__(self, environment):
     self.environment = environment
     self.images = Images(FilePath("data").child("img2"))
     self.images.load()
     self.actions = deque()
     self.action = None
     self.center = Vector2D((0, 0))
예제 #21
0
파일: boid.py 프로젝트: tomdml/boids
    def __init__(self, pos=None, vel=None, color=None):
        self._pos = pos or Vector2D(
            randint(0, Config.SCREEN_X),
            randint(0, Config.SCREEN_Y))

        angle = uniform(-math.pi, math.pi)
        self.vel = vel or Vector2D(
            Config.MAX_SPEED * math.cos(angle),
            Config.MAX_SPEED * math.sin(angle))

        self.color = color or (
            randint(99, 150),
            randint(99, 255),
            randint(200, 255))

        self.turn = 0
예제 #22
0
 def screenCoord(self, p):
     width = self.screen.get_width()
     height = self.screen.get_height()
     (cx, cy) = self.screen.get_rect().center
     return Vector2D((((p.x - self.center[0]) /
                       (self.environment.width / 2)) * width) + cx,
                     (((p.y - self.center[1]) /
                       (self.environment.height / 2)) * height) + cy)
예제 #23
0
 def string2particle(str):
     args = str.split(';')
     return Particle(
         #int(args[0]),
         center=Vector2D(
             float(args[1]),
             float(args[2]),
         ),
         radius=0.5,
         velocity=Vector2D(
             float(args[3]),
             float(args[4]),
         )
         # float(args[5]),
         # float(args[6]),
         # float(args[7]),
     )
예제 #24
0
 def test_mul(self):
     ''' Tests the multiplication operator.
     '''
     result1 = self.v1 * 5
     expected_result1 = Vector2D(0.0, 0.0)
     self.assertEqual(result1, expected_result1)
     result2 = self.v1 * self.v2
     expected_result2 = 0.0
     self.assertEqual(result2, expected_result2)
예제 #25
0
def go_left(snakeElements):
    element_iterator = iter(snakeElements)
    head = next(element_iterator)
    if head.velocity.x == 0:
        change_position_cords = head.position
        head.velocity.set_values(-1, 0)
        for element in element_iterator:
            element.moves_to_make.append(
                Move(change_position_cords, Vector2D(-1, 0)))
예제 #26
0
 def __init__(self, position=(0, 0)):
     super(Ghost, self).__init__()
     self.ID = Ghost.ID
     Ghost.ID += 1
     self.sprites = settings.SPRITES[Ghost.NAME[self.ID]]
     self.image = self.sprites[0]
     self.rect = self.image.get_rect(center=position)
     self.prev_tile_index = (0, 0)
     self.tile_index = settings.get_tile_index(position)
     self.direction = Vector2D(0, 0)
     self.moving = False  # replace with abs(self.direction) == 0
     self.position = Vector2D(*position)
     self.target = self.position
     self.end_target = self.position
     self.time = 0
     self.speed = 80
     self.dead = False
     self.frightened = False
     self.mode = 0
예제 #27
0
 def __init__(self, canvas, length, generations=5, faktor=0.6,
              alphabet='F+-[]', axiom='F', rules={'F': 'FF+[+F-F-F]-[-F+F+F]'}):
         self.canvas = canvas
         self.alphabet = alphabet
         self.axiom = axiom
         self.sentence = axiom
         self.rules = rules # pozor na dict
         self.length = Vector2D(0, length)
         self.faktor = faktor
         self.gens = generations
예제 #28
0
def generate():
    global width, height
    global balls
    for num in range(5):
        ball = Ball(Point2D(0, 0), 0, Vector2D(0, 0), (1, 1, 1))
        colliding = True
        while (colliding):
            radius = randint(1, 10) * 10
            pos = Point2D.randPoint((radius, width - radius),
                                    (radius, height - radius))
            vel = Vector2D(uniform(-3, 3), uniform(-3, 3))
            ball = Ball(pos, radius, vel, (random(), random(), random()))

            colliding = False
            for other in balls:
                if (ball.colliding(other)):
                    colliding = True
                    break
        balls += [ball]
예제 #29
0
    def collide(self, other):
        if not self.colliding(other):
            return

        v1mass = 2 * other.mass() / (self.mass() + other.mass())
        v1posd = Vector2D(self.pos.x - other.pos.x, self.pos.y - other.pos.y)
        v1dot = (self.vel - other.vel).dot(v1posd)
        v1mag = (v1posd).mag() ** 2

        v2mass = 2 * self.mass() / (self.mass() + other.mass())
        v2posd = Vector2D(other.pos.x - self.pos.x,other.pos.y-self.pos.y)
        v2dot = (other.vel - self.vel).dot(v2posd)
        v2mag = (v2posd).mag() ** 2

        self.vel = self.vel - v1mass * v1dot * v1posd / v1mag
        self.update()
        self.__collided = True
        other.vel = other.vel - v2mass * v2dot * v2posd / v2mag
        other.update()
        other.__collided = True
 def set_end_taget(self, tile_map, pacman, ghosts):
     """
     Sets the destination the ghost is heading ultimately. Not to be confused with "set_target" which sets the target
     for the next tile in order to reach the end target.
     """
     if self.dead:
         self.end_target = settings.HOUSE_POS[Ghost.NAME[self.ID]]
     elif tile_map[self.tile_index].is_type(
             "house"
     ):  # If the ghost exit the house it will change end_target.
         self.end_target = Vector2D(224,
                                    232)  # So the ghosts can move outside,
     elif self.frightened:
         # self.end_target = 2 * self.position - pacman.position
         # Added self.position - pacman.position to keep the end_target one tile away from ghost.
         # Else it would enter the end_target when it got eaten and immediately go back.
         self.end_target = 2 * self.position - pacman.position + self.direction * settings.TILE_WIDTH
     elif Ghost.MODE == Ghost.MODES["chase"]:
         if Ghost.NAME[self.ID] == "blinky":
             self.end_target = pacman.position
         elif Ghost.NAME[self.ID] == "inky":
             blinky = None
             for ghost in ghosts:
                 if ghost.ID == 0:
                     blinky = ghost
             a = pacman.position + pacman.direction * settings.TILE_WIDTH * 2  # Two tiles ahead of pacman.
             b = a - blinky.position + a
             self.end_target = b
             # self.end_target = pacman.position + pacman.direction * settings.TILE_WIDTH * 4  # Temp
         elif Ghost.NAME[self.ID] == "pinky":
             # Four tiles ahead of pacman.
             self.end_target = pacman.position + pacman.direction * settings.TILE_WIDTH * 4
         elif Ghost.NAME[self.ID] == "clyde":
             if abs(
                     self.position - pacman.position
             ) > settings.TILE_WIDTH * 8:  # Pacman more than 8 tiles away.
                 self.end_target = pacman.position
             else:
                 self.end_target = Vector2D(8, 560)  # Scatter corner
     else:  # Ghost.MODE == Ghost.MODES["scatter"]:
         self.end_target = Vector2D(*settings.SCATTER_POS[self.ID])