예제 #1
0
def run():
	pygame.init()
	screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)

	game = Game(screen)

	clock = pygame.time.Clock()
	bat_image = pygame.image.load("ant.png").convert_alpha()
	ball_image = pygame.image.load("ball.png").convert_alpha()

	bat = Bat("p1", game, bat_image, 300, Vector2(320, 350))
	bat2 = Bat("p2", game, bat_image, 300, Vector2(320, 50))
	direction = Vector2(1, 1).get_normalised()
	ball = Ball("ball", game,  ball_image, 100, Vector2(300, 200), direction)
	game.add_entity(bat, bat2, ball)

	while True:
		for event in pygame.event.get():
			if event.type == QUIT:
				return
		time_passed = clock.tick(30)
		pressed_keys = pygame.key.get_pressed()
		if pressed_keys[K_LEFT]:
			bat.left()
		elif pressed_keys[K_RIGHT]:
			bat.right()
		if pressed_keys[K_a]:
			bat2.left()
		elif pressed_keys[K_d]:
			bat2.right()

		game.process(time_passed)
		game.render()

		pygame.display.update()
예제 #2
0
    def update_points(self, size):

        self.t_points = []
        self.b_points = []
        self.l_points = []
        self.r_points = []

        self.t_margin = self.margins[0]
        self.b_margin = size[1] - self.margins[1]
        self.l_margin = self.margins[2]
        self.r_margin = size[0] - self.margins[3]

        h_step = (self.r_margin - self.l_margin) / float(self.res)
        v_step = (self.b_margin - self.t_margin) / float(self.res)

        # Top / Bottom
        for x in range(self.res + 1):
            self.t_points.append(
                Vector2(x * h_step + self.l_margin, self.t_margin))
            self.b_points.append(
                Vector2(x * h_step + self.l_margin, self.b_margin))

        # Left / Right
        for y in range(self.res + 1):
            self.l_points.append(
                Vector2(self.l_margin, y * v_step + self.t_margin))
            self.r_points.append(
                Vector2(self.r_margin, y * v_step + self.t_margin))
예제 #3
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()
    # Add all our ant entities
    for ant_no in range(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)
        # Add a leaf entity 1 in 20 frames
        if randint(1, 10) == 1:
            leaf = Leaf(world, leaf_image)
            leaf.location = Vector2(randint(0, w), randint(0, h))
            world.add_entity(leaf)
        # Add a spider entity 1 in 100 frames
        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()
예제 #4
0
    def __init__(self, position, speed, image, bounce_sound):

        self.position = Vector2(position)
        self.speed = Vector2(speed)
        self.image = image
        self.bounce_sound = bounce_sound
        self.age = 0.0
예제 #5
0
    def __init__(self, pos, size, world, speed=200, entity_follow=None):
        """
        Parameters:
            pos - Vector2 indicating where on the screen the camera should render
            size - Size of the camera
            world - World object that the camera will take entities from to render
            speed - Movement speed of the camera
            entity_follow - The entity the camera should follow
        """
        super().__init__(pos, world)

        # self.position = Vector2(pos)
        self.size = Vector2(size)
        self.speed = speed
        self.physics = CameraPhysicsComponent()
        self.input = CameraInputComponent()

        self.world_pos = Vector2()
        self.scale = 1  # [unused]
        # self.rotation = 0  # [unused] Z-rotation degrees
        # self.rotation_speed = 10
        # self.rotation_direction = 0  # -1 to 1

        # self.world = world
        self.entity_follow = entity_follow

        self._current_entity_index = -1
def do_intercept(boat1, boat2):
    time_passed = clock.tick(30)
    time_passed_seconds = time_passed / 1000.0

    # 计算运动
    # 计算boat1的运动
    speed = boat1.speed
    angle_degrees = boat1.direction
    speed_x = speed * math.cos(math.radians(angle_degrees))
    speed_y = speed * math.sin(math.radians(angle_degrees))
    boat1.center_x = boat1.center_x + speed_x * time_passed_seconds
    boat1.center_y = boat1.center_y + speed_y * time_passed_seconds

    # 目标的速度向量
    vector_speed_boat1 = Vector2(speed_x, speed_y)
    # 追击者的速度向量
    speed_boat2 = boat2.speed
    angle_degrees_boat2 = boat2.direction
    speed_x_boat2 = speed_boat2 * math.cos(math.radians(angle_degrees_boat2))
    speed_y_boat2 = speed_boat2 * math.sin(math.radians(angle_degrees_boat2))
    vector_speed_boat2 = Vector2(speed_x_boat2, speed_y_boat2)

    # 速度向量之差
    vector_speed_diff = vector_speed_boat1 - vector_speed_boat2

    # 计算拦截
    # 追击者与目标之间的距离向量
    vector_distance = Vector2(boat1.center_x - boat2.center_x, boat1.center_y - boat2.center_y)

    # 相遇的时间
    expected_time_to_intercept = vector_distance.get_length() / vector_speed_diff.get_length()

    # 计算预期的相遇点
    expected_intercept_point = Vector2(boat1.center_x + vector_speed_boat1.x * expected_time_to_intercept,
                                       boat1.center_y + vector_speed_boat1.y * expected_time_to_intercept)

    # boat2进行追逐
    # vector_u = v_rotate_2d(boat1, expected_intercept_point)
    vector_u = v_rotate_2d_2(expected_intercept_point, Vector2(boat2.center_x, boat2.center_y))
    # 将向量u标准化
    u_norm = vector_u.normalise()
    # print u_norm
    if u_norm.x > 0:
        boat2.direction -= ANGLE_SPEED * time_passed_seconds
    elif u_norm.x == 0:
        pass
    else:
        boat2.direction += ANGLE_SPEED * time_passed_seconds

    # 计算boat2的运动
    speed_boat2 = boat2.speed
    angle_degrees_boat2 = boat2.direction
    speed_x_boat2 = speed_boat2 * math.cos(math.radians(angle_degrees_boat2))
    speed_y_boat2 = speed_boat2 * math.sin(math.radians(angle_degrees_boat2))

    boat2.center_x = boat2.center_x + speed_x_boat2 * time_passed_seconds
    boat2.center_y = boat2.center_y + speed_y_boat2 * time_passed_seconds

    return expected_intercept_point
예제 #7
0
 def __init__(self, world, name, image):
     self.speed = 0
     self.name = name
     self.image = image
     self.world = world
     self.location = Vector2(0, 0)
     self.brain = StateMachine()
     self.destination = Vector2(0, 0)
예제 #8
0
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()
예제 #9
0
파일: test.py 프로젝트: hpfily/python
 def __init__(self, staysprit, runsprit):
     self.staysprit = staysprit
     self.runsprit = runsprit
     self.sprit = staysprit
     #        self.surface    = surface
     self.location = Vector2(1584, 1312)
     self.destination = Vector2(0, 0)
     self.direction = 'DownLeft'
     self.state = 'stay'
     self.speed = 200  #
예제 #10
0
파일: GameEntity.py 프로젝트: Leonxc/demo
 def __init__(self, id, image, world, location):
     self.name = "ant"
     self.id = id
     self.image = image
     self.world = world
     self.location = Vector2(location)
     self.destination = Vector2(randint(0, world.width),
                                randint(0, world.high))
     self.speed = 120
     self.senseRange = 60
     self.state = "explore"
예제 #11
0
    def rotate(surface_info, degrees):
        center_vec = Vector2(surface_info.surface.get_rect().center)
        points_diff = surface_info.offset + center_vec  # offset is -ive already, so just add it

        rotated_surf = pg.transform.rotate(surface_info.surface, -degrees)
        rotated_surf_center = Vector2(rotated_surf.get_rect().center)
        rotated_points_diff = common.rotate_vector2(points_diff, degrees)

        offset = -(rotated_surf_center + rotated_points_diff)
        # ^ re-add both components and * -1 to make offset easier to use (outer functions just add it)

        return SurfaceInfo.create(rotated_surf, offset)
예제 #12
0
파일: GameEntity.py 프로젝트: Leonxc/demo
 def __init__(self, id, image, world):
     self.name = "spider"
     self.id = id
     self.image = image
     self.world = world
     self.health = 25
     self.speed = 80
     self.state = "explore"
     self.location = Vector2(0, 0)
     self.destination = Vector2(randint(0, world.width - 20),
                                randint(0, world.high - 20))
     self.target = None
     self.senseRange = 120
예제 #13
0
파일: class79.py 프로젝트: johndpope/works
 def __init__(self,world,name,image,groups):
     pygame.sprite.Sprite.__init__(self,groups)
     #super(GameEntity,self).__init__(groups)
     self.world = world
     self.name  = name
     self.ID = 0
     self.image = image
     self.rect = self.image.get_rect()
     self.speed = 0
     self.location    = Vector2(0,0)
     self.destination = Vector2(0,0)
     # brain
     self.brain = Brain()
예제 #14
0
class NullGraphicsComponent(GraphicsComponent):
    _DUMMY_SURFACE_SIZE = Vector2(32, 32)
    _DUMMY_SURFACE_OFFSET = Vector2(-16, -32)
    _DUMMY_SURFACE = pg.Surface((32, 32))
    _DUMMY_SURFACE.fill(pg.Color('white'))

    def __init__(self):
        super().__init__()

    def render_info(self, entity):
        ri = RenderInfo()
        ri.surface_info = SurfaceInfo.create(self._DUMMY_SURFACE, self._DUMMY_SURFACE_OFFSET)
        ri.world_pos = entity.position
        return ri
def main():
    pygame.init()
    
    screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
    window_title = program.app
    pygame.display.set_caption(window_title)
    window_icon = pygame.image.load('images/fg_fsm_icon_32x32.jpg')
    pygame.display.set_icon(window_icon)
    
    world = World()
    
    w, h = SCREEN_SIZE 
    
    clock = pygame.time.Clock()
    
    ghoul_image = pygame.image.load("images/ghoul.png").convert_alpha()
    drum_image = pygame.image.load("images/drum.png").convert_alpha()
    glowing_one_image = pygame.image.load("images/glowing_one.png").convert_alpha()
    
    #add the drum entities
    for i in xrange(DRUM_COUNT):
        drum = Drum(world, drum_image)
        drum.location = Vector2(randint(24, w - 24), randint(24, h - 24))
        world.add_entity(drum)

    # add all our glowing one entities
    for i in xrange(GLOWING_ONE_COUNT):
        glowing_one = Glowing_One(world, glowing_one_image)
        glowing_one.location = Vector2(randint(24, w - 24), randint(24, h - 24))
        glowing_one.brain.set_state("exploring")
        world.add_entity(glowing_one)

    # add all our ghoul entities
    for i in xrange(GHOUL_COUNT):
        ghoul = Ghoul(world, ghoul_image)
        ghoul.location = Vector2(randint(24, w - 24), randint(24, h - 24))
        ghoul.brain.set_state("exploring")
        world.add_entity(ghoul)
        
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            
        time_passed = clock.tick(30)
        
        world.process(time_passed)
        world.render(screen)
        
        pygame.display.update()
예제 #16
0
def initial_pattern_tracking(boat, pattern_tracking):
    pattern_tracking.current_control_index = 0
    pattern_tracking.delta_heading_degress = 0
    pattern_tracking.delta_position = 0

    pattern_tracking.initial_heading = boat.direction
    pattern_tracking.initial_position = Vector2(boat.center_x, boat.center_y)
예제 #17
0
파일: ai1.py 프로젝트: Lee7goal/sagit
 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
예제 #18
0
def run_game():
    pygame.init()
    w, h = SCREEN_SIZE
    screen = pygame.display.set_mode((SCREEN_SIZE), 0, 32)
    world = World()
    world.render(screen)
    ant_image = pygame.image.load("ant.png").convert_alpha()
    leaf_image = pygame.image.load("leaf.png").convert_alpha()
    clock = pygame.time.Clock()

    # generate ant
    for i in range(ANT_COUNT):
        ant = Ant(world, ant_image)
        ant.location = Vector2(randint(0, w), randint(0, h))
        # ant.render(screen)
        ant.brain.set_state("exploring")
        world.add_entity(ant)

    done = True
    while done:
        for event in pygame.event.get():
            if event.type == QUIT:
                exit()
        time_passed = clock.tick(30)
        # if randint(1,10) == 1:
        #     leaf = Leaf(world, leaf_image)
        #     # leaf.render(screen)
        #     leaf.location = Vector2(randint(0,w),randint(0,h))
        #     world.add_entiyt(leaf)

        world.process(time_passed)
        world.render(screen)
        pygame.display.update()
예제 #19
0
 def keys_event_handle(cls, pressed_keys, p_tank, current_time, screen_pos,
                       bullets, special_bullets):
     move = Vector2(0, 0)
     # 获取玩家坦克移动方向
     if pressed_keys[K_w]:
         move.y -= 1
         p_tank.change_direction(K_UP)
     elif pressed_keys[K_a]:
         move.x -= 1
         p_tank.change_direction(K_LEFT)
     elif pressed_keys[K_s]:
         move.y += 1
         p_tank.change_direction(K_DOWN)
     elif pressed_keys[K_d]:
         move.x += 1
         p_tank.change_direction(K_RIGHT)
     # 针对开火按键的处理
     if pressed_keys[K_h]:
         bullet = p_tank.fire(current_time, screen_pos)
         if bullet:
             bullets.add(bullet)
     elif pressed_keys[K_j]:
         s_bullet = p_tank.fire_a_fire(current_time, screen_pos)
         if s_bullet:
             special_bullets.add(s_bullet)
     elif pressed_keys[K_k]:
         s_bullet = p_tank.fire_a_electricity(current_time, screen_pos)
         if s_bullet:
             special_bullets.add(s_bullet)
     elif pressed_keys[K_l]:
         s_bullet = p_tank.fire_a_ice(current_time, screen_pos)
         if s_bullet:
             special_bullets.add(s_bullet)
     return move
예제 #20
0
 def world_to_screen(self, pos):
     """Convert world coordinates (Vector2) to screen coordinates (Vector2)"""
     vec2to3 = Vector3(pos.x, pos.y, 0)
     transformed = self.get_tmatrix().get_inverse().transform(
         vec2to3)  # World to screen
     return Vector2(transformed[0] + self.position.x,
                    transformed[1] + self.position.y)
예제 #21
0
def movimento_foguete(posicao_atual_foguete):

    speed_foguete = 200

    pressed_keys = pygame.key.get_pressed()
    direction_foguete = Vector2(0, 0)

    if pressed_keys[K_LEFT]:
        direction_foguete.x = -1
    elif pressed_keys[K_RIGHT]:
        direction_foguete.x = 1

    if pressed_keys[K_UP]:
        direction_foguete.y = -1
    elif pressed_keys[K_DOWN]:
        direction_foguete.y = 1

    direction_foguete.normalize()

    time_passed_foguete = clock.tick(30)
    segundos_foguete = time_passed_foguete / 1000.0

    posicao_atual_foguete += direction_foguete * speed_foguete * segundos_foguete

    return (posicao_atual_foguete)
def v_rotate_2d(boat1, boat2):
    x_boat1 = boat1.center_x
    y_boat1 = boat1.center_y

    x_boat2 = boat2.center_x
    y_boat2 = boat2.center_y

    # 全局坐标系下,相对位置的向量
    x1 = x_boat1 - x_boat2
    y1 = y_boat1 - y_boat2

    angle_a_degrees = boat2.direction
    if x1 == 0:
        if y1 > 0:
            angle_b_radians = math.pi * 0.5
        elif y1 == 0:
            pass
        else:
            angle_b_radians = -math.pi * 0.5
    else:
        angle_b_radians = math.atan(y1 * 1.0 / x1)
    angle_b_degrees = math.degrees(angle_b_radians)

    # boat1在boat2的局部坐标系下,boat1中心与局部坐标系原点连线到局部坐标系x轴的角度
    angle_c_degrees = 90 - (angle_a_degrees - angle_b_degrees)

    # 两船距离
    distance = math.sqrt(x1 ** 2 + y1 ** 2)
    x2 = distance * math.sin(math.radians(angle_c_degrees))
    y2 = distance * math.cos(math.radians(angle_c_degrees))
    return Vector2(x2, y2)
예제 #23
0
    def move(self, direction):
        """
        移动,设置朝向
        :param direction: 方向
        :return:
        """
        v = Vector2()
        if 'l' in direction:
            self.frame_row = 1
            v.x -= 1
        if 'r' in direction:
            self.frame_row = 2
            v.x += 1
        if 'u' in direction:
            self.frame_row = 3
            v.y -= 1
        if 'd' in direction:
            self.frame_row = 0
            v.y += 1
        if v.get_length() == 0:
            self.stop()
            return
        self.heading = v

        self.speed = self.move_speed
예제 #24
0
    def get_close_energy(self, location, search_range=100.0):
        location = Vector2(*location)
        for entity in self.energy_stones.values():
            distance = location.get_distance_to(entity.location)
            if distance < search_range:
                return entity

        return None
예제 #25
0
 def birth_a_tank(self, screen, pos, current_time, map_pos=Vector2(0, 0)):
     if self.life > 0:
         tank = tank_classes.PlayerTank(screen)
         tank.birth(pos, current_time, map_pos)
         self.tank = tank
         self.life -= 1
         return tank
     return None
예제 #26
0
def get_objects_position_for_base(map_name, object_layer_name):
    tiled_map = load_pygame(map_name)
    object_layer = tiled_map.get_layer_by_name(object_layer_name)
    positions = {}
    for a_object in object_layer:
        positions[a_object.name] = Vector2(a_object.x + a_object.width / 2,
                                           a_object.y + a_object.height / 2)
    return positions
예제 #27
0
 def move(self, time_passed, dist=Vector2(1, 1)):
     if dist is not None:
         move_distance = self.speed * time_passed * dist
         if dist[1] > -1:
             self.image = plane_back_im
         else:
             self.image = plane_front_im
         self.pos += move_distance
예제 #28
0
    def check_conditions(self):

        # If inside the nest, randomly drop the object
        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
예제 #29
0
 def get_close_entity(self, name, location, range=100.):
     location = Vector2(*location)
     for entity in self.entities.itervalues():
         if entity.name == name:
             distance = location.get_distance_to(entity.location)
             if distance < range:
                 return entity
     return None
예제 #30
0
    def render(self, screen):
        # Overridding the default render method
        w, h = self.image.get_size()
        x, y = self.location
        W, H = RESOLUTION

        # Reseting original image location
        if abs(x) == w:
            self.location = Vector2(0, y)
            x = 0

        # Blitting the image loop
        if x - w < W:
            location = Vector2(x + w, y)
            screen.blit(self.image, location)

        screen.blit(self.image, self.location)