def enter(self, character): '''The actor will remain inside as long as the parent's death toll is not 0.''' character.body.set_velocity(vec2d(0, 0)) if self.parent.death_toll == 0: return True else: character.body.set_velocity(vec2d(0, 0)) return False
def enter(self, character): '''The actor will remain inside as long as the parent's death toll is not 0.''' character.body.set_velocity(vec2d(0,0)) if self.parent.death_toll==0: return True else: character.body.set_velocity(vec2d(0,0)) return False
def __init__(self, space, start, end, color=(0,255,255,255), radius=50): self.color = color self.start = start self.end = end self.radius = radius self.shape = cp.cpSegmentShapeNew(BACKGROUND, vec2d(*start), vec2d(*end), radius) self.shape.contents.e = 0.1 self.shape.contents.u = 0.2 cp.cpSpaceAddStaticShape(space, self.shape)
def seek1D(current_pos, target_pos, max_force): dist=target_pos-current_pos #force=40*dist #if max_force*max_force>force*force: #return force*vec2d(1,0) #else: if dist>0: return max_force*vec2d(1,0) elif dist<0: return -max_force*vec2d(1,0) return vec2d(0,0)
def __init__(self, space, mass, radius, pos=(300,300), color=(0,240,0,255)): self.color = color self.mass = mass self.radius = radius ball_moment = cp.cpMomentForCircle(mass, 5, 0.0, vec2d(0,0)) self.body = cp.cpBodyNew( mass, ball_moment ) self.shape = cp.cpCircleShapeNew(self.body, radius, vec2d(0.0, 0.0) ) self.shape.contents.e = 0.5 self.set_position( pos ) cp.cpSpaceAddBody(space, self.body) cp.cpSpaceAddShape( space, self.shape )
def __init__(self, original_body): Basic_Actor.__init__(self, original_body.body.get_position()) if not original_body.__class__ in Ghost.__images: Ghost.__images[ original_body.__class__] = original_body.image.copy() self.image = Ghost.__images[original_body.__class__].copy() self.image.set_alpha(255) #layer=0 and group=INCORPOREAL avoids the ghost from interacting with other things self.embody(self.rect.center, group='INCORPOREAL', layers=0) #Flies upwards without gravity self.body.set_velocity(vec2d(0, -400)) self.body.apply_force(vec2d(0, -9000), vec2d(0, 0))
def __init__(self, original_body): Basic_Actor.__init__(self, original_body.body.get_position()) if not original_body.__class__ in Ghost.__images: Ghost.__images[original_body.__class__]=original_body.image.copy() self.image=Ghost.__images[original_body.__class__].copy() self.image.set_alpha(255) #layer=0 and group=INCORPOREAL avoids the ghost from interacting with other things self.embody(self.rect.center, group='INCORPOREAL', layers=0) #Flies upwards without gravity self.body.set_velocity(vec2d(0,-400)) self.body.apply_force(vec2d(0,-9000), vec2d(0,0))
def embody(self, position, group='CAVEMEN', layers=255, friction=0): '''Initializes the sprite's body. See pymunk documentation to understand the parameters. All bodies will have a circular shape. The diameter of the circle is currently defined to be the sprite's rect width. This is probably wrong and I should think of a better way. There isn't any distintion between group and collision type at the moment, both are the same.''' space=Basic_Actor.level.space actor=self center=actor.rect.center radius=actor.rect.width/2.0 body=pm.Body(10,1e100) body.position=position[0], position[1] shape=pm.Circle(body, radius, vec2d(0,0)) #shape.set_layers(0) shape.group=groups[group] shape.collision_type = groups[group] shape.friction=friction actor.set_id(shape.id) space.add(shape) space.add(body) actor.body=body actor.shape=shape Basic_Actor.level.with_body.add(self)
def update(self, current_time): '''The skeleton has three states (not implemented through a state machine): * In free fall without touching any floor * Over some floor, being slowly buried. It scares the cavemen. * Deep into the ground. When the skeleton reaches this state it stops being a sprite and it becomes an fixed image. It also stops scaring the Cavemen.''' if hasattr(self,'current_floor'): #If it is here, then it means it is over some floor. if self.get_position()[1]<self.current_floor.get_position()[1]+5: #If the skeleton is not deep enough, it gets burried at a fixed rate if current_time>self.last_update+self.update_interval: self.set_position([self.get_position()[0], self.get_position()[1]+1]) self.last_update=current_time return else: #if the skeleton is deep enough, it stops scaring Cavemen and becomes a fixed image instead of a sprite. self.current_floor.death_toll-=1 self.current_floor.image.blit(self.image, [self.rect[0]-self.current_floor.rect[0], self.rect[1]-self.current_floor.rect[1]]) del self.body Basic_Actor.level.with_body.remove(self) Basic_Actor.level.all.remove(self) Basic_Actor.level.visible.remove(self) Sprite.kill(self) elif hasattr(self, 'body') and (self.body.get_velocity()-vec2d(0,0)).get_length()<0.01: #If the skeleton has a physical body and is not falling then it must mean it is over a floor, and gets attached to it, increasing its death_toll. It also removes its body so the physics engine doesn't affect it anymore. floor_collisions=Basic_Actor.State_Machine.floor_collisions collision_data=floor_collisions.pop(self.id, None) if collision_data is None: return self.current_floor=self.get_sprite(collision_data[1]) space=Basic_Actor.level.space space.remove_shape(self.shape) space.remove_body(self.body) self.current_floor.death_toll+=1 else: return
def embody(self, position, group='CAVEMEN', layers=255, friction=0): '''Initializes the sprite's body. See pymunk documentation to understand the parameters. All bodies will have a circular shape. The diameter of the circle is currently defined to be the sprite's rect width. This is probably wrong and I should think of a better way. There isn't any distintion between group and collision type at the moment, both are the same.''' space = Basic_Actor.level.space actor = self center = actor.rect.center radius = actor.rect.width / 2.0 body = pm.Body(10, 1e100) body.position = position[0], position[1] shape = pm.Circle(body, radius, vec2d(0, 0)) #shape.set_layers(0) shape.group = groups[group] shape.collision_type = groups[group] shape.friction = friction actor.set_id(shape.id) space.add(shape) space.add(body) actor.body = body actor.shape = shape Basic_Actor.level.with_body.add(self)
def do_action(self, solver, action): action = action[0] self.save_angle() cp.cpBodyApplyForce(self.base.body, vec2d(action*15000,0), vec2d(0,0)) cp.cpSpaceStep(self.space, dt) cp.cpBodyResetForces(self.base.body) clock.tick() self.win.dispatch_events() self.win.clear() self.ball.render() self.floor.render() self.base.render() self.win.flip()
class FakeBody(): position = vec2d(0, 0) def __init__(self): pass def set_position(self, position): self.position = position
def enter(self): self.parent.body.set_velocity(vec2d(0,0)) deltaDeath=self.gate.parent.death_toll-self.gate.destination_death_toll() decision_number=random.uniform(0,1) probability=0.5*tanh(10*deltaDeath)+0.5 if decision_number<probability: pass#self.parent.invisible() else: self.parent_SM.set_state(Wandering)
def evade(current_pos, target_pos, max_force): x_dist=target_pos[0]-current_pos[0] #y_dist=target_pos[1]-current_pos[1] #dist=(x_dist**2+y_dist**2)**0.5 if x_dist==0: x_dist=1 if abs(x_dist)>100: return vec2d(0,0) else: return -4*vec2d(max_force,0)*x_dist/abs(x_dist) #if dist==0: #dist=1 #force=-400.0*vec2d(x_dist,0)/dist #if 400.0*x_dist/dist>max_force*10: #force=10*max_force*vec2d(1,0)*x_dist/abs(x_dist) return force
def get_initial_state(self): # return first state self.space = space = cp.cpSpaceNew() space.contents.gravity = vec2d(0.0, -900.0) space.contents.damping = 0.01 cp.cpSpaceResizeStaticHash(space, 50.0, 200) cp.cpSpaceResizeActiveHash(space, 50.0, 10) self.ball = ball = Ball(space, 5, 10, pos=(310, 180)) self.floor = Wall(space, (-60000,40), (60000,40)) self.base = base = Box(space, 5, 50, 20, (300,100)) cp.cpResetShapeIdCounter() joint = cp.cpPinJointNew( ball.body, base.body, vec2d(0,0), vec2d(0,0) ) self.save_angle() cp.cpSpaceAddJoint(space, joint) if self.rl.episodes%100==0: self.save() return self.get_state()
def __init__(self, original_body): '''Could implement different skeleton images for each actor''' Basic_Actor.__init__(self,original_body.body.get_position()) if Skeleton._image is None: Skeleton._image=load_sequence("Skeleton.png", 1, load_mirror=False)[0] self.image=Skeleton._image[0] self.rect=self.image.get_rect() self.rect.center=original_body.rect.center self.embody(original_body.body.get_position(), layers=0, friction=0.9) self.body.set_velocity(vec2d(0,0))
def embody_floor(self, floor): vec2d=self.vec2d transform_Y=self.transform_Y rect=floor.rect point_a=floor.rect.topleft point_b=floor.rect.topright width=floor.rect.height/2.0 body = self.pm.Body(1e100, 1e100) shape= self.pm.Segment(body, vec2d(point_a[0], transform_Y(point_a[1])), vec2d(point_b[0], transform_Y(point_b[1])), width) shape.friction=0 shape.group=self.groups['FLOORS'] shape.collision_type = self.groups['FLOORS'] floor.set_id(shape.id) self.space.add_static_shape(shape) floor.body=body floor.shape=shape body.set_position(vec2d(floor.rect.topleft)) self.with_body.add(floor)
def __init__(self, original_body): '''Could implement different skeleton images for each actor''' Basic_Actor.__init__(self, original_body.body.get_position()) if Skeleton._image is None: Skeleton._image = load_sequence("Skeleton.png", 1, load_mirror=False)[0] self.image = Skeleton._image[0] self.rect = self.image.get_rect() self.rect.center = original_body.rect.center self.embody(original_body.body.get_position(), layers=0, friction=0.9) self.body.set_velocity(vec2d(0, 0))
def __init__(self, space, mass, width, height, pos, color=(255,0,0,255)): poly = [ [ width/2, height/2 ], [ width/2, -height/2 ], [ -width/2, -height/2 ], [ -width/2, height/2 ], ] p_num = len(poly) P_ARR = vec2d * p_num p_arr = P_ARR(vec2d(0,0)) for i, (x,y) in enumerate( poly ): p_arr[i].x = x p_arr[i].y = y moment = cp.cpMomentForPoly( mass, p_num, p_arr, vec2d(0,0)) self.color = color self.body = cp.cpBodyNew( mass, moment ) self.body.contents.p = vec2d( *pos ) cp.cpSpaceAddBody( space, self.body ) self.shape = shape = cp.cpPolyShapeNew( self.body, p_num, p_arr, vec2d(0,0) ) shape.contents.u = 0.5 cp.cpSpaceAddShape(space, shape)
def embody_floor(self, floor): vec2d = self.vec2d transform_Y = self.transform_Y rect = floor.rect point_a = floor.rect.topleft point_b = floor.rect.topright width = floor.rect.height / 2.0 body = self.pm.Body(1e100, 1e100) shape = self.pm.Segment(body, vec2d(point_a[0], transform_Y(point_a[1])), vec2d(point_b[0], transform_Y(point_b[1])), width) shape.friction = 0 shape.group = self.groups['FLOORS'] shape.collision_type = self.groups['FLOORS'] floor.set_id(shape.id) self.space.add_static_shape(shape) floor.body = body floor.shape = shape body.set_position(vec2d(floor.rect.topleft)) self.with_body.add(floor)
def execute(self): parent=self.parent parent_id=parent.id floor_collisions=State_Machine.floor_collisions collision_data=floor_collisions.pop(parent_id, None) velocity=parent.body.get_velocity() if collision_data is None: fall_speed=velocity[1] if abs(fall_speed)>200: self.parent_SM.set_state(Falling) return current_floor=parent.get_sprite(collision_data[1]) #target selection self.landmarks=current_floor.get_items() if self.target is None or not self.target in self.landmarks: self.target=random.choice(self.landmarks) target_pos=self.target.get_position()[0] actor_pos=self.actor.get_position()[0] parent.body.reset_forces() dist=target_pos-actor_pos if dist*dist<50: target_state=self.target.get_trigger_state() if target_state is not None: self.parent_SM.set_state(target_state) #swich state! self.target=None return else: total_force=seek1D(actor_pos, target_pos, self.actor.max_steering) #total_force=vec2d(0,0) if not parent.flee_from is None: total_force+=evade(self.actor.get_position(), parent.flee_from, self.actor.max_steering) if abs(parent.flee_from[0]-actor_pos)>100: parent.fle_from=None parent.body.apply_force(total_force, vec2d(0,0)) velocity=velocity[0] if abs(velocity)>0.01: parent.orientation=int(velocity/abs(velocity)) parent.set_image(parent.orientation, parent.current_image)
def update(self, current_time): '''The skeleton has three states (not implemented through a state machine): * In free fall without touching any floor * Over some floor, being slowly buried. It scares the cavemen. * Deep into the ground. When the skeleton reaches this state it stops being a sprite and it becomes an fixed image. It also stops scaring the Cavemen.''' if hasattr(self, 'current_floor'): #If it is here, then it means it is over some floor. if self.get_position( )[1] < self.current_floor.get_position()[1] + 5: #If the skeleton is not deep enough, it gets burried at a fixed rate if current_time > self.last_update + self.update_interval: self.set_position( [self.get_position()[0], self.get_position()[1] + 1]) self.last_update = current_time return else: #if the skeleton is deep enough, it stops scaring Cavemen and becomes a fixed image instead of a sprite. self.current_floor.death_toll -= 1 self.current_floor.image.blit(self.image, [ self.rect[0] - self.current_floor.rect[0], self.rect[1] - self.current_floor.rect[1] ]) del self.body Basic_Actor.level.with_body.remove(self) Basic_Actor.level.all.remove(self) Basic_Actor.level.visible.remove(self) Sprite.kill(self) elif hasattr(self, 'body') and (self.body.get_velocity() - vec2d(0, 0)).get_length() < 0.01: #If the skeleton has a physical body and is not falling then it must mean it is over a floor, and gets attached to it, increasing its death_toll. It also removes its body so the physics engine doesn't affect it anymore. floor_collisions = Basic_Actor.State_Machine.floor_collisions collision_data = floor_collisions.pop(self.id, None) if collision_data is None: return self.current_floor = self.get_sprite(collision_data[1]) space = Basic_Actor.level.space space.remove_shape(self.shape) space.remove_body(self.body) self.current_floor.death_toll += 1 else: return
class Nivel(): #bordes=Rect(0,0, 100, 100) offset = vec2d(0, 0) old_offset = vec2d(0, 0) enteroAzar = random.randint import pymunk as pm from pymunk.vec2d import vec2d from collision_handler import Collision_State_Handler #sync_list=[] coll_handlers = [] pm.init_pymunk() space = pm.Space() space.gravity = vec2d(0.0, 900.0) physics_step = 40 #in milliseconds from groups import definitions as groups def __init__(self, timer, file=None): #create sprite goups self.enemies = pygame.sprite.Group() self.friends = pygame.sprite.Group() self.floors = pygame.sprite.Group() self.with_body = pygame.sprite.Group() self.all = pygame.sprite.OrderedUpdates() self.visible = pygame.sprite.OrderedUpdates() #connects actors with current level sprites.Basic_Actor.set_level(self) #setups physics engine self.space.resize_static_hash() self.space.resize_active_hash() self.space.set_damping(0.2) self.background = pygame.Surface(SCREENRECT.size).convert() self.temp_background = self.background.copy() self.last_time = 0 if file is not None: self.populate_from_file(file, timer) def set_as_BG(self, item): position = vec2d(item.rect) - self.offset self.background.blit(item.image, position) def set_offset(self, new_offset): self.old_offset = self.offset self.offset = new_offset def get_background(self): #if not self.old_offset==self.offset: # self.temp_background.blit(self.background, self.offset) return self.temp_background def transform_Y(self, Ycoord): return Ycoord def embody_floor(self, floor): vec2d = self.vec2d transform_Y = self.transform_Y rect = floor.rect point_a = floor.rect.topleft point_b = floor.rect.topright width = floor.rect.height / 2.0 body = self.pm.Body(1e100, 1e100) shape = self.pm.Segment(body, vec2d(point_a[0], transform_Y(point_a[1])), vec2d(point_b[0], transform_Y(point_b[1])), width) shape.friction = 0 shape.group = self.groups['FLOORS'] shape.collision_type = self.groups['FLOORS'] floor.set_id(shape.id) self.space.add_static_shape(shape) floor.body = body floor.shape = shape body.set_position(vec2d(floor.rect.topleft)) self.with_body.add(floor) def populate_from_file(self, file, timer): config = eval(open(file, 'U').read()) self.sanity_check(config) floors = dict() for floor_id in config['Floors']: placement = list(config['Relative Placement'][floor_id]) placement[1] = 600 - self.transform_Y(placement[1]) floors[floor_id] = sprites.Floor( placement, round(config['Floor Sizes'][floor_id] / 32.0)) self.embody_floor(floors[floor_id]) #self.set_as_BG(floors[floor_id]) gates = dict() for gate1_id in config['Gate Graph']: gate2_id = config['Gate Graph'][gate1_id][0] gates[gate1_id], gates[gate2_id] = sprites.Gate.create_connected() shelters = dict() for shelter_id in config['Shelters']: shelters[shelter_id] = sprites.Shelter() for floor_id in config['Hierarchy']: for item_id in config['Hierarchy'][floor_id]: if item_id in gates.keys(): floors[floor_id].attach_gate( gates[item_id], list(config['Relative Placement'][item_id])) #self.set_as_BG(gates[item_id]) elif item_id in shelters.keys(): floors[floor_id].attach_gate( shelters[item_id], list(config['Relative Placement'][item_id])) #self.set_as_BG(shelters[item_id]) num_walkers = config['Options'].get('Walkers', 50) for floor in floors.values(): self.floors.add(floor) for i in range(num_walkers): caminante = sprites.Caveman([ self.enteroAzar(50, 700), 600 - config['Relative Placement']['A'][1] - 50 ]) self.enemies.add(caminante) #personaje=sprites.Volador([400,500], False) #nivel_actual.friends.add(personaje) for floor_id in config['Initial Bodycount']: floors[floor_id].death_toll = config['Initial Bodycount'].get( floor_id, 0) #Register collision function to handle colisions with floor: self.coll_handlers.append( self.Collision_State_Handler(self.space, self.groups['FLOORS'], self.groups['CAVEMEN'], timer).get_table()) engine.State_Machine.set_collision_handlers() #self.space.add_collisionpair_func(self.groups['FLOORS'], self.groups['INCORPOREAL'], None) self.all.add([x.items for x in self.floors]) self.all.add(self.floors) self.all.add(self.friends) self.all.add(self.enemies) self.visible.add(self.floors) self.visible.add([x.items for x in self.floors]) self.visible.add(self.friends) self.visible.add(self.enemies) #self.Space.add_collisionpair_func(self.groups['CAVEMEN'], self.groups['FLOORS'], ) def sanity_check(self, conf_module): main_keys = [ 'Floors', 'Gates', 'Hierarchy', 'Relative Placement', 'Gate Graph', 'Floor Sizes', 'Options' ] for key in main_keys: assert conf_module.has_key(key), 'Module key ' + key + ' missing' Floors = conf_module['Floors'] Gates = conf_module['Gates'] Placements = conf_module['Relative Placement'] Graph = conf_module['Gate Graph'] Sizes = conf_module['Floor Sizes'] Hierarchy = conf_module['Hierarchy'] for floor in Floors: #checks all floors have a position assert Placements.has_key( floor), 'Floor ' + floor + ' position not defined.' assert Sizes.has_key( floor), 'Floor ' + floor + ' size not defined.' if not Sizes[floor] % 32 == 0: print 'Warning, ' + floor + ' size is not multiple of tile size 32' assert 0 <= list(Placements[floor])[0] < SCREENRECT.size[ 0], 'Floor ' + floor + ' x-coordinate out of range' assert 0 <= list(Placements[floor])[1] < SCREENRECT.size[ 1], 'Floor ' + floor + ' y-coordinate out of range' assert 0 <= list( Placements[floor])[0] + Sizes[floor] <= SCREENRECT.size[ 0], 'Floor ' + floor + ' out of bounding box' assert 0 <= list(Placements[floor])[1] + 32 <= SCREENRECT.size[ 1], 'Floor ' + floor + ' out of bounding box' Parents_graph = self.invert(Hierarchy) Inverse_graph = self.invert(Graph) for gate in Gates: assert Parents_graph.has_key( gate), 'Gate ' + gate + ' is an orphan :\'(' assert len( Parents_graph[gate] ) == 1, 'Gate ' + gate + ' has more than one parent: ' + str( Parents_graph[gate]) assert Placements.has_key( gate), 'Gate ' + gate + ' position not defined.' assert 32 <= list(Placements[gate])[0] <= round( Sizes[Parents_graph[gate][0]] / 32.0 ) * 32 - 32, 'Gate ' + gate + ' outside parent colision box' assert 0 == list( Placements[gate] )[1], 'Gate ' + gate + ' coordinate is not 0 (Must be)' assert gate in Inverse_graph or gate in Graph, 'Gate ' + gate + ' not connected to other gate' for floor_id in conf_module['Initial Bodycount']: assert floor_id in Floors, floor_id + ' not defined in floors list' def invert(self, graph): inv = {} for k, v_list in graph.iteritems(): for v in v_list: keys = inv.setdefault(v, []) keys.append(k) return inv def set_visible(self, sprite): if sprite in self.all and not sprite in self.visible: self.visible.add(sprite) def set_invisible(self, sprite): if sprite in self.all and sprite in self.visible: self.visible.remove(sprite) def update(self, current_time): self.all.update(current_time) #print current_time, self.last_time+self.physics_step if current_time > self.last_time + self.physics_step: self.space.step(self.physics_step / 1000.0) self.last_time = current_time #ok... now sincronizes sprites with pymunk. Should use a new group for sprites with body for sprite in self.visible: rel_pos = sprite.body.position + self.offset sprite.rect.topleft = [rel_pos[0], rel_pos[1]]
def set_position(self, coordinates): '''Sets the sprite position to the new coordinates. * coordinate: can be a vec2d or a Rect''' self.body.set_position(vec2d(coordinates))
def execute(self): self.gate.enter(self.parent) self.parent.body.set_velocity(vec2d(0,0)) self.parent_SM.set_state(Wandering)
def main(): DEBUG_RECTANGLES=False pygame.init() screen=pygame.display.set_mode(SCREENRECT.size) font = pygame.font.Font(None, 30) #keep track of time clock = pygame.time.Clock() #create level nivel_actual=Nivel(pygame.time, 'Level0.py') #background=nivel_actual.background screen.blit(nivel_actual.background, (0,0)) pygame.display.update() i=0 #game loop while 1: for event in pygame.event.get(): if event.type == QUIT \ or (event.type == KEYDOWN and \ event.key == K_ESCAPE): print clock.get_fps() pygame.display.quit() return elif event.type == KEYDOWN: if event.key == K_UP: personaje.bajar_ala() elif event.key == K_RIGHT: personaje.acelerar(1) elif event.key == K_LEFT: personaje.acelerar(-1) elif event.type == KEYUP: if event.key == K_UP: personaje.subir_ala() elif event.key == K_RIGHT: personaje.acelerar(0) elif event.key == K_r: DEBUG_RECTANGLES=not DEBUG_RECTANGLES elif event.type == MOUSEBUTTONUP: #print 'Click at '+str(event.pos) caught=pygame.sprite.spritecollide(Mouse(event.pos, 200),nivel_actual.enemies, False) if len(caught)>0: for sprite in caught: #sprite.flee_from=event.pos displacement=vec2d(event.pos)-vec2d(sprite.rect) length=displacement.length if length<10: length=10.0 displacement=15000*displacement/length**2 length=displacement.length displacement[1]=-random.uniform(0,length) displacement[0]=0 sprite.body.set_velocity(displacement) caught=pygame.sprite.spritecollide(Mouse(event.pos, 10),nivel_actual.enemies, False) if len(caught)>0: caught[0].kill() nivel_actual.set_offset(vec2d(50*math.sin(0.5*pygame.time.get_ticks()*2*math.pi/2462.0),50*math.sin(0.5*pygame.time.get_ticks()*2*math.pi/2000.0))) #clear sprites #update physics and AI nivel_actual.update(pygame.time.get_ticks()) #redraw sprites screen.fill((0,0,0)) screen.blit(nivel_actual.background, nivel_actual.offset) #pygame.display.flip() nivel_actual.visible.draw(screen) if DEBUG_RECTANGLES: for actor in nivel_actual.visible: pygame.draw.rect(screen, (0,0,255), actor.rect, 1) #if hasattr(actor,'crect'): #pygame.draw.rect(screen, (255,0,0), actor.crect, 1) for floor in nivel_actual.floors: text = font.render(str(floor.death_toll), 1, (255, 255, 255)) screen.blit(text, floor.rect.midtop) pygame.draw.line(screen, (0,255,255), floor.shape.get_a()+nivel_actual.offset, floor.shape.get_b()+nivel_actual.offset, 3) pygame.display.update() clock.tick(40) #nivel_actual.visible.clear(screen, nivel_actual.get_background()) pygame.display.set_caption("fps: " + str(clock.get_fps())) #if nivel_actual.visible._spritelist: #pygame.display.set_caption("velocity: "+ str(nivel_actual.visible._spritelist[0].body.velocity[1])) print clock.get_fps() pygame.display.quit()
def set_as_BG(self, item): position=vec2d(item.rect)-self.offset self.background.blit(item.image, position)
def set_position(self, position): self.body.contents.p = vec2d(position[0], position[1])
def cpvadd(v1, v2): return vec2d(v1.x + v2.x, v1.y + v2.y)
def cpvrotate(v1, v2): return vec2d(v1.x*v2.x - v1.y*v2.y, v1.x*v2.y + v1.y*v2.x)
def main(): DEBUG_RECTANGLES = False pygame.init() screen = pygame.display.set_mode(SCREENRECT.size) font = pygame.font.Font(None, 30) #keep track of time clock = pygame.time.Clock() #create level nivel_actual = Nivel(pygame.time, 'Level0.py') #background=nivel_actual.background screen.blit(nivel_actual.background, (0, 0)) pygame.display.update() i = 0 #game loop while 1: for event in pygame.event.get(): if event.type == QUIT \ or (event.type == KEYDOWN and \ event.key == K_ESCAPE): print clock.get_fps() pygame.display.quit() return elif event.type == KEYDOWN: if event.key == K_UP: personaje.bajar_ala() elif event.key == K_RIGHT: personaje.acelerar(1) elif event.key == K_LEFT: personaje.acelerar(-1) elif event.type == KEYUP: if event.key == K_UP: personaje.subir_ala() elif event.key == K_RIGHT: personaje.acelerar(0) elif event.key == K_r: DEBUG_RECTANGLES = not DEBUG_RECTANGLES elif event.type == MOUSEBUTTONUP: #print 'Click at '+str(event.pos) caught = pygame.sprite.spritecollide(Mouse(event.pos, 200), nivel_actual.enemies, False) if len(caught) > 0: for sprite in caught: #sprite.flee_from=event.pos displacement = vec2d(event.pos) - vec2d(sprite.rect) length = displacement.length if length < 10: length = 10.0 displacement = 15000 * displacement / length**2 length = displacement.length displacement[1] = -random.uniform(0, length) displacement[0] = 0 sprite.body.set_velocity(displacement) caught = pygame.sprite.spritecollide( Mouse(event.pos, 10), nivel_actual.enemies, False) if len(caught) > 0: caught[0].kill() nivel_actual.set_offset( vec2d( 50 * math.sin(0.5 * pygame.time.get_ticks() * 2 * math.pi / 2462.0), 50 * math.sin( 0.5 * pygame.time.get_ticks() * 2 * math.pi / 2000.0))) #clear sprites #update physics and AI nivel_actual.update(pygame.time.get_ticks()) #redraw sprites screen.fill((0, 0, 0)) screen.blit(nivel_actual.background, nivel_actual.offset) #pygame.display.flip() nivel_actual.visible.draw(screen) if DEBUG_RECTANGLES: for actor in nivel_actual.visible: pygame.draw.rect(screen, (0, 0, 255), actor.rect, 1) #if hasattr(actor,'crect'): #pygame.draw.rect(screen, (255,0,0), actor.crect, 1) for floor in nivel_actual.floors: text = font.render(str(floor.death_toll), 1, (255, 255, 255)) screen.blit(text, floor.rect.midtop) pygame.draw.line(screen, (0, 255, 255), floor.shape.get_a() + nivel_actual.offset, floor.shape.get_b() + nivel_actual.offset, 3) pygame.display.update() clock.tick(40) #nivel_actual.visible.clear(screen, nivel_actual.get_background()) pygame.display.set_caption("fps: " + str(clock.get_fps())) #if nivel_actual.visible._spritelist: #pygame.display.set_caption("velocity: "+ str(nivel_actual.visible._spritelist[0].body.velocity[1])) print clock.get_fps() pygame.display.quit()
def set_as_BG(self, item): position = vec2d(item.rect) - self.offset self.background.blit(item.image, position)