Example #1
0
def setupPlayer(entityManager, screenSize):
	startingPosition = Vector2(20, 20);
	size = Vector2(30, 30);

	player = entityManager.createEntity();
	position = PositionComponent(startingPosition);
	velocity = VelocityComponent();
	force = ForceComponent();
	acceleration = AccelerationComponent();
	mass = MassComponent(100);

	shape = AABBShape(size);
	collision = CollisionComponent(shape);

	display = DisplayComponent((255, 0, 0), "Rect", size);
	controller = PlayerControlledComponent();
	health = HealthComponent(100);

	entityManager.addComponent(player, position);
	entityManager.addComponent(player, velocity);
	entityManager.addComponent(player, force);
	entityManager.addComponent(player, acceleration);
	entityManager.addComponent(player, mass);
	entityManager.addComponent(player, collision);
	entityManager.addComponent(player, display);
	entityManager.addComponent(player, controller);
	entityManager.addComponent(player, health);

	return player;
Example #2
0
class Bullet:
    def __init__(self, (from_x, from_y), (to_x, to_y)):
        self.pos = Vector2(from_x, from_y)
        self.destination = Vector2(to_x, to_y)
        self.heading = Vector2.from_points(self.pos, self.destination)
        self.heading.normalize()
        self.speed = 500  #pixels per second
        self.total_distance = 0
        self.sprite = pygame.image.load(
            '../images/bullet_lvl_2.png').convert_alpha()
        w, h = self.sprite.get_size()
        if w > 10:
            ratio = 10. / w
            h = int(h * ratio)
            self.sprite = pygame.transform.scale(self.sprite, (10, h))
        self.rotation = 0
        to_x = to_x - from_x
        to_y = (to_y - from_y) * -1
        if to_x != 0:
            angle = atan(to_y / to_x) / (pi / 180.)
        else:
            angle = -90
        if to_x < 0:
            angle += 180.
        if to_x >= 0 and to_y < 0:
            angle += 360.
        self.rotation = angle - 90
        self.pos += self.heading * 100  #dodaje dlugos lugy
        self.rotated_sprite = pygame.transform.rotate(self.sprite,
                                                      self.rotation)
        w, h = self.rotated_sprite.get_size()
        self.draw_pos = Vector2(self.pos.x - w / 2, self.pos.y - h / 2)
Example #3
0
def regular_polygon(n, radius=1.0, theta=0.0, centre=Vector2(0,0), grounded = False):
    if grounded:
        theta = -(n-2)*pi/(2*n)
    v = [(i, centre + Vector2(radius*cos(2*pi*i/n + theta),
                              radius*sin(2*pi*i/n + theta)))
         for i in range(n)]
    return tiling2_polygon(v)
def test_add_ShouldReturnResult(vectors):
    v1, v2 = vectors
    expected = Vector2(0, 0)
    assert expected == v1+v2

    expected = Vector2(2, 4)
    assert expected == v1+v1
Example #5
0
def main():
    fpsClock = pygame.time.Clock()

    pygame.init()
    displaySurface = pygame.display.set_mode((screenWidth, screenHeight))
    pygame.display.set_caption(title)

    blue = AABB(Vector2(60, 60), Vector2(140, 60))
    red = AABB(Vector2(300, 180), Vector2(100, 180))

    holdingRect = None
    holdingOffset = Vector2()
    lastMouseState = (False, False, False)

    gameRunning = True
    while (gameRunning):
        for event in pygame.event.get():
            if (event.type == QUIT):
                gameRunning = False

        lastMouseState, holdingRect, holdingOffset = updateMouse(
            lastMouseState, holdingRect, holdingOffset, blue, red, minBounds,
            maxBounds)

        render(displaySurface, blue, red)

        renderMouse(displaySurface, holdingRect, holdingOffset)

        pygame.display.update()
        fpsClock.tick(fps)

    pygame.quit()
    sys.exit()
Example #6
0
def getCloserAndFurtherPoints(aabb, circle):
    closestX = 0
    closestY = 0
    furthestX = 0
    furthestY = 0

    if (circle.centerX < aabb.left):
        closestX = aabb.left
        furthestX = aabb.right
    elif (circle.centerX > aabb.right):
        closestX = aabb.right
        furthestX = aabb.left
    else:
        insideX = True
        closestX = circle.centerX
        furthestX = circle.centerX

    if (circle.centerY < aabb.top):
        closestY = aabb.top
        furthestY = aabb.bottom
    elif (circle.centerY > aabb.bottom):
        closestY = aabb.bottom
        furthestY = aabb.top
    else:
        closestY = circle.centerY
        furthestY = circle.centerY

    return Vector2(closestX, closestY), Vector2(furthestX, furthestY)
Example #7
0
    def __init__(self, images, area, speed, active=False):
        pygame.sprite.Sprite.__init__(self)

        self.images = images
        self.active = active
        self.sprite = pygame.Surface((block_size, block_size * 3), 0, 8)
        self.rect = self.sprite.get_rect()

        self.colors = [
            random.randint(1, 6),
            random.randint(1, 6),
            random.randint(1, 6)
        ]
        #self.colors = [1,1,2]
        self.update_sprite()

        self.locations = [block_size * x + 200 for x in range(0, 6)]
        self.xpos = 2

        self.pos = Vector2((self.locations[self.xpos], block_size))
        self.dir = Vector2((0, 1))

        self.speed = speed
        self.speedup = False

        self.area = area
        self.target = Vector2(self.pos.x, self.area.get_bottom(self.xpos))

        self.terminate = False
Example #8
0
    def move(self, dir):
        if block.terminate:
            return

        x, y = self.pos

        if dir == 1:
            if self.xpos > 0:
                a, b = area.find_loc(
                    (self.locations[self.xpos - 1], self.pos.y))
                if area.data[b][a] == 0:
                    self.xpos -= 1
            else:
                return

        elif dir == 2:
            if self.xpos < 5:
                a, b = area.find_loc(
                    (self.locations[self.xpos + 1], self.pos.y))
                if area.data[b][a] == 0:
                    self.xpos += 1
            else:
                return

        self.target = Vector2(self.locations[self.xpos],
                              self.area.get_bottom(self.xpos))
        self.pos = Vector2((self.locations[self.xpos], y))
Example #9
0
    def add_test(self):
        vector1 = Vector2(1, 1)
        vector2 = Vector2(2, 3)

        vector3 = vector1 + vector2
        self.assertEqual(vector3.x, 3)
        self.assertEqual(vector3.y, 4)
Example #10
0
 def move(self, time_passed_seconds, speed):
     dv = Vector2(self.destination)
     lv = Vector2(self.rect.x, self.rect.y)
     heading = Vector2.from_points(lv, dv)
     heading.normalize()
     d = heading * time_passed_seconds * speed
     self.rect.move_ip(round(d.x), round(d.y))
Example #11
0
 def draw(self, graph_visual):
     self.shape.draw()
     self.border.draw()
     if self.node.parent is not None:
         par = graph_visual.get_visual(self.node.parent)
         line = pygame.draw.lines(
             self.shape.draw_surface, (0, 255, 0), True,
             [[
                 self.shape.position.x_pos + self.shape.scale[0] / 2,
                 self.shape.position.y_pos + self.shape.scale[1] / 2
             ],
              [
                  par.shape.position.x_pos + par.shape.scale[0] / 2,
                  par.shape.position.y_pos + par.shape.scale[1] / 2
              ]], 1)
     if (self.is_open or self.is_closed or self.is_goal
             or self.is_start) and self.show_scores:
         text = Text(Vector2(5, 5), (0, 0, 0), str(self.node.f_score), 12,
                     self.shape.draw_surface)
         text.draw_on_surface(self.shape.rect)
         text2 = Text(Vector2(25, 20), (0, 0, 0), str(self.node.h_score),
                      12, self.shape.draw_surface)
         text2.draw_on_surface(self.shape.rect)
         text3 = Text(Vector2(5, 20), (0, 0, 0), str(self.node.g_score), 12,
                      self.shape.draw_surface)
         text3.draw_on_surface(self.shape.rect)
Example #12
0
def main():
    app = Application(0.1)
    app.update()
    r = Shape(100, 10, 50)
    s = Rectangle(Vector2(100, 100), (150, 100, 150), [50, 50], pygame, 0)
    s.draw()
    l = Line(Vector2(50, 50), (75, 75, 75), [1, 50], pygame)
 def __init__(self, x, y, w, h, color=(255, 255, 255)):
     self.position = Vector2(x, y)
     self.size = Vector2(w, h)
     self.velocity = Vector2()
     self.color = color
     global ID
     self.id = ID
     ID += 1
Example #14
0
File: board.py Project: rurush47/go
 def get_surrounding_points_list(state, position):
     points_to_check = [
         position + Vector2(0, 1), position + Vector2(-1, 0),
         position + Vector2(1, 0), position + Vector2(0, -1)
     ]
     points_to_check = filter(lambda x: Board.in_bounds(state, x),
                              points_to_check)
     return points_to_check
Example #15
0
 def __init__(self, rect):
     lines = [
         Vector2(rect.left, rect.top),
         Vector2(rect.right, rect.top),
         Vector2(rect.right, rect.bottom),
         Vector2(rect.left, rect.bottom)
     ]
     PolyCollider.__init__(self, lines)
Example #16
0
 def start(self) -> None:
     y_direction = randint(0, self.screen_rect.bottom)
     x_direction = randint(0, self.screen_rect.right)
     destination = Vector2(x_direction, y_direction) - (Vector2(5, 5) / 2)
     heading = Vector2.from_points(self.screen_rect.center, destination)
     heading.normalize()
     self.ball.direction = heading
     self.game_state = GameState.RUNNING
     self.started_at = datetime.now()
Example #17
0
    def __init__(self, x, y):
        """ create a new boid at x,y """
        self.neighbors = 0

        self.position = Vector2(x, y)
        self.acceleration = Vector2(0, 0)
        self.velocity = Vector2(
            random.uniform(-self.max_speed, self.max_speed),
            random.uniform(-self.max_speed, self.max_speed))
Example #18
0
 def __init__(self, parent=None):
     self.Position = Vector2(0, 0)
     self.width = 0
     self.height = 0
     self.Direction = Vector2(0, 0)
     self.sprite = None
     self.type = Constants.ObjectType.Null
     self.subObjects = list()
     self.parent = parent
Example #19
0
def periodic_copies(tiling2, bounding_box,
                    periods=[Vector2(1,0), Vector2(0,1)]):
    gen = LatticeSearcher(len(periods))
    for n in gen:
        t1 = tiling2.translate(sum((u*c for (u,c) in zip(periods, n)), Vector2(0,0)))
        if t1.in_box(bounding_box):
            yield t1
        else:
            gen.reject()
Example #20
0
def triangular_tiling(bounding_box):
    periods = [Vector2(1,0),Vector2(0.5,3**0.5/2)] # _ and /
    fundamental_vertex = {(): Vector2(0,0)}
    fundamental_edges = {(1,):[((),(0,0)), ((),(0,1))], #/
                         (2,):[((),(0,0)), ((),(1,0))], #-
                         (3,):[((),(0,1)),((),(1,0))]}  #\
    fundamental_faces = {True:[((1,),(0,0)),((2,),(0,0)),((3,),(0,0))],
                         False:[((1,),(1,0)),((2,),(0,1)),((3,),(0,0))]}
    return periodic_tiling2(fundamental_vertex,fundamental_edges,fundamental_faces,bounding_box,periods)
Example #21
0
	def update(self, deltaTime):
		for entity in self.getAllEntitiesPossessingComponents(PlayerControlledComponent, ForceComponent): #, VelocityComponent):
			controller = self.getComponent(entity, PlayerControlledComponent);
			#velocityComponent = self.getComponent(entity, VelocityComponent);
			forceComponent = self.getComponent(entity, ForceComponent);

			controls = controller.controls;

			keys = pygame.key.get_pressed();
			dx = 0;
			dy = 0;
			if (keys[controls["up"]]):
				dy -= 1;
			if (keys[controls["down"]]):
				dy += 1;
			if (keys[controls["left"]]):
				dx -= 1;
			if (keys[controls["right"]]):
				dx += 1;

			# speed = 200.0;
			# velocityComponent.velocity = Vector2(dx, dy).setMagnitudeTo(speed);

			forceComponent.force += Vector2(dx, dy) * 10000#0;

		for entity in self.getAllEntitiesPossessingComponents(AIControlledComponent, PositionComponent, VelocityComponent):
			controller = self.getComponent(entity, AIControlledComponent);
			positionComponent = self.getComponent(entity, PositionComponent);
			velocityComponent = self.getComponent(entity, VelocityComponent);

			players = self.getAllEntitiesPossessingComponents(PlayerControlledComponent, PositionComponent);
			if (len(players) > 0):
				# Ugly hack
				# Would be fixed with a tag system
				player = players.pop();

				playerPositionComponent = self.getComponent(player, PositionComponent);

				direction = playerPositionComponent.position - positionComponent.position;
				speed = 100.0;
				vecToMove = direction.setMagnitudeTo(speed);
				velocityComponent.velocity = vecToMove;
			else:
				velocityComponent.velocity = Vector2(0, 0);


		for entity in self.getAllEntitiesPossessingComponents(HealthComponent):
			healthComponent = self.getComponent(entity, HealthComponent);

			healthComponent.health -= 5 * deltaTime;

			if (healthComponent.health <= 0):
				healthComponent.health = 0;
				self.entityManager.removeComponent(entity, PlayerControlledComponent);
				self.entityManager.removeComponent(entity, VelocityComponent);
				self.entityManager.getComponent(entity, DisplayComponent).colour = (128, 128, 128);
Example #22
0
	def GetPieceLocations(self):
		if self.size is None or self.origin is None or self.vertical is None:
			raise Exception('Attempt to get piece locations of uninitialized ship.')
		if not self.pieceLocations is None:
			return self.pieceLocations
		locationAddend = Vector2(1, 0)
		if self.vertical:
			locationAddend = Vector2(0, 1)
		self.pieceLocations = [ self.origin + locationAddend * length for length in range(self.size) ]
		return list(self.pieceLocations)
Example #23
0
    def test_in_bounds(self):
        Board.size = 9
        b = Board()
        pos1 = Vector2(2, 3)
        pos2 = Vector2(10, 4)
        pos3 = Vector2(-1, 5)

        self.assertEquals(b.in_bounds(pos1), True)
        self.assertEquals(b.in_bounds(pos2), False)
        self.assertEquals(b.in_bounds(pos3), False)
Example #24
0
    def test_is_empty(self):
        Board.size = 9
        b = Board()
        pos1 = Vector2(2, 3)
        pos2 = Vector2(3, 4)

        b.board[2][3] = StoneColor.BLACK

        self.assertEquals(b.is_empty(pos1), False)
        self.assertEquals(b.is_empty(pos2), True)
Example #25
0
 def lineIntersects(self, A, B):
     v = B - A
     w = self.center - A
     t = Vector2.dot(v, w) / Vector2.dot(v, v)
     if t > 1:
         t = 1
     elif t < 0:
         t = 0
     closest = A + (v * t)
     return closest, self.pointIn(closest)
Example #26
0
 def lineIntersects(self,A,B):
     v = B - A
     w = self.center - A
     t = Vector2.dot(v,w) / Vector2.dot(v,v)
     if t > 1:
         t = 1
     elif t < 0:
         t = 0
     closest = A + (v*t)
     return closest,self.pointIn(closest)
 def __init__(self, id, origen, destino, velocidad, color):
     super(Particula, self).__init__()
     self.id = id
     self.origen = Vector2(origen[0], origen[1])
     self.destino = Vector2(destino[0], destino[1])
     self.velocidad = velocidad
     self.color = Color(color[0], color[1], color[2])
     self.distancia = int(
         math.sqrt((self.destino.x - self.origen.x)**2 +
                   ((self.destino.y - self.origen.y)**2)))
Example #28
0
    def __init__(self, world, name, image):
 
        self.world = world
        self.name = name
        self.image = image
        self.location = Vector2(0, 0)
        self.destination = Vector2(0, 0)
        self.speed = 0.
        self.brain = StateMachine()
        self.id = 0
Example #29
0
    def test_valid_states_generator(self):
        Board.size = 2
        b = Board()

        generator = b.valid_states_generator(StoneColor.BLACK)

        move1 = generator.next()
        move2 = generator.next()

        self.assertEqual(move1[0], Vector2(0, 0))
        self.assertEqual(move2[0], Vector2(0, 1))
 def __init__(self, algorithm, screen):
     '''function to initialize the values for the visual algorithm'''
     self.algorithm = algorithm
     self.screen = screen
     self.visual_grid = VisualGraph(self.algorithm.grid, 35, screen)
     self.visual_grid.gen_visual()
     self.algorithm.path()
     self.start_node_visual = DragableRect(self.screen, Vector2
                                           (900, 400), [30, 30], (93, 255, 115))
     self.end_node_visual = DragableRect(self.screen, Vector2
                                         (900, 450), [30, 30], (252, 130, 65))
Example #31
0
def hexagonal_tiling(bounding_box):
    periods = [Vector2(0,3**0.5), Vector2(1.5,3**0.5/2)]
    fundamental_vertices = {True: Vector2(0,0),   # >-
                            False: Vector2(1,0)}  # -<
    fundamental_edges = {1:[(True, (0,0)), (False, (0,0))],
                         2:[(True, (0,0)), (False, (0,-1))],
                         3:[(True, (0,0)), (False, (1,-1))]}
    fundamental_faces = {():[(1,(0,0)), (2,(0,1)), (3,(0,1)),
                             (1,(1,0)), (2,(1,0)), (3,(0,0))]}
    return periodic_tiling2(fundamental_vertices,fundamental_edges,
                            fundamental_faces,bounding_box,periods)
Example #32
0
 def move(self, time_passed_seconds, speed):
     dv = Vector2(self.destination)
     lv = Vector2(self.rect.x, self.rect.y)
     heading = Vector2.from_points(lv, dv)
     heading.normalize()
     d = heading * time_passed_seconds * speed
     self.rect.move_ip(round(d.x), round(d.y))
Example #33
0
 def update(self, delta):
     if self.last_location:
         self.last_vector = Vector2.from_points(self.last_location, (self.rect.x, self.rect.y))
     
     self.rect.move_ip((self.randirx, self.randiry))
     
     center = self.rect.center
     self.image = pygame.transform.rotate(self.original, self.rotation)
     self.rect = self.image.get_rect(center=center)
     self.bounding = self.rect.inflate(-self.rect.width/2.25, -self.rect.height/2.25) 
     
     self.last_location = (self.rect.x, self.rect.y)
Example #34
0
    def _calculate_destination(self, mouse_pos):
        """
        Figure out the destination coords for the bullet, starting from the
        center of the screen through the point the player click, to the edge
        of the screen.
        """
        dx,dy = mouse_pos

        step = Vector2.from_points((WINDOWWIDTH/2,WINDOWHEIGHT/2),
                                   (dx,dy)) * 0.1
        while True:
            if dx > WINDOWWIDTH or dy > WINDOWHEIGHT or dx < 0 or dy < 0:
                break
            dx += step.x
            dy += step.y

        return (dx, dy)
Example #35
0
 def getBoundingRadius(self):
     return Vector2.distance(self.corners[0], self.center)
Example #36
0
position = Vector2(100.0, 100.0)
heading = Vector2()

while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            exit()

    screen.blit(background, (0,0))
    screen.blit(sprite, position)

    time_passed = clock.tick(100)
    time_passed_seconds = time_passed / 1000.0

    # 参数前面加*意味着把列表或元组展开
    destination = Vector2( *pygame.mouse.get_pos() ) - Vector2( *sprite.get_size() )
    # 计算鱼儿当前位置到鼠标位置的向量
    vector_to_mouse = Vector2.from_points(position, destination)
    # 向量规格化
    vector_to_mouse.normalize()

    # 这个heading可以看做是鱼的速度,但是由于这样的运算,鱼的速度就不断改变了

    # 在没有到达鼠标时,加速运动,超过以后则减速。因而鱼会在鼠标附近晃动。
    heading = heading + (vector_to_mouse * .6)
    # position=heading + (vector_to_mouse * time_passed_seconds)
    position += heading * time_passed_seconds
    # position +=vector_to_mouse*0.5
    pygame.display.update()
Example #37
0
 def pointIn(self,point):
     return Vector2.distance(self.center,point) < self.radius
Example #38
0
 def testPoint(self, point):
     return Vector2.distance(point, self._center) < self._radius
Example #39
0
 def go_to(self, x, y):
     actual = (self.x, self.y)
     to = (x, y)
     self.direction = Vector.from_points(actual, to)
     self.direction.normalise()
     print self.direction.x