示例#1
0
 def move(self):
     if self.alive:
         robot_pos = Vec2d(self.x, self.y)
         target_pos = Vec2d(800, 300)
         angle_between = target_pos.get_angle_between(robot_pos)
         angle_out = self.brain.forward([(sensor.reading / self.max_range)
                                         for sensor in self.sensors])[1]
         # self.robot_angle = np.interp(angle_out, [-1, 1], [-60, 60])
         triggered = False
         for sensor in self.sensors:
             if sensor.reading < self.max_range:
                 triggered = True
         if triggered:
             self.robot_angle = np.interp(angle_out, [-1, 1], [-60, 60])
         else:
             self.robot_angle = np.interp(angle_out, [-1, 1], [-60, 60])
             delta_y = 300 - self.y
             delta_x = 800 - self.x
             # self.robot_angle = m.degrees(m.atan(delta_y/delta_x))
         # self.robot_angle += self.brain.forward([(sensor.reading/self.max_range) for sensor in self.sensors])[1] # this changes between -1 and 1 degrees per decision
         self.x += 7 * self.brain.forward([
             (sensor.reading / self.max_range) for sensor in self.sensors
         ])[0] * m.cos(m.radians(self.robot_angle))
         self.y += 7 * self.brain.forward([
             (sensor.reading / self.max_range) for sensor in self.sensors
         ])[0] * m.sin(m.radians(self.robot_angle))
示例#2
0
文件: p2.py 项目: wiledy/plane
 def boss_shut(self):
     do_shut = random.randint(1, 3)
     # 第一种方法,圆形
     if do_shut == 1:
         for x in range(21):
             angle = math.pi / 10
             copy_pos = copy.deepcopy([self.boss_pos[0] + 140, self.boss_pos[1] + 100])
             normal_vec = Vec2d(math.cos(x*angle), math.sin(x*angle)).normalized()
             self.enemy_bullets.append([copy_pos, normal_vec])
     # 第二种方法,螺旋
     elif do_shut == 2:
         for x in range(-10, 11):
             angle = math.pi / 10
             copy_pos = copy.deepcopy([self.boss_pos[0] + 140, self.boss_pos[1] + 100])
             normal_vec = Vec2d(math.cos(x * angle), math.sin(x * angle)).normalized()
             self.enemy_bullets.append([copy_pos, normal_vec])
             sleep(0.05)
     # 第三种方法,来回
     elif do_shut == 3:
         for x in range(-10, 11):
             angle = math.pi / 10
             copy_pos = copy.deepcopy([self.boss_pos[0] + 140, self.boss_pos[1] + 100])
             normal_vec = Vec2d(math.cos(x * angle), abs(math.sin(x * angle))).normalized()
             self.enemy_bullets.append([copy_pos, normal_vec])
             sleep(0.1)
示例#3
0
 def do_actions(self):
     goal = self.tank.world.collision("tank", self.tank.location,
                                      self.tank.direction, TK, self.tank.id)
     # 控制方向,and遇到阻挡会停下来
     pressed_keys = pygame.key.get_pressed()
     if pressed_keys[K_LEFT]:
         self.tank.direction = Vec2d(-1, 0)
         if goal is None:
             self.tank.speed = self.tank.normal_speed
         else:
             self.tank.speed = 0
     elif pressed_keys[K_RIGHT]:
         self.tank.direction = Vec2d(1, 0)
         if goal is None:
             self.tank.speed = self.tank.normal_speed
         else:
             self.tank.speed = 0
     elif pressed_keys[K_UP]:
         self.tank.direction = Vec2d(0, -1)
         if goal is None:
             self.tank.speed = self.tank.normal_speed
         else:
             self.tank.speed = 0
     elif pressed_keys[K_DOWN]:
         self.tank.direction = Vec2d(0, 1)
         if goal is None:
             self.tank.speed = self.tank.normal_speed
         else:
             self.tank.speed = 0
     else:
         self.tank.speed = 0
     # 控制开火
     if pressed_keys[K_SPACE]:
         self.tank.fire()
示例#4
0
 def detect_static2(self):  #first obstacle
     q = Vec2d(200, 300)
     r = 75
     v = Vec2d(self.x1, self.y1) - Vec2d(self.x0, self.y0)
     p = Vec2d(self.x0, self.y0)
     A = v.dot(v)
     B = 2 * (v.dot((p - q)))
     C = p.dot(p) + q.dot(q) - ((2 * p).dot(q)) - r**2
     if (
             B**2 - 4 * A * C
     ) >= 0:  # Sensors delayed updating could be something to do with this line
         x_solution = np.roots([A, B, C])
         if 0 <= x_solution[0] <= 1 or 0 <= x_solution[1] <= 1:
             y_solution = [p + x_solution[0] * v, p + x_solution[1] * v]
             # pygame.draw.line(screen, (255, 0, 0), (self.x0, self.y0), (self.x1, self.y1))
             # pygame.draw.circle(screen, (0, 255, 0), (int(y_solution[1][0]), int(y_solution[1][1])), 1, 0)  # here
             pygame.draw.line(screen, (0, 255, 0), (self.x0, self.y0),
                              (y_solution[1][0], y_solution[1][1]))
             # print("Sensor {}s reading is {}".format(self.id, p.get_distance(y_solution[1])))
             self.reading = p.get_distance(y_solution[1])
         else:
             # print("Sensor {}s reading is {}".format(self.id, self.max_range))
             self.reading = self.max_range
     else:
         self.reading = self.detect_static()
示例#5
0
 def evaluate_fitness(self):
     if self.alive:
         target_pos = Vec2d(800, 300)
         start = Vec2d(self.start_x, self.start_y)
         robot_pos = Vec2d(self.x, self.y)
         angle = robot_pos.get_angle_between(target_pos)
         total = start.get_distance(target_pos)
         distance = robot_pos.get_distance(target_pos)
         closest = total
         # completion_time = self.sensors[0].completion_time
         if distance < self.best:
             self.best = distance
         if self.hitTarget:
             targetFactor = 1
         else:
             targetFactor = 0
         try:
             # self.fitness = (1 / self.best)
             # self.fitness = 1/(distance*m.cos(m.radians(angle)))
             self.fitness = (1 / distance) + (0.5 * (1 / self.best)) + (
                 1 * (1 / self.time_alive)) + (0.5 * targetFactor)
             # self.fitness = distance
             # self.fitness = (total - distance) / total
         except ZeroDivisionError:
             print("tried dividing by zero")
             self.fitness = 100
示例#6
0
 def detectObstacle(self, obstacle):
     if obstacle.shape == 'Circle':
         q = Vec2d(obstacle.position)
         r = obstacle.radius
         v = Vec2d(self.x1, self.y1) - Vec2d(self.x0, self.y0)
         p = Vec2d(self.x0, self.y0)
         A = v.dot(v)
         B = 2 * (v.dot((p - q)))
         C = p.dot(p) + q.dot(q) - ((2 * p).dot(q)) - r**2
         # print(Vec2d(self.x1, self.y1), Vec2d(self.x0, self.y0))
         # print(A, B, C)
         # print(p, Vec2d(self.x1, self.y1))
         if (
                 B**2 - 4 * A * C
         ) >= 0:  # Sensors delayed updating could be something to do with this line
             x_solution = np.roots([A, B, C])
             if 0 <= x_solution[0] <= 1 or 0 <= x_solution[1] <= 1:
                 y_solution = [p + x_solution[0] * v, p + x_solution[1] * v]
                 pygame.draw.line(screen, (0, 255, 0), (self.x0, self.y0),
                                  (y_solution[1][0], y_solution[1][1]))
                 self.reading = p.get_distance(y_solution[1])
                 # self.activated = True
                 # print("Sensor {} is {}".format(self.id, self.reading))
             else:
                 # self.activated = False
                 self.reading = self.max_range
         else:
             self.reading = self.max_range
示例#7
0
def test():
    try:
        fps = 5
        surface = pygame.display.set_mode((600, 600))
        pygame.init()
        spheres = (
            Tree(surface, pygame.Color(255, 255, 0), Vec2d(300, 500), 8, 250),
            Tree(surface, pygame.Color(255, 255, 0), Vec2d(330, 500), 5, 100),
        )
        clock = pygame.time.Clock()
        pause = False
        while True:
            clock.tick(fps)
            events = pygame.event.get()
            for event in events:
                if event.type == pygame.QUIT:
                    sys.exit(0)
            keyinput = pygame.key.get_pressed()
            if keyinput is not None:
                if keyinput[pygame.K_ESCAPE]:
                    sys.exit(1)
            if pause is not True:
                surface.fill((0, 0, 0, 255))
                for thing in spheres:
                    thing.update()
                pygame.display.flip()
    except KeyboardInterrupt:
        print 'shutting down'
示例#8
0
 def collision(self, name, location, direction, size, id):
     # 碰撞判定
     # 这里的entity可以表示对方,但self是指world而不是我自己,所以自己的值全都需要传入:位置、方向、尺寸和id
     location = Vec2d(*location)  # 传入的值可能不符合Vec2d格式,这里规范一下
     direction = Vec2d(*direction)
     self.entities2 = copy.copy(self.entities)
     for entity in self.entities2.values():
         # 先检查对方不是自己!
         if id != entity.id:
             # 是否有碰撞体积
             if (name in ("tank_user", "tank_enemy") and entity.collision_to_tank)\
                     or (name == "canon" and entity.collision_to_canon):  # 注意分类的集合,不重复也不缺少
                 # 获得自身到对方的距离向量
                 distance = entity.location - location
                 # 获得距离向量到自身朝向的投影
                 proj_x = distance.projection(direction)
                 # 距离向量到自身侧向的投影
                 proj_y = distance.projection(direction.perpendicular())
                 if proj_y.get_length() < (
                         size + entity.size -
                         4) / 2:  # 这里标量化了,不用担心方向,-4是为了让侧面不容易被卡住
                     if direction.dot(proj_x) > 0:  # dot表示点积,确保是向前的
                         if proj_x.get_length() < (size + entity.size) / 2:
                             return entity
     return None
示例#9
0
 def genCorners(self):
     """
     Pad at angle=0
     
           _ upperLeft corner
          /    _ upperRight corner
         /    /
         *---*
         |   |
         |   |
         |   |
         |   |
         |   |
         *---*
         |    \_ lowerRight corner
          \_ lowerLeft corner
      
     """
     upperLeft  = Vec2d((mdl_pad._IN_TRACK, 0.0))
     upperRight = Vec2d((mdl_pad._OUT_TRACK, 0.0))
     lowerLeft  = Vec2d((mdl_pad._OUT_TRACK, 0.0))
     lowerRight = Vec2d((mdl_pad._IN_TRACK, 0.0))
     
     return [ upperLeft.rotate_rad(self.angle + self.length/2),
              upperRight.rotate_rad(self.angle + self.length/2),
              lowerLeft.rotate_rad(self.angle - self.length/2),
              lowerRight.rotate_rad(self.angle - self.length/2)  ]
示例#10
0
文件: Player.py 项目: FahmiA/NoteWars
    def update(self, elapsedTimeSec):
        Actor.update(self, elapsedTimeSec)

        # Handle mouse rotation
        mousePos = pygame.mouse.get_pos()
        angleToMouse = (Vec2d(mousePos) - self.getPosition()).get_angle() - 90
        self._rotate(angleToMouse)

        # Handle keyboard movement
        pressedKeys = pygame.key.get_pressed()
        self._velocity = Vec2d(0, 0)
        if pressedKeys[K_w]:
            self._velocity.y -= 1.0
        if pressedKeys[K_s]:
            self._velocity.y += 1.0
        if pressedKeys[K_a]:
            self._velocity.x -= 1.0
        if pressedKeys[K_d]:
            self._velocity.x += 1.0
        self._velocity = self._truncate(self._velocity * self._maxVelocity,
                                        self._maxVelocity)
        self._updatePosition()

        # Handle firing laser
        if self._fireDurationSec > 0:
            self._laser.fire(self.rect.center, self._rotation)
            self._fireDurationSec -= elapsedTimeSec
        else:
            self._laser.stop()
示例#11
0
    def arrow_pressed(self, keycode, keysdown):
        if not self.__ship.has_target():
            opts = self.__options
            arrows = [opts.up, opts.down, opts.left, opts.right]
            arrows_pressed = filter(lambda x: x in keysdown, arrows)
            last_pressed = None
            if len(arrows_pressed) > 0:
                last_pressed = arrows_pressed.pop()

            # Movement of the ship is made by strafing relative to the current
            # direction of the ship. Values found by trial and error.
            # TODO: Figure out why these values work, since they still don't
            #       make any sense
            dirs = {
                opts.up: (1, 0),
                opts.left: (0, -1),
                opts.down: (-1, 0),
                opts.right: (0, 1)
            }
            strafe_1 = Vec2d(dirs[keycode])
            if last_pressed == None:
                self.__ship.strafe = strafe_1.get_angle()
            else:
                strafe_2 = Vec2d(dirs[last_pressed])
                strafe_total = strafe_1 + strafe_2
                self.__ship.strafe = strafe_total.get_angle()

            self.__ship.speed = SHIPSPEED
示例#12
0
 def got_shot(self):
     global LIVES, GAMEOVER
     time.sleep(0.2)  # 延迟0.2秒,注意使用前要先import time
     LIVES -= 1
     self.location = Vec2d(9 * 24, 25 * 24)
     self.direction = Vec2d(0, -1)
     if LIVES < 0:
         GAMEOVER = True
示例#13
0
 def __init__(self, name="Entity"):
     self._name = name
     self._traits = {}
     self.pos = Vec2d(0, 0)
     self.vel = Vec2d(0, 0)
     self.size = Size(0, 0)
     self.sprite = None
     self.debug = True
示例#14
0
 def __init__(self, world, name, image):
     self.world = world
     self.name = name
     self.image = image
     self.location = Vec2d(0, 0)
     self.destination = Vec2d(0, 0)
     self.speed = 0.
     self.brain = StateMachine()
     self.id = 0
示例#15
0
 def update(self, lines):
     """update every frame"""
     fps = 1 / (time.time() - self.last_tick)
     self.draw_text("Frames per second %f" % fps, offset=Vec2d(0, 0))
     counter = 1
     for line in lines:
         self.draw_text(line, offset=Vec2d(0, self.size * counter))
         counter += 1
     self.last_tick = time.time()
示例#16
0
 def __init__(self, surface, game_engine):
     self.surface = surface
     self.game_engine = game_engine
     self.initialize()
     self.origin = Vec2d(self.surface.get_width() / 2, self.surface.get_height() /2)
     self.origin1 = Vec2d(self.surface.get_width() / 3, self.surface.get_height() /2)
     self.color = (255, 0, 0)
     self.vector = None
     self.initialize()
示例#17
0
 def __init__(self, world, no):
     self.world = world
     self.no = no
     self.color = (0, 0, 0)
     self.location = Vec2d(0, 0)
     self.velocity = Vec2d(0.0, 0.0)
     self.collision = True # 默认有碰撞体积
     self.mass = 10
     self.size = 60
     self.id = 0
示例#18
0
文件: play.py 项目: linbin89/invoker
 def create_enemy(self):
     # 间隔某段时间就创建新的敌机
     if self.time_record % (250 - self.hard * 40) == 0:
         x = random.randint(0, 1920)
         vec_x = random.randint(-1920, 1920)
         vec_y = random.randint(200, 500)
         vec_normal = Vec2d(vec_x, vec_y).normalized()
         self.live_enemy.append([x, 0, vec_normal, [vec_x, vec_y]])
         # 存在敌机
         self.enemy_find = 1
     # 移动敌机
     for enemy_pos in self.live_enemy:
         # 销毁超出范围的敌机并扣一分
         if enemy_pos[1] >= 1080:
             self.live_enemy.remove(enemy_pos)
             if self.my_count > 0:
                 self.my_count -= 1
         # 改变碰壁敌机的移动方向
         elif enemy_pos[0] < 10 or enemy_pos[0] > 1910:
             new_vec_x = 1000 - enemy_pos[0]
             new_vec_y = random.randint(enemy_pos[3][1] + 200,
                                        enemy_pos[3][1] + 500)
             new_vec_normal = Vec2d(new_vec_x, new_vec_y).normalized()
             self.live_enemy[self.live_enemy.index(
                 enemy_pos)][2] = new_vec_normal
             self.live_enemy[self.live_enemy.index(enemy_pos)][3] = [
                 new_vec_x, new_vec_y
             ]
     for enemy_pos in self.live_enemy:
         # 到达随机方向向量的y坐标附近就随机一个新的方向
         if enemy_pos[3][1] - 30 < enemy_pos[1] < enemy_pos[3][1] + 30:
             new_vec_x = random.randint(-1920, 1920)
             new_vec_y = random.randint(enemy_pos[3][1] + 400,
                                        enemy_pos[3][1] + 500)
             new_vec_normal = Vec2d(new_vec_x, new_vec_y).normalized()
             self.live_enemy[self.live_enemy.index(
                 enemy_pos)][2] = new_vec_normal
             self.live_enemy[self.live_enemy.index(enemy_pos)][3] = [
                 new_vec_x, new_vec_y
             ]
         # 否则按单位向量移动敌机
         else:
             self.live_enemy[self.live_enemy.index(
                 enemy_pos)][0] += self.live_enemy[self.live_enemy.index(
                     enemy_pos)][2][0]
             self.live_enemy[self.live_enemy.index(
                 enemy_pos)][1] += self.live_enemy[self.live_enemy.index(
                     enemy_pos)][2][1]
     # 画出敌机
     for enemy_pos in self.live_enemy:
         # 按照飞机中心为标准
         self.screen.blit(self.enemy_picture, [
             enemy_pos[0] - self.enemy_picture.get_width() / 2,
             enemy_pos[1] - self.enemy_picture.get_height() / 2
         ])
示例#19
0
    def process_video(self):
        video = cv2.VideoCapture(self.video_path)

        width = video.get(cv2.CAP_PROP_FRAME_WIDTH) * self.scale_factor
        height = video.get(cv2.CAP_PROP_FRAME_HEIGHT) * self.scale_factor

        scale_vector = Vec2d(width, height)

        last_time = -1
        last_pos = Vec2d(-1, -1)

        max_frames = 800
        frame_index = 0

        while(video.isOpened() and frame_index < max_frames):
            frame_index += 1
            ret, frame = video.read()

            # Process frame if it is available
            if(ret):
                # Process frame to grab locations
                # Downsize frame
                frame = cv2.resize(
                    frame, (0, 0), fx=self.scale_factor, fy=self.scale_factor)

                # cur_pos = self.color_detect(frame)
                cur_pos = self.motion_detect(frame)

                if cur_pos != -1 and cur_pos != Vec2d(0,0):
                    # Scale down vector to a 0.0 -> 1.0 scale
                    cur_pos = cur_pos.elm_div(scale_vector)

                    # Calculate frame velocity
                    cur_time = video.get(cv2.CAP_PROP_POS_MSEC) / 1000.0
                    cur_vel = self.calculate_velocity(
                        cur_time, last_time, cur_pos, last_pos)

                    if cur_vel.mag() < 300:
                        sample = Sample(cur_pos, cur_vel, Vec2d(0, 0), cur_time)
                        self.path.append(sample)

                    last_time = cur_time
                    last_pos = cur_pos

            else:
                print("Processing complete " + str(len(self.path)))
                # print(path)
                break

        # When everything done, release the capture
        video.release()
        if self.debug:
            cv2.destroyAllWindows()

        return self.path
示例#20
0
    def process(self, time_passed):
        global No_collision
        other_ball = self.world.collision(self.location, self.size, self.no, self.collision)
		# 搜索可能的碰撞对象
        # 发生碰撞后,两个球的速度发生相应改变
        if other_ball is not None:
            vec_distance = other_ball.location - self.location
            d0 = vec_distance.x
            d1 = vec_distance.y
            v00 = self.velocity.x - other_ball.velocity.x
            v01 = self.velocity.y - other_ball.velocity.y

            r = (self.size**2)*0.95 # 最后的数字是补充碰撞时粘连带来的莫名其妙的速度损失
           
            #r = (vec_distance.get_length())**2
 
            # v10 = (d0**2*v00 - d0**2*v00 + d1**2*v00 + d1**2*v00 - 2.0*d0*d1*v01)/((d0**2 + d1**2)*2.0)
            #v10 = (d0**2*v00 - d0**2*v00 + d1**2*v00 + d1**2*v00 - 2.0*d0*d1*v01)/1000
            #v11 = (d0**2*v01 + d0**2*v01 + d1**2*v01 - d1**2*v01 - 2.0*d0*d1*v00)/1000
            #v20 = (2.0*d0*(d0*v00 + d1*v01))/1000
            #v21 = (2.0*v01*d1**2 + 2.0*d0*v00*d1)/1000
            
            v10 = (v00*d1*d1 - d0*v01*d1)/r
            v11 = (v01*d0*d0 - d1*v00*d0)/r
            v20 = (d0*d0*v00 + d0*d1*v01)/r
            v21 = (v01*d1*d1 + d0*v00*d1)/r


            self.location -= vec_distance*0.08 # 这个数字是为了防止两个球粘连,在碰撞时强制反向弹跳,数值越小越容易粘连
            other_ball.location += vec_distance*0.08
            self.velocity += Vec2d(v10 - v00, v11 - v01)
            other_ball.velocity += Vec2d(v20, v21)

            No_collision += 1

        # 增加屏幕边缘反弹
        global No_rebound
        if self.location.x < 0 + self.size/2:
            self.location.x = 0 + self.size/2
            self.velocity.x = - self.velocity.x
            No_rebound += 1
        if self.location.x > W - self.size/2:
            self.location.x = W - self.size/2
            self.velocity.x = - self.velocity.x
            No_rebound += 1
        if self.location.y < 0 + self.size/2:
            self.location.y = 0 + self.size/2
            self.velocity.y = - self.velocity.y
            No_rebound += 1
        if self.location.y > H - self.size/2:
            self.location.y = H - self.size/2
            self.velocity.y = - self.velocity.y
            No_rebound += 1
        # 每一步都要让移动的东西继续移动
        self.location += time_passed * self.velocity
示例#21
0
    def __init__(self, length):
        self._length = length
        self._outerThickness = 20  # pixels
        self._innerThickness = 7  # pixels

        self._firedFromPos = Vec2d(0, 0)
        self._firedToPos = Vec2d(0, 0)

        self._outerColour = pygame.Color('#670da0ff')
        self._innerColour = pygame.Color('#9840cfff')

        self._isFiring = False
示例#22
0
 def do_actions(self):
     goal = self.tank.world.collision("tank_user", self.tank.location,
                                      self.tank.direction, TK, self.tank.id)
     # 控制方向,and遇到阻挡会停下来
     pressed_keys = pygame.key.get_pressed()
     if pressed_keys[K_LEFT]:
         self.tank.direction = Vec2d(-1, 0)
         if goal is None:
             self.tank.speed = self.tank.normal_speed
         elif goal.name == "bonus":
             self.tank.world.remove_entity(
                 goal)  # 如果撞到的东西是bonus,就去掉它,并给自己加速(假设所有的bonus都是加速器)
             self.tank.normal_speed += 48
             self.tank.canon_amount += 15
         else:
             self.tank.speed = 0  # 如果撞到别的东西,就停下来
     elif pressed_keys[K_RIGHT]:
         self.tank.direction = Vec2d(1, 0)
         if goal is None:
             self.tank.speed = self.tank.normal_speed
         elif goal.name == "bonus":
             self.tank.world.remove_entity(goal)
             self.tank.normal_speed += 48
             self.tank.canon_amount += 15
         else:
             self.tank.speed = 0
     elif pressed_keys[K_UP]:
         self.tank.direction = Vec2d(0, -1)
         if goal is None:
             self.tank.speed = self.tank.normal_speed
         elif goal.name == "bonus":
             self.tank.world.remove_entity(goal)
             self.tank.normal_speed += 48
             self.tank.canon_amount += 15
         else:
             self.tank.speed = 0
     elif pressed_keys[K_DOWN]:
         self.tank.direction = Vec2d(0, 1)
         if goal is None:
             self.tank.speed = self.tank.normal_speed
         elif goal.name == "bonus":
             self.tank.world.remove_entity(goal)
             self.tank.normal_speed += 48
             self.tank.canon_amount += 15
         else:
             self.tank.speed = 0
     else:
         self.tank.speed = 0
     # 控制开火
     if pressed_keys[K_SPACE]:
         self.tank.fire()
示例#23
0
def run():
    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
    world = World()
    # 这里定义的小写world变量名是一个实例,用来在后面传递给其他类
    # 当然,World类只有这一个实例
    w, h = SCREEN_SIZE
    clock = pygame.time.Clock()
    ant_image = pygame.image.load("ant.png").convert_alpha()
    leaf_image = pygame.image.load("leaf.png").convert_alpha()
    spider_image = pygame.image.load("spider.png").convert_alpha()

    for ant_no in range(ANT_COUNT):
        ant = Ant(world, ant_image)
        ant.location = Vec2d(randint(0, w), randint(0, h))
        # 随机放置每只蚂蚁的位置
        ant.brain.set_state("exploring")
        # 默认是搜索状态
        world.add_entity(ant)
# 一个一个添加蚂蚁们

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                return
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                exit()
# 让ESC也可以退出程序
        time_passed = clock.tick(30)
        # 可以改变帧率

        if randint(1, 10) == 1:
            leaf = Leaf(world, leaf_image)
            leaf.location = Vec2d(randint(0, w), randint(0, h))
            world.add_entity(leaf)
# 10分之一概率掉落新的叶子(是不是概率太大了?)

        if randint(1, 100) == 1:
            spider = Spider(world, spider_image)
            spider.location = Vec2d(-50, randint(0, h))
            spider.destination = Vec2d(w + 50, randint(0, h))
            world.add_entity(spider)

# 100分之一概率产生蜘蛛
# 蜘蛛总是从屏幕左侧-50处出发,走向屏幕右侧

        world.process(time_passed)
        world.render(screen)

        pygame.display.update()
示例#24
0
 def __init__(self, world, name, image):  # 定义通用属性,每一个都要赋予初始值
     self.world = world
     self.name = name
     self.image = image
     self.id = 0
     self.location = Vec2d(0, 0)  # 赋予初值,但是没什么意义,只是表示存在这个属性,后面还要修改
     self.speed = 0.
     self.direction = Vec2d(0, -1)  # 默认是朝下的(敌人)
     self.hp = 1  # 所有对象默认生命值 = 1
     self.size = TK
     self.invincible = False  # 默认不是无敌的
     self.collision_to_tank = True  # 默认对坦克有碰撞体积
     self.collision_to_canon = True  # 默认对炮弹有碰撞体积
     self.flag = 0  # 所属阵营(0表示中立,1表示玩家,2表示敌人)
     self.brain = StateMachine()
示例#25
0
 def initialize(self):
     for index in range(10):
         circle = []
         first = Vec2d(20 * index * 1.2, 0)
         for degree in xrange(0, 360, 5):
             circle.append(first.rotated(degree))
         self.circles.append(circle)
示例#26
0
    def __init__(self, common, init_pos, init_dir, img_file, speed):
        self.common = (self.surface, self.res, self.options) = common
        img = self.res.get_graphics(img_file)

        # Initialize the VecSprite superclass
        super(Ship, self).__init__(init_pos, init_dir, img, speed)

        # Movement. Ships can strafe, as opposed to any object
        self.__strafe = Vec2d(self.direction).rotated(0)
        self.__strafe_angle = 0

        # A ship may be headed automatically towards some target
        self.__target = None

        # When a ship is hit, it should flash (with yellow)
        self.__hit = False

        # The hitsurface is an overlay drawn when the ship is hit
        self.__hitsurface = self.image.copy()
        self.calculate_hitsurface()

        # Ship statistics
        self.__damage = 0
        self.__max_damage = 3
        # Used when ships explode
        self.__exploding = False
        self.__explode_counter = 1
示例#27
0
 def set_strafe(self, angle_degrees):
     """
     Set a strafe vector that is relative to the ship angle with given amount
     of degrees. 90 or -90 here will strafe to the sides, for instance
     """
     self.__strafe = Vec2d(self.direction).rotated(angle_degrees)
     self.__strafe_angle = angle_degrees
示例#28
0
 def __init__(self, angle=_START_ANGLE, length=_LENGTH):
     mdl_object.__init__(self, Vec2d((1.0, 0.0)).rotate_rad(angle))
     self.angle  = normalized_radian_angle(angle)
     self.length = length
     self.normal = -self
     self.angular_velocity = mdl_pad._ANG_VELOCITY
     self.corners = self.genCorners()
示例#29
0
    def __init__(self,
                 field_of_view=90,
                 num_of_sensors=5,
                 start_pos=Vec2d(0, 0)):
        self.pos = start_pos
        self.sensors = []
        for i in range(num_of_sensors):
            sensor = Sensor()
            self.sensors.append(sensor)

    # def update(self, particles):
    # 		# Update robot position
    #
    # 		# Using new posititon update sensor position
    # 		for sensor in self.sensors:
    # 				sensor.update(self.pos, particles)
    # 				# After updating sensor
    #
    # 				# Get reading of sensor
    #
    #
    #
    # 		#  Draw new robot
    #
    #
    # 		# Loop throw sensor draw sensor lines
    #
    # 		pass
示例#30
0
 def lateral_correct(self):
     # 先判断原始方向
     if self.direction in (Vec2d(-1, 0), Vec2d(1, 0)):  # 横向的
         s1 = self.location[0] // 12  # 取商的整数部分
         s2 = self.location[0] % 12  # 余数
         if s2 <= 6:
             self.location[0] = s1 * 12
         else:
             self.location[0] = s1 * 12 + 12
     else:  # 纵向的
         s1 = self.location[1] // 12
         s2 = self.location[1] % 12
         if s2 <= 6:
             self.location[1] = s1 * 12
         else:
             self.location[1] = s1 * 12 + 12
示例#31
0
 def calc_pos(self):
     self.pos = self.rel_pos.rotated(self.parent.facing_direction)#posizione rispetto alla nave
     #mo calcoliamo i proiettili
     self.type['facing_direction'] = self.parent.facing_direction + self.rel_direction
     self.type["speed"] = Vec2d.versor(self.type['facing_direction']) * self.type['launch_speed']
 def direction_changed(self):
     super().direction_changed()
     self.onWard_versor = Vec2d.versor(self.facing_direction)
     self.recalculate_cannon()