示例#1
0
    def __init__(self, position_x_y, lenght_x_y, color):
        #
        self.position = position_x_y
        self.oldlenght = lenght_x_y

        self.lenght = self.oldlenght + self.position

        # All Entity corner, it's a vector2 position on screen
        self.upperleftcorner = self.position
        self.downleftcorner = self.position + Vec2(0, self.oldlenght.y)
        self.upperrightcorner = self.position + Vec2(self.oldlenght.x, 0)
        self.downrightcorner = self.position + \
            Vec2(self.oldlenght.x, self.oldlenght.y)
        self.corners = [
            self.upperleftcorner, self.upperrightcorner, self.downleftcorner,
            self.downrightcorner
        ]

        # The 4 wall of the entity, it's two vector2
        self.upwall = (self.upperleftcorner, self.upperrightcorner)
        self.rightwall = (self.upperrightcorner, self.downrightcorner)
        self.downwall = (self.downrightcorner, self.downleftcorner)
        self.leftwall = (self.downleftcorner, self.upperleftcorner)
        self.walls = [
            self.upwall, self.rightwall, self.downwall, self.leftwall
        ]

        self.color = color
示例#2
0
def main():
    pygame.init()
    dims = Vec2(240, 160)
    window = pygame.display.set_mode((dims.x * square_size, dims.y * square_size))
    grid = Grid(dims, window)
    pygame.display.set_caption("Maze")
    maze_generator = MazeGenerator(grid)
    astar = AStar(grid, Vec2(0, 0), grid.dims - Vec2(2, 2))
    running = True
    clock = pygame.time.Clock()

    while running:

        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                running = False
            if e.type == pygame.KEYDOWN:
                if e.key == pygame.K_SPACE:
                    astar.step()

        if not maze_generator.finished():
            maze_generator.step()

        if maze_generator.finished():
            astar.step()

        if not maze_generator.finished():
            draw_cell(window, maze_generator.current_cell(), colors.red)

        pygame.display.update()
        # clock.tick(60)

    pygame.quit()
示例#3
0
    def init_pixels(self, surface=None):
        self.pixels.clear()

        if surface is None:
            # Alocate memory for the pixels
            for y in range(self.size.y):
                self.pixels.append([])

                for x in range(self.size.x):
                    self.pixels[y].append(None)

            self.clear(WHITE)
        else:
            # Load image (for example .png)
            self.surface = surface.copy()
            self.size = Vec2(self.surface.get_width(),
                             self.surface.get_height())
            self.scaled_size = Vec2(self.size.x * self.zoom,
                                    self.size.y * self.zoom)
            self.origin = Vec2(self.size.x / 2, self.size.y / 2)
            self.scaled_origin = Vec2(self.origin.x * self.zoom,
                                      self.origin.y * self.zoom)

            for y in range(self.size.x):
                self.pixels.append([])

                for x in range(self.size.y):
                    color = surface.get_at((x, y))
                    self.pixels[y].append(Pixel(Vec2(x, y), color.copy()))

            self.update_pixels()
示例#4
0
 def __init__(self, position, velocity=Vec2(0, 0), mass=1):
     self.position = position
     self.velocity = velocity
     self.forces = Vec2()
     self.static_forces = Vec2()
     self.mass = mass
     self.connections = []
     super().__init__()
示例#5
0
    def get_inside_mouse_pos(self, x, y):
        relative_pos = Vec2(x - (self.pos.x - self.scaled_origin.x),
                            y - (self.pos.y - self.scaled_origin.y))
        converted_pos = Vec2(
            clamp(int(relative_pos.x / self.zoom), 0, self.size.x - 1),
            clamp(int(relative_pos.y / self.zoom), 0, self.size.y - 1))

        return converted_pos
 def get_unvisited(self):
     unvisited = []
     current = self.current_cell()
     for direction in [Vec2(2, 0), Vec2(0, 2), Vec2(-2, 0), Vec2(0, -2)]:
         if current + direction < self.grid.dims and current + direction >= Vec2(
                 0, 0):
             if self.grid.get_cell(current + direction) == colors.black:
                 unvisited.append(direction)
     return unvisited
示例#7
0
 def __init__(self, world, pos, d, index):
     Entity.__init__(self, world, pos, Vec2(d * 0.6, 0))
     self.gravity = Vec2(0, 0)
     self.anim = Anim("png/Objects/Bullet_00%s.png".__mod__, 0, 4, (15, 15),
                      True, 10)
     self.d = d
     self.index = index
     self.damage = 5
     self.shown = True
示例#8
0
 def get_cells(self):
     for direction in [Vec2(1, 0), Vec2(0, 1), Vec2(-1, 0), Vec2(0, -1)]:
         test = self.current.coord + direction
         if test >= self.grid.dims and test < Vec2(0, 0):
             continue
         if not self.grid.get_cell(test) in [colors.white, colors.green]:
             continue
         self.grid.set_cell(test, colors.green)
         self.open.append(CellData(test, self.end, self.current))
示例#9
0
 def __init__(self, world, pos, vel=Vec2(0, 0)):
     self.pos = pos
     self.vel = vel
     self.acc = Vec2(0, 0)
     self.gravity = Vec2(0, 0.01)
     self.image = None
     self.paused = False
     self.world = world
     self.health = 0
示例#10
0
 def set(self, verts):
     rightMost = 0
     highestXCoord = verts[0].x
     for i in range(len(verts)):
         x = verts[i].x
         if x > highestXCoord:
             highestXCoord = x
             rightMost = i
         elif x == highestXCoord:
             if verts[i].y < verts[rightMost].y:
                 rightMost = i
     
     hull = [0] * Polygon.MAX_POLY_VERTEX_COUNT
     outCount = 0
     indexHull = rightMost
     nextHullIndex = 0
     
     while True:
         hull[outCount] = indexHull
         nextHullIndex = 0
         for i in range(len(verts)):
             if nextHullIndex == indexHull:
                 nextHullIndex = i
                 continue
             
             e1 = verts[nextHullIndex] - verts[hull[outCount]]
             e2 = verts[i] - verts[hull[outCount]]
             c = cross(e1, e2)
             if  c < 0:
                 nextHullIndex = i
                 
             if c == 0 and e2.lengthSq() > e1.lengthSq():
                 nextHullIndex = i
                 
         outCount += 1
         
         indexHull = nextHullIndex
         
         if nextHullIndex == rightMost:
             self.vertexCount = outCount
             break
     
     #copy vertices into shape's vertices
     #print(verts)
     #print("len verts:", len(verts))
     #print("vertexCount:", self.vertexCount)
     
     for i in range(self.vertexCount):
         #print("i:", i)
         self.vertices.append(Vec2( verts[hull[i]]))
         
     # Compute face normals    
     for i in range(self.vertexCount):
         face = self.vertices[(i+1)%self.vertexCount] - self.vertices[i]
         self.normals.append(Vec2(face.y, -face.x))
         self.normals[i].normalize()
示例#11
0
def get_line_pixels(start_pos: Vec2, end_pos: Vec2) -> []:
    start_pos.x = round(start_pos.x)
    start_pos.y = round(start_pos.y)
    end_pos.x = round(end_pos.x)
    end_pos.y = round(end_pos.y)

    dist = Vec2(
        end_pos.x - start_pos.x,
        end_pos.y - start_pos.y
    )

    if abs(dist.x) > abs(dist.y):
        steps = abs(dist.x)
    else:
        steps = abs(dist.y)
    
    if steps == 0:
        return [start_pos.copy()]

    increment = Vec2(
        dist.x / (steps),
        dist.y / (steps)
    )

    pixels = []
    pos = start_pos.copy()
    for i in range(steps):
        pos.x += increment.x
        pos.y += increment.y
        pixels.append(Vec2(round(pos.x), round(pos.y)))
    
    return pixels
示例#12
0
    def draw(self):
        self.surface.blit(self.bg, tuple(self.bga))
        self.surface.blit(self.bg, tuple(self.bga - Vec2(self.width, 0)))
        self.surface.blit(self.bg, tuple(self.bga + Vec2(self.width, 0)))
        self.surface.blit(
            self.font.render("Score: %s" % self.kills, True, (0, 0, 0)),
            (10, 10))

        for obj in self.objects:
            obj.draw(self.surface)

        self.player.draw(self.surface)
示例#13
0
 def __init__(self, a, b):
     if not isinstance(a, Body) or  not isinstance(b, Body):
         raise NotImplement
     
     self.A = a
     self.B = b
     self.penetration = 0
     self.impulse_normal = Vec2()
     self.contact_points = [Vec2(), Vec2()]
     self.contactCount = 0
     self.e = RESTITUTION
     self.sf = STATIC_FRICTION
     self.df = DYNIMIC_FRICTION
示例#14
0
    def __init__(self,
                 image,
                 position=Vec2(0, 0),
                 velocity=Vec2(0, 0),
                 rotation=0.0,
                 angular_velocity=0.0):
        super().__init__()

        self.original_img = image
        self.rect = self.original_img.get_rect()

        self.position = position
        self.velocity = velocity
        self.angular_velocity = angular_velocity
        self.rotation = rotation
示例#15
0
    def __init__(self, position=Vec2(200, 100)):
        super().__init__(image=content.get_image("data/ship01.png"),
                         position=position)

        self.angular_acceleration = 0.1
        self.max_angular_velocity = 120.0 * self.angular_acceleration
        self.acceleration = 0.1
示例#16
0
 def __init__(self, world, pos):
     Entity.__init__(self, world, pos, Vec2(0, 0))
     self.size = (100, 100)
     self.runspeed = 0.3
     self.jumpspeed = 0.3
     self.runanim = Anim("png/Run (%s).png".__mod__, 1, 8, self.size, True,
                         15)
     self.idleanim = Anim("png/Idle (%s).png".__mod__, 1, 10, self.size,
                          True, 15)
     self.jumpanim = Anim("png/Jump (%s).png".__mod__, 1, 10, self.size,
                          False, 10)
     self.shootanim = Anim("png/Shoot (%s).png".__mod__, 1, 4, self.size,
                           False, 15, self.resetanim)
     self.runshootanim = Anim("png/RunShoot (%s).png".__mod__, 1, 9,
                              self.size, False, 15, self.resetanim)
     self.jumpshootanim = Anim("png/JumpShoot (%s).png".__mod__, 1, 5,
                               self.size, False, 15, self.resetanim)
     self.slideanim = Anim("png/Slide (%s).png".__mod__, 1, 10, self.size,
                           False, 10, self.resetanim)
     self.dieanim = Anim("png/Dead (%s).png".__mod__, 1, 10, self.size,
                         False, 15)
     self.jumpmeleeanim = Anim("png/JumpMelee (%s).png".__mod__, 1, 8,
                               self.size, False, 15, self.resetanim)
     self.meleeanim = Anim("png/Melee (%s).png".__mod__, 1, 8, self.size,
                           False, 15, self.resetanim)
     self.anim = self.idleanim
     self.facing = RIGHT
     self.ground = self.pos.y
     self.maxhealth = 20
     self.health = self.maxhealth
     self.shootsound = WavePlayer('sounds/shoot.wav')
     self.jumpsound = WavePlayer('sounds/jump.wav')
     self.meleedamage = 10
示例#17
0
 def __iter__(self):
     cells = []
     for x in range(self.dims.x):
         for y in range(self.dims.y):
             coord = Vec2(x, y)
             cells.append((coord, self.get_cell(coord)))
     return iter(cells)
示例#18
0
    def clear(self, color: Vec4):
        for y in range(self.size.y):
            for x in range(self.size.x):
                self.pixels[y][x] = Pixel(Vec2(x, y), color.copy())

        self.surface.fill(color.as_tuple())
        self.changed_pixels.clear()
示例#19
0
def handle_event():
    for event in pygame.event.get():
        if event.type == QUIT:
            Game.done = True
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                Game.done = True
            elif event.key == K_LEFT:
                o = Game.seasaw.orient - 0.1
                Game.seasaw.setOrient(o)
            elif event.key == K_RIGHT:
                o = Game.seasaw.orient + 0.1
                Game.seasaw.setOrient(o)
        #elif event.type == MOUSEBUTTONDOWN:

    b1, b2, b3 = pygame.mouse.get_pressed()
    if b1:
        Game.counter += 1
        if Game.counter % 7 == 0:
            mouseX, mouseY = pygame.mouse.get_pos()
            #size =  randint(10,40)
            #b = Body(Circle(size), mouseX, Game.screen_size[1]-mouseY)
            #verts = []
            #vertCount = randint(3, Polygon.MAX_POLY_VERTEX_COUNT)
            #for i in range(vertCount):
            #    verts.append(Vec2(randrange(-40,40), randrange(-40,40)))
            hw = randrange(10, 40)
            hh = randrange(10, 40)

            #b = Body(Polygon(verts=verts), mouseX, Game.screen_size[1]-mouseY)
            b = Body(Polygon(boxHw=hw, boxHh=hh), mouseX, mouseY)
            #b.setOrient(1.5)

            Game.bodies.append(b)
            #print("vertices:",b.shape.vertices)
            #print("normals:", b.shape.normals)
    elif b2:
        Game.counter += 1
        if Game.counter % 7 == 0:
            mouseX, mouseY = pygame.mouse.get_pos()

            verts = []
            vertCount = randint(3, Polygon.MAX_POLY_VERTEX_COUNT)
            for i in range(vertCount):
                verts.append(Vec2(randrange(-40, 40), randrange(-40, 40)))

            b = Body(Polygon(verts=verts), mouseX, mouseY)

            Game.bodies.append(b)
            #print("vertices:",b.shape.vertices)
            #print("normals:", b.shape.normals)

    elif b3:
        Game.counter += 1
        if Game.counter % 7 == 0:
            mouseX, mouseY = pygame.mouse.get_pos()
            size = randint(10, 40)
            b = Body(Circle(size), mouseX, mouseY)
            Game.bodies.append(b)
示例#20
0
    def __mul__(self, other):
        if not isinstance(other, Vec2):
            raise NotImplement

        out = Vec2()
        out.x = self.m00 * other.x + self.m01 * other.y
        out.y = self.m10 * other.x + self.m11 * other.y
        return out
示例#21
0
 def spawnpickup(self):
     if self.player.paused: return
     z = HealthPickup(
         self,
         Vec2(self.player.pos.x + random.choice([300, -300]),
              self.player.pos.y))
     z.load()
     self.objects.append(z)
示例#22
0
 def setBox(self, hw, hh):
     self.vertexCount = 4
     self.vertices.append(Vec2(-hw, -hh))
     self.vertices.append(Vec2(hw, -hh))
     self.vertices.append(Vec2(hw, hh))
     self.vertices.append(Vec2(-hw, hh))
     self.normals.append(Vec2(0, -1))
     self.normals.append(Vec2(1, 0))
     self.normals.append(Vec2(0, 1))
     self.normals.append(Vec2(-1, 0))
示例#23
0
    def draw(self, screen):
        """Draw the gameobject."""
        middle = Vec2(self.pos.xpos + self.surface.get_width() / 2,
                      self.pos.ypos + self.surface.get_height() / 2)

        lineseek = Vec2(middle.xpos + self.velocity.direction.xpos * self.velocity.get_mag(),
                        middle.ypos + self.velocity.direction.ypos * self.velocity.get_mag())
        lineflee = Vec2(middle.xpos + self.velocity.direction.xpos * self.velocity.get_mag() * -1,
                        middle.ypos + self.velocity.direction.ypos * self.velocity.get_mag() * -1)
        linewander = Vec2(middle.xpos + self.wanderforce.xpos / 6,
                          middle.ypos + self.wanderforce.ypos / 6)

        pygame.draw.line(screen, RED, middle.value, lineflee.value, 2)
        pygame.draw.line(screen, BLUE, middle.value, lineseek.value, 2)
        pygame.draw.line(screen, PINK, middle.value, linewander.value, 2)

        textpos = "Pos: <{:0.5}{}{:1.5}>".format(
            self.pos.xpos, ", ", self.pos.ypos)
        surfacep = self.font.render(textpos, True, (0, 0, 0))
        screen.blit(surfacep, (self.pos.xpos - 50, self.pos.ypos + 50))

        targetpos = "TargetPos: <{0:.5} {1:.5}>".format(
            str(self.targetpos.xpos), str(self.targetpos.ypos))
        surfacet = self.font.render(targetpos, True, (0, 0, 0))
        screen.blit(surfacet, (self.pos.xpos - 50, self.pos.ypos + 60))

        velpos = "Velocity: <{0:.5} {1:.5}>".format(
            str(self.velocity.xpos), str(self.velocity.ypos))
        surfacev = self.font.render(velpos, True, (0, 0, 0))
        screen.blit(surfacev, (self.pos.xpos - 50, self.pos.ypos + 70))

        howpos = "Steering Behavior created by Williams, Donray"
        surfaceh = self.font.render(howpos, True, (0, 0, 0))
        screen.blit(surfaceh, (screen.get_width() / 2 + 10, 30))

        inspos = "F1 = Seek / F2 = Flee / F3 = Wander / F4 = All"
        surfaceh = self.font.render(inspos, True, (0, 0, 0))
        screen.blit(surfaceh, (screen.get_width() / 2 + 10, 40))

        rotate = pygame.transform.rotate(
            self.surface, -180 * math.atan2(self.heading[1], self.heading[0]) /
            math.pi)
        self.heading = Vec2.get_direction(self.velocity)

        screen.blit(rotate, (self.pos.xpos, self.pos.ypos))
示例#24
0
 def shoot(self):
     if self.pos.y < self.ground:
         self.anim = self.jumpshootanim
     elif abs(self.world.bgv.x) > 0:
         self.anim = self.runshootanim
     else:
         self.anim = self.shootanim
     self.anim.face(self.facing)
     self.anim.reset()
     if self.facing == RIGHT:
         b = Bullet(self.world, self.pos + Vec2(70, 45), 1,
                    len(self.world.objects))
     elif self.facing == LEFT:
         b = Bullet(self.world, self.pos + Vec2(0, 45), -1,
                    len(self.world.objects))
     b.load()
     self.world.objects.append(b)
     if self.world.sfx: self.shootsound.play()
示例#25
0
    def __init__(self, shape, posX, posY, orient=0, density=1):
        self.shape = shape
        self.pos = Vec2(posX, posY)
        self.velocity = Vec2(0, 0)
        self.force = Vec2(0, 0)

        self.angularVelocity = 0
        self.torque = 0
        self.orient = orient
        self.mass = 0
        self.invMass = 0
        self.inertia = 0
        self.invInertia = 0
        self.staticFriction = 0.4
        self.dynamicFriction = 0.3
        self.restitution = RESTITUTION

        self.shape.computeMass(density, self)
        self.shape.setOrient(self.orient)
示例#26
0
def min_disk(points):
    points_vec2 = points
    if not isinstance(points[0], Vec2):
        points_vec2 = Vec2.from_tuple_array(points)

    points_len = len(points_vec2)
    if points_len < 2:
        return None
    else:
        return min_disk_recursive(points_vec2[:])
示例#27
0
 def __init__(self, parent, data):
     self.parent = parent
     count = unpack('H', data[:2])[0]
     data = data[2:]
     self.texcoords = []
     for i in range(count):
         x, y = unpack('ff', data[:8])
         data = data[8:]
         self.texcoords.append(Vec2(x, 1.0 - y))
     self.size = 2 + count * 2 * 4
示例#28
0
 def __init__(self, position):
     """Initialize."""
     self.pos = position
     self.velocity = Vec2(0, 0)
     self.acceleration = Vec2(0, 0)
     self.targetpos = Vec2(0, 0)
     self.force = Vec2(0, 0)
     self.wander_angle = 45.0
     self.heading = Vec2(0, 0)
     self.max_velocity = 100
     self.direction = self.velocity.direction
     self.surface = pygame.Surface((45, 25), pygame.SRCALPHA)
     pygame.draw.lines(self.surface, random.choice((BLACK, BLUE, PINK, MAROON, GREEN)),
                       True, [(1, 1), (15, 25), (25, 1)], 2)
     pygame.draw.circle(self.surface, RED, (25, 3), 3)
     self.font = pygame.font.SysFont('mono', 12)
     self.wanderforce = None
     self.indseek = False
     self.indflee = False
     self.indwander = False
示例#29
0
 def drawhealthbar(self, surface):
     ap = self.pos + self.world.bgx + Vec2(10, 0)
     surface.fill((0, 0, 0), (ap.x - 1, ap.y - 10, 66, 5))
     hp = self.health / self.maxhealth
     if hp > 0.66:
         hc = (0, 255, 0)
     elif hp > 0.33:
         hc = (255, 165, 0)
     else:
         hc = (255, 0, 0)
     surface.fill(hc, (ap.x, ap.y - 9, hp * 64, 3))
示例#30
0
    def update(self):
        self.lenght = self.oldlenght + self.position
        self.upperleftcorner = self.position
        self.upperrightcorner = self.position + Vec2(self.oldlenght.x, 0)
        self.downleftcorner = self.position + Vec2(0, self.oldlenght.y)
        self.downrightcorner = self.position + \
            Vec2(self.oldlenght.x, self.oldlenght.y)

        # All Entity corner, it's a vector2 position on screen
        self.upperleftcorner = self.position
        self.downleftcorner = self.position + Vec2(0, self.oldlenght.y)
        self.upperrightcorner = self.position + Vec2(self.oldlenght.x, 0)
        self.downrightcorner = self.position + \
            Vec2(self.oldlenght.x, self.oldlenght.y)
        self.corners = [
            self.upperleftcorner, self.upperrightcorner, self.downleftcorner,
            self.downrightcorner
        ]

        # The 4 wall of the entity, it's two vector2
        self.upwall = (self.upperleftcorner, self.upperrightcorner)
        self.rightwall = (self.upperrightcorner, self.downrightcorner)
        self.downwall = (self.downrightcorner, self.downleftcorner)
        self.leftwall = (self.downleftcorner, self.upperleftcorner)
        self.walls = [
            self.upwall, self.rightwall, self.downwall, self.leftwall
        ]
示例#31
0
 def spawnzombie(self):
     if self.player.paused: return
     if random.random() < 0.1:
         c = BigZombie
     else:
         c = Zombie
     z = c(
         self,
         Vec2(self.player.pos.x + random.choice([400, -400]),
              self.player.ground), c)
     z.load()
     self.zombies.append(z)
     self.objects.append(z)