예제 #1
0
 def acceleration(self, pos, d):
     A = -G * (pos + np.array([d, 0.0, 0.0])) * (self.mass / 2) / (
         v.length(pos + np.array([d, 0.0, 0.0]))**3
     )  # first mass contibution
     B = -G * (pos + np.array([-d, 0.0, 0.0])) * (self.mass / 2) / (
         v.length(pos + np.array([-d, 0.0, 0.0]))**3
     )  # second mass contibution
     return A + B  # full acceleration
예제 #2
0
 def acceleration_rotational(self, pos, d, angle):
     x_r = d * math.cos(angle)
     y_r = d * math.sin(angle)
     A = -G * (pos + np.array([x_r, y_r, 0.0])) * (self.mass / 2) / (
         v.length(pos + np.array([x_r, y_r, 0.0]))**3
     )  # first mass contibution
     B = -G * (pos + np.array([-x_r, -y_r, 0.0])) * (self.mass / 2) / (
         v.length(pos + np.array([-x_r, -y_r, 0.0]))**3
     )  # second mass contibution
     return A + B  # full acceleration
예제 #3
0
    def _localVertices(self):
        w, h = self.size[0], self.size[1]
        rot = self.rot
        radius = vectors.length((0, 0), (w, h)) / 2

        # top right corner
        #  ______
        # |     /|
        # |    / | 
        # |   /__|    
        # |a     |
        # |      |
        # |______|

        a = math.asin(h/(2 * radius))
        #c = (radius * round(cos(rot + a), 2), radius * round(sin(rot + a), 2)) 
        c = vectors.component(radius, rot + a)
        v = [(c[0], c[1])]

        # top left corner
        #c = (radius * round(cos(rot + pi - a), 2), radius * round(sin(rot + pi - a), 2)) 
        c = vectors.component(radius, rot + (math.pi - a))
        v.append((c[0], c[1]))

        # bottom left corner
        #c = (radius * round(cos(rot + pi + a), 2), radius * round(sin(rot + pi + a), 2)) 
        c = vectors.component(radius, rot + (math.pi + a))
        v.append((c[0], c[1]))
    
        # bottom right corner
        #c = (radius * round(cos(rot - a), 2), radius * round(sin(rot - a), 2)) 
        c = vectors.component(radius, rot - a)
        v.append((c[0], c[1]))

        return (list(map(lambda t: (round(t[0], 2), round(t[1], 2)), v)))
예제 #4
0
    def _localVertices(self):
        w, h = self.size[0], self.size[1]
        rot = self.rot
        radius = vectors.length((0, 0), (w, h)) / 2

        # top right corner
        #  ______
        # |     /|
        # |    / |
        # |   /__|
        # |a     |
        # |      |
        # |______|

        a = math.asin(h / (2 * radius))
        #c = (radius * round(cos(rot + a), 2), radius * round(sin(rot + a), 2))
        c = vectors.component(radius, rot + a)
        v = [(c[0], c[1])]

        # top left corner
        #c = (radius * round(cos(rot + pi - a), 2), radius * round(sin(rot + pi - a), 2))
        c = vectors.component(radius, rot + (math.pi - a))
        v.append((c[0], c[1]))

        # bottom left corner
        #c = (radius * round(cos(rot + pi + a), 2), radius * round(sin(rot + pi + a), 2))
        c = vectors.component(radius, rot + (math.pi + a))
        v.append((c[0], c[1]))

        # bottom right corner
        #c = (radius * round(cos(rot - a), 2), radius * round(sin(rot - a), 2))
        c = vectors.component(radius, rot - a)
        v.append((c[0], c[1]))

        return (list(map(lambda t: (round(t[0], 2), round(t[1], 2)), v)))
예제 #5
0
 def execute(self, obj):
     pos = V.vector(obj.rect.center)
     targpos = obj.target.rect.center
     traveltime = V.length(pos-targpos)/obj.maxspeed
     targvel = obj.target.velocity
     futurepos = targpos + targvel*traveltime
     desired_velocity = obj.maxspeed*V.normalize(futurepos - pos)
     obj.steering = desired_velocity - obj.velocity
     V.truncate(obj.steering, obj.maxforce)
예제 #6
0
 def execute(self, obj):
     pos = V.vector(obj.rect.center)
     targpos = obj.target.rect.center
     traveltime = V.length(pos - targpos) / obj.maxspeed
     targvel = obj.target.velocity
     futurepos = targpos + targvel * traveltime
     desired_velocity = obj.maxspeed * V.normalize(pos - futurepos)
     obj.steering = desired_velocity - obj.velocity
     V.truncate(obj.steering, obj.maxforce)
예제 #7
0
    def update(self):

        self.prevpos = V.vector(self.rect.center).copy()

        self.state.execute(self)

        ## Add a tiny force toward the center of the field
        if False:  #self.state != S.Wait():
            center = V.vector(pygame.display.get_surface().get_rect().center)
            towardcenter = center - self.rect.center
            V.normalize_ip(towardcenter)
            self.steering += 0.5 * towardcenter

        self.velocity += FORCE_PER_TICK * self.steering / (self.mass)
        V.truncate(self.velocity, self.maxspeed)

        speed = V.length(self.velocity)
        if speed > 0.001:
            self.heading = V.normalize(self.velocity)
        self.rect.center += self.velocity
        self.depth = -self.rect.centery

        #determine which image direction to use, based on heading and velocity:
        if speed >= 0.001:
            small = 0.382  # sin(22.5 degrees)
            big = 0.923  # cos(22.5 degrees)
            x, y = self.heading
            if y >= big: self.dir = 's'
            elif small <= y:
                if x > 0: self.dir = 'se'
                else: self.dir = 'sw'
            elif -small <= y:
                if x > 0: self.dir = 'e'
                else: self.dir = 'w'
            elif -big <= y:
                if x > 0: self.dir = 'ne'
                else: self.dir = 'nw'
            else: self.dir = 'n'
        else:
            self.velocity[0] = self.velocity[1] = 0.0

    #image action:  stopped or moving?
        if speed < 0.001:
            self.aspeed = 0.5
            action = 'looking'
        else:
            self.aspeed = 0.2 * speed
            action = 'walking'

        self.images = Images.get(self.name)[self.dir][action]
        self.nframes = len(self.images)

        #advance animation frame
        self.frame = self.aspeed + self.frame
        while self.frame >= self.nframes:
            self.frame -= self.nframes
        self.image = self.images[int(self.frame)]
예제 #8
0
    def update(self):

        self.prevpos = V.vector(self.rect.center).copy()

        self.state.execute(self)
        
        ## Add a tiny force toward the center of the field
        if False:#self.state != S.Wait():
            center = V.vector(pygame.display.get_surface().get_rect().center)
            towardcenter = center - self.rect.center
            V.normalize_ip(towardcenter)
            self.steering += 0.5*towardcenter      
        
        self.velocity += FORCE_PER_TICK*self.steering/(self.mass)
        V.truncate(self.velocity, self.maxspeed)

        speed = V.length(self.velocity)
        if speed > 0.001:
            self.heading = V.normalize(self.velocity)
        self.rect.center += self.velocity
        self.depth = -self.rect.centery
        
    #determine which image direction to use, based on heading and velocity:
        if speed >= 0.001:
            small = 0.382 # sin(22.5 degrees)
            big = 0.923  # cos(22.5 degrees)
            x,y = self.heading
            if y >= big: self.dir = 's'
            elif small <= y:
                if x > 0: self.dir = 'se'
                else: self.dir = 'sw'
            elif -small <= y:
                if x > 0: self.dir = 'e'
                else: self.dir = 'w'
            elif -big <= y:
                if x > 0: self.dir = 'ne'
                else: self.dir = 'nw'
            else: self.dir = 'n'
        else:
            self.velocity[0] = self.velocity[1] = 0.0
        
    #image action:  stopped or moving?
        if speed < 0.001: 
            self.aspeed = 0.5
            action = 'looking'
        else: 
            self.aspeed = 0.2*speed
            action = 'walking'
            
        self.images = Images.get(self.name)[self.dir][action]
        self.nframes = len(self.images)
        
    #advance animation frame
        self.frame = self.aspeed+self.frame
        while self.frame >= self.nframes: self.frame -= self.nframes
        self.image = self.images[int(self.frame)]
예제 #9
0
 def shoot(self, weapon):
     if weapon is "WEAP_BULLET":
         entity.entBullet(self.ent.projloc("WEAP_BULLET"),
                          vec.component(
                              SPD_BULLET + vec.length(self.ent.vel),
                              self.ent.rot),
                          owner=self.ent)
         print "bullet shot. travelling at %s units per frame %s, at an angle of %s radians" % (
             SPD_BULLET, vec.component(SPD_BULLET,
                                       self.ent.rot), self.ent.rot)
     pass
예제 #10
0
    def __init__(self,
                 pos,
                 rot=0,
                 vel=(0, 0),
                 player=False,
                 sprite=None,
                 size=None,
                 expiry=-1,
                 interact=True,
                 health=HEALTH_PLANE,
                 owner=None):
        self.age = 0
        self.expiry = expiry
        self.health = health

        self.owner = owner

        self.pos = pos

        # if rotation and velocity is given, use only the magnitude of the velocity
        if rot:
            self.rot = ROT_PLANE_INT * round(rot / ROT_PLANE_INT)
        else:
            self.rot = ROT_PLANE_INT * round(
                vectors.anglex(vel) / ROT_PLANE_INT)
        self.vel = vectors.component(vectors.length(vel), self.rot)

        self.ctlfunc = control.ctlPlane(self)

        self.player = player
        if self.player:
            Entity.players.append(self)

        self.interact = interact

        #if not Texture.textures.has_key("OBJ_PLANE"):
        #    Texture("OBJ_PLANE", IMGDIR + "OBJ_PLANE" + IMGEXT)
        #self.texture = Texture.textures["OBJ_PLANE"]
        #self.size = (40, 40)#(self.image.w, self.image.h)
        if not sprite:
            self.sprite = sprclass.plane
        else:
            self.sprite = sprite

        if not size:
            self.size = len(self.sprite[0]), len(self.sprite)
        else:
            self.size = size

        self.cells = []
        if self.interact:
            cell.add(self)
        Entity.entities.append(self)
예제 #11
0
def gradient_descent2(f, xstart, ystart, tolerance=1e-6):
    i = 0
    x = xstart
    y = ystart
    grad = approx_gradient2(f, x, y)
    while length(grad) > tolerance:
        i = i + 1
        x -= 0.01 * grad[0]
        y -= 0.01 * grad[1]
        grad = approx_gradient2(f, x, y)
    print(f'gradient_descent2: converged after {i} iterations')
    return x, y
예제 #12
0
def gradient_descent(f, vstart, dx=1e-6, max_steps=1000):
    v = vstart
    grad = approx_gradient(f, v, dx)
    steps = 0
    while length(grad) > dx and steps < max_steps:
        v = [(vi - 0.01 * dvi) for vi, dvi in zip(v, grad)]
        grad = approx_gradient(f, v, dx)
        steps += 1
    print(f'gradient_descent: max_steps = {max_steps}')
    print(
        f'gradient_descent: converged or reached max_steps after {steps} steps'
    )
    return v
예제 #13
0
def pnt2line(pnt, start, end):
    line_vec = vec.vector(start, end)
    pnt_vec = vec.vector(start, pnt)
    line_len = vec.length(line_vec)
    line_unitvec = vec.unit(line_vec)
    pnt_vec_scaled = vec.scale(pnt_vec, 1.0 / line_len)
    t = vec.dot(line_unitvec, pnt_vec_scaled)
    if t < 0.0:
        t = 0.0
    elif t > 1.0:
        t = 1.0
    nearest = vec.scale(line_vec, t)
    dist = vec.distance(nearest, pnt_vec)
    nearest = vec.add(nearest, start)
    return (dist, nearest)
예제 #14
0
    def __init__(self, pos, rot = 0, vel = (0, 0), player = False, sprite = None, size = None, expiry = -1, interact = True, health = HEALTH_PLANE, owner = 
None):
        self.age = 0
        self.expiry = expiry
        self.health = health

        self.owner = owner

        self.pos = pos

        # if rotation and velocity is given, use only the magnitude of the velocity
        if rot:
            self.rot = ROT_PLANE_INT * round(rot / ROT_PLANE_INT)
        else:
            self.rot = ROT_PLANE_INT * round(vectors.anglex(vel) / ROT_PLANE_INT)
        self.vel = vectors.component(vectors.length(vel), self.rot)

        self.ctlfunc = control.ctlPlane(self)
        
        self.player = player
        if self.player:
            Entity.players.append(self)

        self.interact = interact
        
        #if not Texture.textures.has_key("OBJ_PLANE"):
        #    Texture("OBJ_PLANE", IMGDIR + "OBJ_PLANE" + IMGEXT)
        #self.texture = Texture.textures["OBJ_PLANE"]
        #self.size = (40, 40)#(self.image.w, self.image.h)
        if not sprite:
            self.sprite = sprclass.plane
        else:
            self.sprite = sprite

        if not size:
            self.size = len(self.sprite[0]), len(self.sprite)
        else:
            self.size = size

        self.cells = []
        if self.interact:
            cell.add(self)
        Entity.entities.append(self)
예제 #15
0
파일: boat.py 프로젝트: meltbanana/clipper
    def move(self, env):      

        #physics of forces on sail here
        #src:https://en.wikipedia.org/wiki/Forces_on_sails#Effect_of_coefficients_of_lift_and_drag_on_forces
        #f: (angle between wind and sail) -> (total force on sail)
        # function returns matrix: Matrix * Wind = Total Force
        def force_on_sails_matrix(wind, sail):         
            #1. get angle between wind and sail
            orientation = np.sign(np.cross(wind, sail))    
            angle = v.angle(wind, sail)
            if np.pi/2 < angle <= np.pi:
               angle = abs(np.pi - angle)
               orientation *= -1
               
            #2. get forces on sail (for 0 <= angle <= pi/2)
            #every ship has different parameters
            #so this is just game model boat 
            #to test control self-education ability
            drag = np.exp(abs(angle)/2) - 1
            lift = -orientation * np.exp(-20*(angle - 0.6)**2)
        
            return np.array([[drag, -lift], [lift, drag]])

            
        #1. rotation
        k_rotate = 0.05 * v.length(self.speed) #wheel -> rotate coefficient
        self.speed = v.rotate(self.speed, (-1) * self.wheel * k_rotate)

        #2. friction
        k_friction = 0.05
        self.speed = self.speed * (1 - k_friction)
        
        #3. acceleration = forces on sails -> projection on boat direction
        k_acceleration = 0.1
        wind_apparent = env.wind - self.speed
        total_force_matrix = force_on_sails_matrix(wind_apparent, v.rotate(self.speed, self.sail))
        total_force = np.dot(total_force_matrix, wind_apparent)
        self.speed += k_acceleration * v.projection(total_force, self.speed)
      
        #4. move
        self.location += self.speed
예제 #16
0
def gradient_descent3(f,
                      xstart,
                      ystart,
                      zstart,
                      tolerance=1e-6,
                      max_steps=1000):
    x = xstart
    y = ystart
    z = zstart
    grad = approx_gradient3(f, x, y, z)
    steps = 0
    while length(grad) > tolerance and steps < max_steps:
        x -= 0.01 * grad[0]
        y -= 0.01 * grad[1]
        z -= 0.01 * grad[2]
        grad = approx_gradient3(f, x, y, z)
        steps += 1
    print(f'gradient_descent3: max_steps = {max_steps}')
    print(
        f'gradient_descent3: converged or reached max_steps after {steps} steps'
    )
    return x, y, z
예제 #17
0
 def getKinectEnergy(self):
     return  self.mass*((v.length(self.vel))**2)/2
예제 #18
0
from vectors import length, scale


def normalize(v):
    l = length(v)
    return scale(1/l, v)
    # return tuple(coord / l for coord in v)

norm = normalize((-1, -1, 2))
print(norm, length(norm))
예제 #19
0
def main():
    ip= CamImageProvider(0, "../resources/testdata.avi")
    #ip = MovieImageProvider("../resources/testdata.avi",0,0)
    sq = Square(0)
    img,imgtime = ip.getImage(1)
    m_d = SquareDetector(img, imgtime, 2, 0)
    m_d.add_marker(sq)
    angle_min = math.pi
    angle_max = 0
    angle_diff_min = 100
    angle_diff_max = 0
    prop_min  = 40
    prop_max = 0
    rot_max = 0
    debug.start_at(ip, 0)
    while cv.WaitKey(1)<>27:
        img,imgtime = ip.getImage(1)
        if img is None:
            return
#        tmpimg = cv.CloneImage(draw_img)
#        tmpimg2 = cv.CloneImage(draw_img)
#        gray2 = cv.CloneImage(gray)
#        gray3 = cv.CloneImage(gray)
#        tmp = cv.CloneImage(gray)
#        mask = cv.CloneImage(gray)
#        mask2=cv.CloneImage(gray)
#        cv.Set(mask2,1)
#        cv.CvtColor(draw_img, gray, cv.CV_BGR2GRAY)
#        cv.CvtColor(draw_img, tmpimg, cv.CV_BGR2HSV)
#        cv.SetImageCOI(tmpimg, 1)
#        cv.Copy(tmpimg, gray)
#        print cv.MinMaxLoc(gray)
#        cv.ShowImage("gray", gray)
        if debug.is_time():
            pass
        m_d.find_markers(img,imgtime,True)
        mar = m_d.markers[0]
        points = mar.points
        m_d.draw_markers(m_d.draw_img)
        debug.show([m_d.draw_img],"main",1,1)
        #debug.show_images()
        if len(points)<>4 or cv.WaitKey(50)<>32: 
            continue
        a = length(vector(points[0],points[1]))
        b = length(vector(points[1],points[2]))
        c = length(vector(points[2],points[3]))
        d = length(vector(points[3],points[0]))
        if a>c:
            a,c = c,a
        if b>d:
            b,d = d,b
        if c == 0.0:
            print mar
        else:
            print "sides a/c:", a/c
            if a/c > prop_max: prop_max = a/c
            if a/c < prop_min: prop_min = a/c
        if d==0.0:
            print mar
        else:
            print "sides b/d", b/d
            if b/d > prop_max: prop_max = b/d
            if b/d < prop_min: prop_min = b/d
        for cor in mar.corners:
            if cor.angle < angle_min:angle_min = cor.angle
            if cor.angle > angle_max:angle_max = cor.angle
            if cor.rotation > rot_max: rot_max = cor.rotation
        a,b,c,d = [c.angle for c in mar.corners]
        if a>c:
            a,c=c,a
        if b>d:
            b,d=d,b
        if a/c > angle_diff_max: angle_diff_max=a/c
        if a/c< angle_diff_min: angle_diff_min = a/c
        print "angle diff a/c", a/c
        if b/d > angle_diff_max: angle_diff_max=b/d
        if b/d< angle_diff_min: angle_diff_min = b/d
        print "angle diff b/d", b/d
                
    print "angle_min", angle_min
    print "angle_max", angle_max
    print "prop_min", prop_min
    print "prop_max", prop_max
    print "rot_max",rot_max
    print "angle_diff_min", angle_diff_min
    print "angle_diff_max",angle_diff_max
예제 #20
0
def normalize(v):
    l = length(v)
    return scale(1/l, v)
예제 #21
0
    def process(self):
        actions = []  # immediate actions

        # increase
        for k in self.inter:
            if self.inter[k] > 0:
                self.inter[k] -= 1

        if self.ent.player:  # human input
            # rotate. all this shit is so you can go like tapTAP to go up or down a slight level. roll on the arrows right?
            if k_clockwise in Control.keyevents:
                actions.append("ROT_CLOCK")
            elif k_counterclockwise in Control.keyevents:
                actions.append("ROT_COUNTER")
            elif Control.keys[k_clockwise] and Control.keys[
                    k_counterclockwise]:  # if both are pressed, going by key events will be unsynched
                pass
            elif Control.keys[
                    k_clockwise]:  #or k_clockwise in Control.keyevents:
                #               self.ent.rot += ROT_PLANE_INT
                actions.append("ROT_CLOCK")
            elif Control.keys[
                    k_counterclockwise]:  #or k_counterclockwise in Control.keyevents:
                #               self.ent.rot -= ROT_PLANE_INT
                actions.append("ROT_COUNTER")

            # accelerate
            if Control.keys[k_accel] and Control.keys[k_decel]:
                pass
            elif Control.keys[k_accel] or k_accel in Control.keyevents:
                #               self.ent.vel = vectors.component(vectors.length(self.ent.vel) + 1, self.ent.rot)
                actions.append("ACCEL")
            elif Control.keys[k_decel] or k_decel in Control.keyevents:
                #               self.ent.vel = vectors.component(vectors.length(self.ent.vel) - 1, self.ent.rot)
                actions.append("DECEL")

            # shoot
            if Control.keys[k_gun] or k_gun in Control.keyevents:
                #               self.shoot()
                actions.append("SHOOT_BULLET")

        else:  # AI
            # will have to adapt this to teammates / opponents, not just players
            if not entity.Entity.players:
                return

            # calculate closest player
            nearplayer = entity.Entity.players[0]
            neardist = math.fabs(self.ent.pos[0] - nearplayer.pos[0])
            for p in entity.Entity.players:
                if math.fabs(self.ent.pos[0] - p.pos[0]) < neardist:
                    nearplayer = p

            # set course
            realangle = vec.anglex((nearplayer.pos[0] - self.ent.pos[0],
                                    nearplayer.pos[1] - self.ent.pos[1]))
            if realangle < 0:
                realangle = 2 * math.pi + realangle
            rotangle = ROT_PLANE_INT * int(realangle / ROT_PLANE_INT)

            xdist = math.fabs(nearplayer.pos[0] - self.ent.pos[0])
            ydist = math.fabs(nearplayer.pos[1] - self.ent.pos[1])
            #pys = [y for _, y in nearplayer.vertices()]
            #ptop = max(pys)
            #pbottom = min(pys)
            pvs = nearplayer.vertices()
            pxs = [x for x, _ in pvs]
            pys = [y for _, y in pvs]
            left, right = min(pxs), max(pxs)
            bottom, top = min(pys), max(pys)

            #print self.ent, self.ent.rot, rotangle

            # set course. if far away, take your turns easy, otherwise, sharp is ok
            #if xdist > AI_PLANE_ACT_DIST: # far, easy
            cmpangle = rotangle
            #else: # close, hard
            #    cmpangle = realangle

            # latter conditions checks for alignment
            if self.ent.rot < cmpangle:
                if cmpangle - self.ent.rot > math.pi:
                    actions.append("ROT_COUNTER")
                else:
                    actions.append("ROT_CLOCK")
            elif self.ent.rot > cmpangle:
                if self.ent.rot - cmpangle > math.pi:
                    actions.append("ROT_CLOCK")
                else:
                    actions.append("ROT_COUNTER")

            # speed up
            if xdist <= AI_PLANE_SLOW_DIST:
                actions.append("DECEL")
            else:
                actions.append("ACCEL")

            # woah, cool
            def supercmp(f):
                if not f and f == self.ent.vel[0]:
                    return cmp(nearplayer.pos[0] - self.ent.pos[0], 0)
                elif not f and f == self.ent.vel[1]:
                    return cmp(nearplayer.pos[1] - self.ent.pos[1], 0)
                return cmp(f, 0)

            # blaze
            if xdist <= AI_PLANE_ACT_DIST:
                # facing the bastard
                if ((supercmp(self.ent.vel[0]) == cmp(nearplayer.pos[0] - self.ent.pos[0], 0)) and \
                    (supercmp(self.ent.vel[1]) == cmp(nearplayer.pos[1] - self.ent.pos[1], 0))):
                    # ^ test is failing on vel[0] == 0 or vel[1] == 0

                    # b = y - mx. we take the linear equation of our ai's velocity,
                    # and compare its offset (b = 0) with the offset computed by
                    # substituting the y and x values of each vertex of the player.
                    # if these vertices lie both above (b > 0) and below (b < 0)
                    # the line of velocity, then a bullet might intersect, so shoot, shoot
                    #if not self.ent.vel[0]:

                    if not self.ent.vel[0]:  # up/down
                        if self.ent.pos[0] > left and self.ent.pos[0] < right:
                            actions.append("SHOOT_BULLET")
                    else:
                        slope = self.ent.vel[1] / self.ent.vel[0]
                        b = self.ent.pos[1] - slope * self.ent.pos[0]
                        above = below = False
                        for v in pvs:
                            if (v[1] - slope * v[0]) > b:
                                above = True
                            else:
                                below = True

                            if above and below:
                                break

                        if above and below:
                            actions.append("SHOOT_BULLET")

        # perform actions
        for a in actions:
            if a == "ROT_CLOCK" and not self.inter["ROT"]:
                self.ent.rot += ROT_PLANE_INT
                if self.ent.rot >= 2 * math.pi:
                    self.ent.rot = 0

                self.ent.vel = vec.component(vec.length(self.ent.vel),
                                             self.ent.rot)
                self.inter["ROT"] = INT_ROT_PLANE
            elif a == "ROT_COUNTER" and not self.inter["ROT"]:
                self.ent.rot -= ROT_PLANE_INT
                if self.ent.rot < 0:
                    self.ent.rot = 2 * math.pi - ROT_PLANE_INT

                self.ent.vel = vec.component(vec.length(self.ent.vel),
                                             self.ent.rot)
                self.inter["ROT"] = INT_ROT_PLANE
            elif a == "ACCEL" and not self.inter["ACCEL"] and vec.length(
                    self.ent.vel) < SPD_PLANE_MAX:
                self.ent.vel = vec.component(
                    vec.length(self.ent.vel) + 1, self.ent.rot)
                self.inter["ACCEL"] = INT_ACCEL_PLANE
            elif a == "DECEL" and not self.inter["DECEL"] and vec.length(
                    self.ent.vel) > SPD_PLANE_MIN:
                self.ent.vel = vec.component(
                    vec.length(self.ent.vel) - 1, self.ent.rot)
                self.inter["DECEL"] = INT_DECEL_PLANE
            elif a == "SHOOT_BULLET" and not self.inter["SHOOT_BULLET"]:
                self.shoot("WEAP_BULLET")
                self.inter["SHOOT_BULLET"] = INT_BULLET_PLANE
예제 #22
0
 def shoot(self, weapon):
     if weapon is "WEAP_BULLET":
         entity.entBullet(self.ent.projloc("WEAP_BULLET"), vec.component(SPD_BULLET + vec.length(self.ent.vel), self.ent.rot), owner = self.ent)
         print "bullet shot. travelling at %s units per frame %s, at an angle of %s radians" % (SPD_BULLET, vec.component(SPD_BULLET, self.ent.rot), self.ent.rot)
     pass
예제 #23
0
    def process(self):
        actions = [] # immediate actions
        
        # increase 
        for k in self.inter:
            if self.inter[k] > 0:
                self.inter[k] -= 1
        
        if self.ent.player: # human input
            # rotate. all this shit is so you can go like tapTAP to go up or down a slight level. roll on the arrows right?
            if k_clockwise in Control.keyevents:
                actions.append("ROT_CLOCK")
            elif k_counterclockwise in Control.keyevents:
                actions.append("ROT_COUNTER")
            elif Control.keys[k_clockwise] and Control.keys[k_counterclockwise]: # if both are pressed, going by key events will be unsynched
                pass
            elif Control.keys[k_clockwise]: #or k_clockwise in Control.keyevents:
#               self.ent.rot += ROT_PLANE_INT
                actions.append("ROT_CLOCK")
            elif Control.keys[k_counterclockwise]: #or k_counterclockwise in Control.keyevents:
#               self.ent.rot -= ROT_PLANE_INT
                actions.append("ROT_COUNTER")
                
            # accelerate
            if Control.keys[k_accel] and Control.keys[k_decel]:
                pass
            elif Control.keys[k_accel] or k_accel in Control.keyevents:
#               self.ent.vel = vectors.component(vectors.length(self.ent.vel) + 1, self.ent.rot)
                actions.append("ACCEL")
            elif Control.keys[k_decel] or k_decel in Control.keyevents:
#               self.ent.vel = vectors.component(vectors.length(self.ent.vel) - 1, self.ent.rot)
                actions.append("DECEL")
                
            # shoot
            if Control.keys[k_gun] or k_gun in Control.keyevents:
#               self.shoot()
                actions.append("SHOOT_BULLET")
                
        else: # AI
            # will have to adapt this to teammates / opponents, not just players
            if not entity.Entity.players:
                return
                
            # calculate closest player    
            nearplayer = entity.Entity.players[0]
            neardist = math.fabs(self.ent.pos[0] - nearplayer.pos[0])
            for p in entity.Entity.players:
                if math.fabs(self.ent.pos[0] - p.pos[0]) < neardist:
                    nearplayer = p
            
            # set course
            realangle = vec.anglex((nearplayer.pos[0] - self.ent.pos[0], nearplayer.pos[1] - self.ent.pos[1]))
            if realangle < 0:
                realangle = 2 * math.pi + realangle
            rotangle = ROT_PLANE_INT * int(realangle / ROT_PLANE_INT)
            
            xdist = math.fabs(nearplayer.pos[0] - self.ent.pos[0])
            ydist = math.fabs(nearplayer.pos[1] - self.ent.pos[1])
            #pys = [y for _, y in nearplayer.vertices()]
            #ptop = max(pys)
            #pbottom = min(pys)
            pvs = nearplayer.vertices()
            pxs = [x for x, _ in pvs]
            pys = [y for _, y in pvs]
            left, right = min(pxs), max(pxs)
            bottom, top = min(pys), max(pys) 
            
            #print self.ent, self.ent.rot, rotangle
            
            # set course. if far away, take your turns easy, otherwise, sharp is ok
            #if xdist > AI_PLANE_ACT_DIST: # far, easy
            cmpangle = rotangle
            #else: # close, hard
            #    cmpangle = realangle
                
            # latter conditions checks for alignment     
            if self.ent.rot < cmpangle:
                if cmpangle - self.ent.rot > math.pi:
                    actions.append("ROT_COUNTER")
                else:
                    actions.append("ROT_CLOCK")
            elif self.ent.rot > cmpangle:
                if self.ent.rot - cmpangle > math.pi:
                    actions.append("ROT_CLOCK")
                else:
                    actions.append("ROT_COUNTER")
                    
                    
            # speed up
            if xdist <= AI_PLANE_SLOW_DIST:
                actions.append("DECEL")
            else:
                actions.append("ACCEL")
                
            # woah, cool
            def supercmp(f):
                if not f and f == self.ent.vel[0]:
                    return cmp(nearplayer.pos[0] - self.ent.pos[0], 0)
                elif not f and f == self.ent.vel[1]:
                    return cmp(nearplayer.pos[1] - self.ent.pos[1], 0)
                return cmp(f, 0)
                    
            # blaze
            if xdist <= AI_PLANE_ACT_DIST:
                # facing the bastard
                if ((supercmp(self.ent.vel[0]) == cmp(nearplayer.pos[0] - self.ent.pos[0], 0)) and \
                    (supercmp(self.ent.vel[1]) == cmp(nearplayer.pos[1] - self.ent.pos[1], 0))):
                # ^ test is failing on vel[0] == 0 or vel[1] == 0
                    
                    # b = y - mx. we take the linear equation of our ai's velocity, 
                    # and compare its offset (b = 0) with the offset computed by
                    # substituting the y and x values of each vertex of the player.
                    # if these vertices lie both above (b > 0) and below (b < 0)
                    # the line of velocity, then a bullet might intersect, so shoot, shoot
                    #if not self.ent.vel[0]:
                    
                    if not self.ent.vel[0]: # up/down
                        if self.ent.pos[0] > left and self.ent.pos[0] < right:
                            actions.append("SHOOT_BULLET")
                    else:
                        slope = self.ent.vel[1] / self.ent.vel[0]
                        b = self.ent.pos[1] - slope * self.ent.pos[0]
                        above = below = False
                        for v in pvs:
                            if (v[1] - slope * v[0]) > b:
                                above = True
                            else:
                                below = True
                                
                            if above and below:
                                break
                                    
                        if above and below:
                            actions.append("SHOOT_BULLET")
        
        # perform actions
        for a in actions:
            if a == "ROT_CLOCK" and not self.inter["ROT"]:
                self.ent.rot += ROT_PLANE_INT
                if self.ent.rot >= 2 * math.pi:
                    self.ent.rot = 0
                
                self.ent.vel = vec.component(vec.length(self.ent.vel), self.ent.rot)
                self.inter["ROT"] = INT_ROT_PLANE
            elif a == "ROT_COUNTER" and not self.inter["ROT"]:
                self.ent.rot -= ROT_PLANE_INT
                if self.ent.rot < 0:
                    self.ent.rot = 2 * math.pi - ROT_PLANE_INT 
                
                self.ent.vel = vec.component(vec.length(self.ent.vel), self.ent.rot)
                self.inter["ROT"] = INT_ROT_PLANE
            elif a == "ACCEL" and not self.inter["ACCEL"] and vec.length(self.ent.vel) < SPD_PLANE_MAX:
                self.ent.vel = vec.component(vec.length(self.ent.vel) + 1, self.ent.rot)
                self.inter["ACCEL"] = INT_ACCEL_PLANE
            elif a == "DECEL" and not self.inter["DECEL"] and vec.length(self.ent.vel) > SPD_PLANE_MIN:
                self.ent.vel = vec.component(vec.length(self.ent.vel) - 1, self.ent.rot)
                self.inter["DECEL"] = INT_DECEL_PLANE
            elif a == "SHOOT_BULLET" and not self.inter["SHOOT_BULLET"]:
                self.shoot("WEAP_BULLET")
                self.inter["SHOOT_BULLET"] = INT_BULLET_PLANE
예제 #24
0
def main():
    ip = CamImageProvider(0, "../resources/testdata.avi")
    #ip = MovieImageProvider("../resources/testdata.avi",0,0)
    sq = Square(0)
    img, imgtime = ip.getImage(1)
    m_d = SquareDetector(img, imgtime, 2, 0)
    m_d.add_marker(sq)
    angle_min = math.pi
    angle_max = 0
    angle_diff_min = 100
    angle_diff_max = 0
    prop_min = 40
    prop_max = 0
    rot_max = 0
    debug.start_at(ip, 0)
    while cv.WaitKey(1) <> 27:
        img, imgtime = ip.getImage(1)
        if img is None:
            return


#        tmpimg = cv.CloneImage(draw_img)
#        tmpimg2 = cv.CloneImage(draw_img)
#        gray2 = cv.CloneImage(gray)
#        gray3 = cv.CloneImage(gray)
#        tmp = cv.CloneImage(gray)
#        mask = cv.CloneImage(gray)
#        mask2=cv.CloneImage(gray)
#        cv.Set(mask2,1)
#        cv.CvtColor(draw_img, gray, cv.CV_BGR2GRAY)
#        cv.CvtColor(draw_img, tmpimg, cv.CV_BGR2HSV)
#        cv.SetImageCOI(tmpimg, 1)
#        cv.Copy(tmpimg, gray)
#        print cv.MinMaxLoc(gray)
#        cv.ShowImage("gray", gray)
        if debug.is_time():
            pass
        m_d.find_markers(img, imgtime, True)
        mar = m_d.markers[0]
        points = mar.points
        m_d.draw_markers(m_d.draw_img)
        debug.show([m_d.draw_img], "main", 1, 1)
        #debug.show_images()
        if len(points) <> 4 or cv.WaitKey(50) <> 32:
            continue
        a = length(vector(points[0], points[1]))
        b = length(vector(points[1], points[2]))
        c = length(vector(points[2], points[3]))
        d = length(vector(points[3], points[0]))
        if a > c:
            a, c = c, a
        if b > d:
            b, d = d, b
        if c == 0.0:
            print mar
        else:
            print "sides a/c:", a / c
            if a / c > prop_max: prop_max = a / c
            if a / c < prop_min: prop_min = a / c
        if d == 0.0:
            print mar
        else:
            print "sides b/d", b / d
            if b / d > prop_max: prop_max = b / d
            if b / d < prop_min: prop_min = b / d
        for cor in mar.corners:
            if cor.angle < angle_min: angle_min = cor.angle
            if cor.angle > angle_max: angle_max = cor.angle
            if cor.rotation > rot_max: rot_max = cor.rotation
        a, b, c, d = [c.angle for c in mar.corners]
        if a > c:
            a, c = c, a
        if b > d:
            b, d = d, b
        if a / c > angle_diff_max: angle_diff_max = a / c
        if a / c < angle_diff_min: angle_diff_min = a / c
        print "angle diff a/c", a / c
        if b / d > angle_diff_max: angle_diff_max = b / d
        if b / d < angle_diff_min: angle_diff_min = b / d
        print "angle diff b/d", b / d

    print "angle_min", angle_min
    print "angle_max", angle_max
    print "prop_min", prop_min
    print "prop_max", prop_max
    print "rot_max", rot_max
    print "angle_diff_min", angle_diff_min
    print "angle_diff_max", angle_diff_max
예제 #25
0
 def length(self):
     return vectors.length(self.coords)
예제 #26
0
 def getEnergy(self, M):
     return self.mass*((v.length(self.vel))**2)/2 - G*M*self.mass/v.length(self.pos)
예제 #27
0
 def vectorLenc(self, M):
     return np.cross(np.cross(self.vel,self.pos),self.vel)*self.mass*self.mass - self.pos*self.mass*G*M/v.length(self.pos)
예제 #28
0
 def getPotentialEnergy(self, M):
     return G*M*self.mass/v.length(self.pos)