def main():
    pygame.init()

    background = (0, 0, 0)
    screen = pygame.display.set_mode((640, 480), 0, 32)
    sprite = pygame.image.load('dennis_0.bmp').convert()

    script = [
        4, 5, 6, 7, 6, 5, 0
    ]
    idx = 0.0
    index = 0

    clock = pygame.time.Clock()

    pos = (Vector2(*screen.get_size()) - Vector2(*(80, 80))) / 2
    target = pos

    heading = Vector2()

    while True:

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

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

        screen.fill(background)
        screen.blit(sprite, pos, (script[index] * 80, 0, 80, 80))
        pygame.display.update()

        if pygame.mouse.get_pressed()[0]:
            target = Vector2( *pygame.mouse.get_pos() ) - Vector2( *(80, 80) ) / 2
        idx += 1 / 4.
        index = int(idx) % (len(script)-1)
      
        params_vector = Vector2.from_points(pos, target)

        if params_vector.get_length() < 5:
            idx = 0
            index = len(script) - 1
            target = pos


        ## Averagely
        params_vector.normalize()
        pos += params_vector * 150 * time_passed_seconds
        
        ## kind2
        # pos += params_vector * time_passed_seconds

        ## king3
        # params_vector.normalize()
        # heading = heading + (params_vector * 5)
        # pos += heading * time_passed_seconds

        pygame.display.update()
Esempio n. 2
0
def line_segment_intersect(line_a, line_b):
    """
    return True if line_a intersect with line_b else False
    params should be LineSegment object
    """

    p1 = line_a.a
    p2 = line_a.b
    p3 = line_b.a
    p4 = line_b.b

    vec_a = Vector2.from_points(p3, p1)
    vec_b = Vector2.from_points(p3, p4)
    d1 = cross_product(vec_a, vec_b)

    vec_a = Vector2.from_points(p3, p2)
    vec_b = Vector2.from_points(p3, p4)
    d2 = cross_product(vec_a, vec_b)

    vec_a = Vector2.from_points(p1, p3)
    vec_b = Vector2.from_points(p1, p2)
    d3 = cross_product(vec_a, vec_b)

    vec_a = Vector2.from_points(p1, p4)
    vec_b = Vector2.from_points(p1, p2)
    d4 = cross_product(vec_a, vec_b)

    # normal intersect
    if d1 * d2 < 0 and d3 * d4 < 0:
        return True

    def on_segment(pi, pj, pk):
        # pi, pj, pk have to be a tuple as (x, y)
        return min(pi[0], pj[0]) <= pk[0] <= max(pi[0], pj[0]) \
            and min(pi[1], pj[1]) <= pk[1] <= max(pi[1], pj[1])

    # abnormal intersect test
    if d1 == 0 and on_segment(p3, p4, p1):
        return True

    if d2 == 0 and on_segment(p3, p4, p2):
        return True

    if d3 == 0 and on_segment(p1, p2, p3):
        return True

    if d4 == 0 and on_segment(p1, p2, p4):
        return True

    return False
Esempio n. 3
0
def cal_face_direct(start_point, end_point):
    best_direct = None
    cos_min = -1
    vec_to_target = Vector2.from_points(start_point, end_point)
    for vec_point, direct in cfg.Direction.VEC_TO_DIRECT.iteritems():
        vec = Vector2(vec_point)

        # cosine law for 2 vectors
        cos_current = cos_for_vec(vec, vec_to_target)
        if cos_current > cos_min:
            cos_min = cos_current
            best_direct = direct

    return best_direct
Esempio n. 4
0
def main():

	background_image_path=r'./picture/sushiplate.jpg'
	sprite_image_path='./picture/fugu.png'
	SCREEN_SIZE=(640,480)
	clock=pygame.time.Clock()
	position=Vector2(100.0,100.0)
	heading=Vector2()
	speed=100

	pygame.init()

	screen = pygame.display.set_mode(SCREEN_SIZE,0,32)
	pygame.display.set_caption("hello world")
	# font=pygame.font.SysFont('arial',16)
	# font_height=font.get_linesize()

	background=pygame.image.load(background_image_path).convert()
	sprite=pygame.image.load(sprite_image_path).convert_alpha()
	destination=Vector2(randint(0,640),randint(0,480))

	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()
		time_passed_seconds=time_passed/1000.0

		

		vector_to_mouse=Vector2.from_points(position,destination)

		if vector_to_mouse.get_length() > 1:
			heading=vector_to_mouse.normalize()
			position+=heading*time_passed_seconds*speed
		else:
			destination=Vector2(randint(0,640),randint(0,480))

		pygame.display.update()
Esempio n. 5
0
    def do_action(self, seconds):
        '''if self.jump_lock:
			self.current_image = self.stick_walk_images[self.count_image]
		else:

			if self.__check_jump_done(seconds):
				self.__jump_lock()
			self.current_image = self.stick_jump_images[self.count_image]'''

        if self.action_state == Stick.WALK_STATE:
            self.current_image = self.stick_walk_images[self.count_image]
        elif self.action_state == Stick.JUMP_STATE:
            if self.__check_jump_done(seconds):
                self.__jump_lock()
            self.current_image = self.stick_jump_images[self.count_image]
        elif self.action_state == Stick.RUN_STATE:
            self.current_image = self.stick_run_images[self.count_image]
        else:
            self.current_image = self.stick_walk_images[0]

        self.stick_position += self.stick_direction * seconds * self.speed_game
        self.stick_direction = Vector2(0, 0)
Esempio n. 6
0
def run():
    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
    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 xrange(ANT_COUNT):
        ant = Ant(world, ant_image)
        ant.location = Vector2(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
        time_passed = clock.tick(30)

        # if randint(1, 10) == 1:
        #     leaf = Leaf(world, leaf_image)
        #     leaf.location = Vector2(randint(0, w), randint(0, h))
        #     world.add_entity(leaf)
        #
        # if randint(1, 100) == 1:
        #     spider = Spider(world, spider_image)
        #     spider.location = Vector2(-50, randint(0, h))
        #     spider.destination = Vector2(w+50, randint(0, h))
        #     world.add_entity(spider)

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

        pygame.display.update()
 def destination(self, destination):
     self._destination = Vector2(destination)
 def _heading(self):
     return Vector2.from_points(self._position, self._destination)
Esempio n. 9
0
 def carry_stuff(self):
     self.destination = self.world.nest_location + (randint(
         -20, 20), randint(-20, 20)) - Vector2(self.image.get_size()) / 2
     self.speed = 60
     self.state = "carry_stuff"
from sys import exit
from gameobjects.vector2 import Vector2
from math import *

pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)

background = pygame.image.load(background_image_filename).convert()
sprite = pygame.image.load(sprite_image_filename).convert_alpha()

clock = pygame.time.Clock()

pygame.mouse.set_visible(False)
pygame.event.set_grab(True)

sprite_pos = Vector2(200, 150)
sprite_speed = 300.
sprite_rotation = 0.
sprite_rotation_speed = 360. # Degrees per second

if pygame.joystick.get_count() > 0:
    joystick = pygame.joystick.Joystick(0)
    joystick.init()
else:
    joystick = None

while True:
    
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
clock = pygame.time.Clock()

position = Vector2(100.0, 100.0)
speed = 250
heading = Vector2()

while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()
        if event.type == MOUSEBUTTONDOWN:
            destination_x = event.pos[0] - sprite.get_width()/2.0 
            destination_y = event.pos[1] - sprite.get_height()/2.0 
            destination = (destination_x, destination_y)

            
            heading = Vector2.from_points(position, destination) 
            heading.normalize()

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

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

    distance_moved = time_passed_seconds * speed 
    position += heading * distance_moved 
    pygame.display.update()
Esempio n. 12
0
 def __init__(self, world, parent, position, heading):
     super(SpiralsBullet,
           self).__init__(world, 'spirals', parent, position, heading, 52,
                          'media/spirals.png', 10)
     self.action_angle = math.pi * 0.3
     self.origin_point = Vector2(position)
 def position(self, position):
     self._position = Vector2(position)
Esempio n. 14
0
#adicionando o nome para a tela
pygame.display.set_caption("Space Game")

background = pygame.image.load(background_image_filename).convert()
nave = pygame.image.load(foguete).convert_alpha()
alien = pygame.image.load(inimigo).convert_alpha()
bala = pygame.image.load(bala_alien).convert_alpha()

#Variáveis
clock = pygame.time.Clock()

alien_pos_x = randint((SCREEN_SIZE[0] + alien.get_height()) / 2,
                      SCREEN_SIZE[0] - alien.get_height())
alien_pos_y = randint(0, (SCREEN_SIZE[1]) - alien.get_height())

direction_alien = Vector2(1, 1)

posicao_fogete = Vector2(randint(nave.get_height(), 100),
                         randint(nave.get_height(), 200))
posicao_alien = Vector2(alien_pos_x, alien_pos_y)

posicao_tiro = Vector2(alien_pos_x, alien_pos_y)

lista_tiros = []

tempo_tiro = 0
pode_atirar = True


def verifica_jogo_fechado():
    for event in pygame.event.get():
Esempio n. 15
0
screen = pygame.display.set_mode((640,480),0,32)
background = pygame.image.load(background_image_filename).convert()
sprite = pygame.image.load(sprite_image_filename).convert_alpha()

clock = pygame.time.Clock()

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()
    time_passed_seconds = time_passed / 1000.0

    destination = Vector2(*pygame.mouse.get_pos()) - Vector2(*sprite.get_size())/2
    vector_to_mouse = Vector2.from_points(position, destination)
    vector_to_mouse .normalize()

    heading = heading + (vector_to_mouse * .6)

    position += heading * time_passed_seconds
    
    pygame.display.update()
Esempio n. 16
0
import pygame, sys, math
from gameobjects.vector2 import Vector2

pygame.init()

map_file = 'images/map.png'
SCR_SIZE = SCR_W, SCR_H = 640, 480

screen = pygame.display.set_mode(SCR_SIZE, 0, 32)

map_img = pygame.image.load(map_file).convert()

map_pos = Vector2(0, 0)

scroll_speed = 1000.0

clock = pygame.time.Clock()

joystick = None

if pygame.joystick.get_count() > 0:
    joystick = pygame.joystick.Joystick(0)
    joystick.init()

print(joystick)
if joystick is None:
    print("Sorry, you need a joystick for this demo")
    pygame.quit()
    exit()

print(f"num of joystick axis: {joystick.get_numaxes()}")
Esempio n. 17
0
#ml1 = MapLoader.MapLoader(BLOCK_SIZE_X,BLOCK_SIZE_Y,640,640,'/home/thomp/pygame/thomp-rpg/build1/maps/level1/room1/room1-64.jpg', True)
#ml2 = MapLoader.MapLoader(BLOCK_SIZE_X,BLOCK_SIZE_Y,640,640,'/home/thomp/pygame/thomp-rpg/build1/maps/level1/room2/room2-64.jpg', False)
#current_map = ml1
#screen = pygame.display.set_mode((current_map.x, current_map.y), 0, 32)
#background = current_map.getImage()
#current_map.parseCSV('maps/level1/room1/room1.csv')
#current_map.setUpLink(ml2)
#ml2.parseCSV('maps/level1/room2/room2.csv')
#ml2.setDownLink(ml1)


# Character object setup
start_block = level_1_map.getActiveRoom().getCharBlock()


start_pos = Vector2(64,64)
player = Character.Character(True,start_pos) 
player.loadSpriteSheets('sprites/playerLeft.txt', 'sprites/playerRight.txt')
leftSpriteSheet = player.getLeftSpriteSheet()
rightSpriteSheet = player.getRightSpriteSheet()
frame = 0 
image = rightSpriteSheet[frame]  # starting character sprite frame
sprite_pos = player.getPosition()


#def move( x_distance, y_distance, current_pos, restricted, upEE, downEE, sprite_sheet ) :
def move( x_distance, y_distance, current_pos, ml, sprite_sheet ) :
	global image
	global frame
	global current_map
	# Check to see if block is restricted
Esempio n. 18
0
# 定义一些变量
# 目标
boat1 = Boat(150, 100, 0, 40, 20, 20)

PATROL_ARRAY_SIZE = 8
ZIGZAG_ARRAY_SIZE = 4

# 巡逻模式
patrol_patterns = []
# 蛇形模式
zigzag_patterns = []

# 数据类型为StateChangeData,用于记录这些模式在执行时位置和方向上的变化
# self, initial_heading_degrees, initial_position, delta_heading_degress, delta_position, current_control_index
pattern_tracking = StateChangeData(0, Vector2(0, 0), 0, 0, 0)

# 前进200
control_data = ControlData(delta_heading_degrees_limit=0,
                           delta_position_limit=200,
                           limit_heading_change=False,
                           limit_position_change=True)
patrol_patterns.append(control_data)
# 右转90度
control_data = ControlData(delta_heading_degrees_limit=90,
                           delta_position_limit=0,
                           limit_heading_change=True,
                           limit_position_change=False)
patrol_patterns.append(control_data)
# 前进200
control_data = ControlData(delta_heading_degrees_limit=0,
Esempio n. 19
0
arrows=[]
player = pygame.image.load("02.png")
#castle = pygame.image.load("01.png")
#grass = pygame.image.load("03.png")
plate = pygame.image.load("04.png")
#arrow = pygame.image.load("05.png")
gun = pygame.image.load("06.png")
fort = pygame.image.load("07.png")

#ball
sprite_image_filename_ball = '05.png'
screen = pygame.display.set_mode((640,480))
#background = screen
clock = pygame.time.Clock()
sprite_image_filename_ball = pygame.image.load(sprite_image_filename_ball).convert_alpha()
position_ball = Vector2(150,150)
position_ball_set = []
position_ball_set.append(position_ball)
position_ball_set_1=[]
position_ball_set_1.append(position_ball)
speed_ball_x = [1.5]
speed_ball_y = [-0.4]
speed = 3.0
timer_ball = 0
time_set_ball = [0]

#cm
sprite_image_filename_cm = '08.png'
screen = pygame.display.set_mode((640,480))
background = screen
clock = pygame.time.Clock()
 def arrangePosition(self):
     self._position = Vector2(self._rect.center)
Esempio n. 21
0
 def is_collide(self, entity1, entity2):
     distance = Vector2.get_magnitude(entity1.pos - entity2.pos)
     if distance < entity1.radius + entity2.radius:
         return True
     else:
         return False
Esempio n. 22
0
 def check_conditions(self):
     if Vector2(*NEST_POSITION).get_distance_to(self.ant.location) < NEST_SIZE:
         if (randint(1, 10) == 1):
             self.ant.drop(self.ant.world.background)
             return "exploring"
     return None
Esempio n. 23
0
 def collide(self, bubble):
     distance = Vector2.get_magnitude(entity.pos - self.pos)
     if distance < self.radius + bubble.radius:
         return True
     else:
         return False
Esempio n. 24
0
def rotate_vector2(vec2, degrees):
    rotation_matrix = Matrix44.z_rotation(math.radians(degrees))
    transformed = rotation_matrix.transform_vec3(Vector3(vec2.x, vec2.y, 0))
    return Vector2(transformed.x, transformed.y)
Esempio n. 25
0
 def __init__(self):
     self.position = Vector2(randint(40, w - 40), randint(40, h - 40))
     self.angle = 0
     self.arrows = []
 def direction(self, direction):
     self._direction = Vector2(Cardinal().getUnitVectorByDirection(direction))
Esempio n. 27
0
        map_right = Rect(1600, 0, 1, 1600)
        map_borders = [map_bottom, map_left, map_right, map_top]

        # print(player_birth_pos)
        # print(boxes_pos)
        # print(can_pass)
        # print(can_not_pass)
        # print(AI_birth_pos)
        # print(prop_car_birth_pos)

        # 获取当前时间
        current_time = pygame.time.get_ticks()
        # 创建一个新的玩家对象
        new_player = player_class.Player()
        # 生成玩家坦克
        p_tank = new_player.birth_a_tank(screen, Vector2(400,
                                                         240), current_time,
                                         player_birth_pos["player"].copy())
        # 将玩家坦克加入玩家坦克的精灵组中
        groups["player_tank"].add(p_tank)

        # 创建基地
        screen_start_pos = Vector2(441, 1096)
        base = base_class.Base(screen)
        base.put(player_birth_pos["base"], screen_start_pos)
        groups["base"].add(base)

        # 生成道具箱
        for pos in boxes_pos:
            c = randint(0, 1)
            if c == 0:
                A = hinder_classes.AmmunitionSupplyBox(screen)
Esempio n. 28
0
 def random_destination(self):
     # Select a point in the screen
     w, h = SCREEN_SIZE
     self.ant.destination = Vector2(randint(0, w), randint(0, h))
Esempio n. 29
0
import pygame
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2

# constants
screensize = screenwidth, screenheight = 640, 480
bgimage = 'sushiplate.jpg'
spriteimage = 'fugu.png'
black = pygame.Color('black')
white = pygame.Color('white')
red = pygame.Color('red')
green = pygame.Color('green')
blue = pygame.Color('blue')
fps = 60
pos = Vector2(200, 150)
speed = 60

# initialize pygame
pygame.init()
screen = pygame.display.set_mode(screensize, 0, 32)
bgsurf = pygame.image.load(bgimage).convert()
spritesurf = pygame.image.load(spriteimage).convert_alpha()
# clock object
clock = pygame.time.Clock()


def getText(msg, color=blue, fontsize=18):
    font = pygame.font.SysFont('bitstreamveraserif', fontsize)
    textsurf = font.render(msg, True,
                           color)  # font.render(text,antialias,fg,bg)
Esempio n. 30
0
import pygame
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2

pygame.init()

screen = pygame.display.set_mode((640, 480), 0, 32)

background = pygame.image.load(background_image_filename).convert()
sprite = pygame.image.load(sprite_image_filename).convert_alpha()

clock = pygame.time.Clock()

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()
    time_passed_seconds = time_passed / 1000.0

    # 参数前面加*意味着把列表或元组展开
    desitination = Vector2( *pygame.mouse.get_pos() ) \
Esempio n. 31
0
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2
from math import *

# constants
screensize = screenwidth, screenheight = 640, 480
bgimage = 'sushiplate.jpg'
spriteimage = 'fugu.png'
black = pygame.Color('black')
white = pygame.Color('white')
red = pygame.Color('red')
green = pygame.Color('green')
blue = pygame.Color('blue')
fps = 60
pos = Vector2(200, 150)
speed = 300
rotation = 0
rotationspeed = 360  # degrees per second

# initialize pygame
pygame.init()
screen = pygame.display.set_mode(screensize, 0, 32)
bgsurf = pygame.image.load(bgimage).convert()
spritesurf = pygame.image.load(spriteimage).convert_alpha()
# clock object
clock = pygame.time.Clock()


def getText(msg, color=blue, fontsize=18):
    font = pygame.font.SysFont('bitstreamveraserif', fontsize)
Esempio n. 32
0
from sys import exit
from gameobjects.vector2 import Vector2
from math import *
#
pygame.init()
#
font = pygame.font.SysFont("arial",32);
font_height = font.get_linesize()
screensize = (1024,720)
screen = pygame.display.set_mode(screensize,0,32)
background = pygame.image.load(background_image_filename).convert()
star = pygame.image.load(star_image_filename)
sprite = pygame.image.load(sprite_image_filename)
clock = pygame.time.Clock()
#
sprite_pos = Vector2(200, 150)
sprite_speed = 300.
sprite_rotation = 0.
sprite_rotation_speed = 360.
star_position = Vector2(100.0, 100.0)
star_speed = 250.
star_heading = Vector2()
#

while True:
  for event in pygame.event.get():
    if event.type == QUIT:
      exit()
    if event.type == MOUSEBUTTONDOWN:
      star_destination = Vector2(*event.pos) - Vector2(*star.get_size())/2
      star_heading = Vector2.from_points(star_position, star_destination)
Esempio n. 33
0
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2

background_image_filename = 'foto-igti.jpg'
sprite_image_filename = 'selo-bootcamp.png'

pygame.init()

screen = pygame.display.set_mode((640, 480), 0, 32)
background = pygame.image.load(background_image_filename).convert()
sprite = pygame.image.load(sprite_image_filename).convert_alpha()

clock = pygame.time.Clock()

sprite_pos = Vector2(200, 150)
sprite_speed = 300

while True:

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

    pressed_keys = pygame.key.get_pressed()

    key_direction = Vector2(0, 0)
    
    if pressed_keys[K_LEFT]:
        key_direction.x = -1
Esempio n. 34
0
    # 消除锯齿
    pygame.draw.aalines(screen, color, True, [(p1['x'], p1['y']),
                                              (p2['x'], p2['y']),
                                              (p3['x'], p3['y']),
                                              (p4['x'], p4['y']),
                                              (p5['x'], p5['y'])], 1)
    # 画出中心
    pygame.draw.aaline(screen, color, (center_x, center_y),
                       (center_x, center_y), 1)


# 游戏主循环
while True:
    time_passed = clock.tick(30)
    # force是施加在单位上的力,force.x表示转向方面的力,force.y表示前进后退方向的力
    force = Vector2(0, 0)

    pressed_keys = pygame.key.get_pressed()
    if pressed_keys[K_ESCAPE]:
        exit()
    if pressed_keys[K_LEFT]:
        force.x = -1
    if pressed_keys[K_RIGHT]:
        force.x = 1
    if pressed_keys[K_UP]:
        force.y = 1
    if pressed_keys[K_DOWN]:
        force.y = -1

    for event in pygame.event.get():
        if event.type == QUIT:
Esempio n. 35
0
 def entry_actions(self):
     self.ant.speed = 60.
     random_offset = Vector2(randint(-20, 20), randint(-20, 20))
     self.ant.destination = Vector2(*NEST_POSITION) + random_offset
Esempio n. 36
0
def do_unit_ai(units, i):

    # 临近单位数量
    neighbors = 0
    do_block = WIDE_VIEW or LIMITED_VIEW or NARROW_VIEW

    # 初始化
    average_position = Vector2(0, 0)
    average_speed = Vector2(0, 0)
    # force是指,为了调整单位,而施加在单位上的力,既包括转向的力,也包括加减速的力
    force = Vector2(0, 0)

    # 检查并收集临近单位的信息
    for j in range(0, len(units), 1):
        if j != i:
            in_view = False
            delta = Vector2(units[j].center_x, units[j].center_y) - Vector2(
                units[i].center_x, units[i].center_y)
            # units[j]在units[i]的相对坐标系中的位置
            w = v_rotate_2d(delta, 90 - units[i].direction)
            if w.y == 0:
                angle_b_degrees = 90
                view_field_degrees = angle_b_degrees
            elif w.y > 0:
                angle_b_degrees = math.degrees(math.atan(math.fabs(w.x / w.y)))
                view_field_degrees = angle_b_degrees
            else:
                angle_b_degrees = math.degrees(math.atan(math.fabs(w.x / w.y)))
                view_field_degrees = 180 - angle_b_degrees

            if WIDE_VIEW:
                if view_field_degrees <= WIDE_VIEW_FIELD_ANGLE_DEGREES / 2.0:
                    in_view = True
                else:
                    in_view = False
                view_field_redius = WIDE_VIEW_FIELD_REDIUS_FACTOR * UNIT_LENGTH
            if LIMITED_VIEW:
                if view_field_degrees <= LIMITED_VIEW_FIELD_ANGLE_DEGREES / 2.0:
                    in_view = True
                else:
                    in_view = False
                view_field_redius = LIMITED_VIEW_FIELD_REDIUS_FACTOR * UNIT_LENGTH
            if NARROW_VIEW:
                if view_field_degrees <= NARROW_VIEW_FIELD_ANGLE_DEGREES / 2.0:
                    in_view = True
                else:
                    in_view = False
                view_field_redius = NARROW_VIEW_FIELD_REDIUS_FACTOR * UNIT_LENGTH
            if in_view:
                # 如果在视野内,并且距离小于安全距离,那么应该远离
                if delta.length <= view_field_redius:
                    # TODO
                    average_position += Vector2(units[j].center_x,
                                                units[j].center_y)
                    speed_x = units[j].speed * math.cos(
                        math.radians(units[j].direction))
                    speed_y = units[j].speed * math.sin(
                        math.radians(units[j].direction))
                    average_speed += Vector2(speed_x, speed_y)
                    neighbors += 1

            # 分隔
            # 分隔意指我们想让每个单位彼此间保持最小距离。
            # 即,根据凝聚和对齐规则,他们会试着靠近一点。我们不想让这些单位撞在一起,或者更糟的是,在某个时刻重叠在一起。
            # 因此,我们采用分隔手段,让每个单位和其视野内的单位保持某一预定的最小间隔距离
            if in_view:
                if delta.length <= SEPARATION_FACTOR * UNIT_LENGTH:
                    # 因为此处是计算分隔,所以m和计算凝聚和对齐时不同
                    if w.x < 0:
                        # 如果w的x值小于0,则必须右转(左侧)
                        m = 1
                    elif w.x > 0:
                        # 如果w的x值大于0,则表示临近单位的平均位置位于units[i]的右侧,units[i]需要左转
                        m = -1
                    # delta是units[j]和units[i]的距离
                    force.x += m * STREERING_FORCE * SEPARATION_FACTOR * UNIT_LENGTH / delta.length

    # 凝聚规则
    # 凝聚意指,我们想让所有单位待在同一个群体当中。
    # 为了满足这条规则,每隔单位都应该朝其临近单位的平均位置前进
    if do_block and neighbors > 0:
        average_position = average_position / neighbors

        speed_x = units[i].speed * math.cos(math.radians(units[i].direction))
        speed_y = units[i].speed * math.sin(math.radians(units[i].direction))
        v = Vector2(speed_x, speed_y)
        v.normalise()
        u = average_position - Vector2(units[i].center_x, units[i].center_y)
        u.normalise()
        w = v_rotate_2d(u, 90 - units[i].direction)

        # 确定和转向力有关的乘数m
        if w.x < 0:
            # 如果w的x值小于0,则必须右转(左侧)
            m = -1
        elif w.x > 0:
            # 如果w的x值大于0,则表示临近单位的平均位置位于units[i]的右侧,units[i]需要左转
            m = 1

        # 最后,做一个快速检查,以得知v和u的内积是否大于-1且小于1。这一定要做,因为这个内积要在计算两向量夹角的时候用到,
        # 而反余弦函数的自变量范围在-1到1之间
        cos_result = (v.x * u.x + v.y * u.y) / (v.length * u.length)
        if math.fabs(cos_result) < 1:
            # 实际计算满足凝聚规则的转向力。
            # 上面的m实际上已经计算出应该向左还是向右转,现在自己算的是转向的力度大小
            # fs.x += m * 一个系数 * math.degrees(math.acos(v*u))
            # 平均位置向量和速度向量夹角,也就是平均位置向量与units[i]的方向的夹角,夹角越大,也就是所需要的转向力越大
            force.x += m * STREERING_FORCE * math.degrees(
                math.acos(cos_result))

    # 对齐规则
    # 对齐,意指我们想让群聚中所有的单位都朝大概的方位运动。
    # 为了实现这条规则,每隔单位都应该在行进时,试着以等同于临近单位行进方向的方向前进。
    if do_block and neighbors > 0:
        average_speed = average_speed / neighbors
        u = average_speed
        u.normalise()

        speed_x = units[i].speed * math.cos(math.radians(units[i].direction))
        speed_y = units[i].speed * math.sin(math.radians(units[i].direction))
        v = Vector2(speed_x, speed_y)
        v.normalise()

        # 平均速度的向量相对于units[i]的的局部坐标系中的表示
        w = v_rotate_2d(u, 90 - units[i].direction)

        # 确定和转向力有关的乘数m
        if w.x < 0:
            # 如果w的x值小于0,则必须右转(左侧)
            m = -1
        elif w.x > 0:
            # 如果w的x值大于0,则表示临近单位的平均位置位于units[i]的右侧,units[i]需要左转
            m = 1

        # 最后,做一个快速检查,以得知v和u的内积是否大于-1且小于1。这一定要做,因为这个内积要在计算两向量夹角的时候用到,
        # 而反余弦函数的自变量范围在-1到1之间
        cos_result = (v.x * u.x + v.y * u.y) / (v.length * u.length)
        if math.fabs(cos_result) < 1:
            # 实际计算满足凝聚规则的转向力。
            # 上面的m实际上已经计算出应该向左还是向右转,现在自己算的是转向的力度大小
            # fs.x += m * 一个系数 * math.degrees(math.acos(v*u))
            # 平均速度向量和速度向量夹角,也就是平均位置向量与units[i]的方向的夹角,夹角越大,也就是所需要的转向力越大
            force.x += m * STREERING_FORCE * math.degrees(
                math.acos(cos_result))

    # 处理转向力对units[i]的影响
    update_single_unit(units[i], force)
Esempio n. 37
0
 def random_destination(self):
     w, h = SCREEN_SIZE
     self.ant.destination = Vector2(randint(0, w), randint(0, h))
Esempio n. 38
0
 def move(self, time_passed, dist=Vector2(0, -1)):
     self.pos += time_passed * self.speed * dist