def main(): pygame.init() screen = pygame.display.set_mode((width,height)) clock = pygame.time.Clock() running = True space = pymunk.Space() space.gravity = 0,-1000 # box walls static = [pymunk.Segment(space.static_body, (10, 50), (300, 50), 5) , pymunk.Segment(space.static_body, (300, 50), (325, 50), 5) , pymunk.Segment(space.static_body, (325, 50), (350, 50), 5) , pymunk.Segment(space.static_body, (350, 50), (375, 50), 5) , pymunk.Segment(space.static_body, (375, 50), (680, 50), 5) , pymunk.Segment(space.static_body, (680, 50), (680, 370), 5) , pymunk.Segment(space.static_body, (680, 370), (10, 370), 5) , pymunk.Segment(space.static_body, (10, 370), (10, 50), 5) ] static[1].color = pygame.color.THECOLORS['red'] static[2].color = pygame.color.THECOLORS['green'] static[3].color = pygame.color.THECOLORS['red'] # player body = pymunk.Body(5, pymunk.inf) body.position = 100,100 head = pymunk.Circle(body, 10, (0,5)) head2 = pymunk.Circle(body, 10, (0,13)) feet = pymunk.Circle(body, 10, (0,-5)) head.layers = head2.layers = 0b1000 feet.collision_type = 1 feet.ignore_draw = head.ignore_draw = head2.ignore_draw = True space.add(body, head, feet,head2) direction = 1 remaining_jumps = 2 landing = {'p':Vec2d.zero(), 'n':0} frame_number = 0 landed_previous = False while running: grounding = { 'normal' : Vec2d.zero(), 'penetration' : Vec2d.zero(), 'impulse' : Vec2d.zero(), 'position' : Vec2d.zero(), 'body' : None } # find out if player is standing on ground pass
def update(self, dt): def f(arbiter): n = -arbiter.contacts[0].normal if n.y > 0.0: self.platformNormal = n self.platformBody = arbiter.shapes[1].body self.platformNormal = Vec2d.zero() self.platformBody = None self.body.each_arbiter(f) # if ground body is found and slope induced grounding normal is lower than feet friction # (find out if grounded) grounded = False ground_velocity = Vec2d.zero() if self.platformBody != None and abs(self.platformNormal.x / self.platformNormal.y) < self.feet.friction: grounded = True self.remaining_jumps = JUMP_TIMES ground_velocity = self.platformBody.velocity # control inputs targetXVel = 0 if self.keyboard[key.LEFT]: targetXVel -= PLAYER_VELOCITY if self.keyboard[key.RIGHT]: targetXVel += PLAYER_VELOCITY if self.keyboard[key.DOWN]: self.slide = True else: self.slide = False if self.jumpTrigger == True: self.jumpTrigger = False if grounded or self.remaining_jumps > 0: # add target jump velocity to body jumpVel = math.sqrt(2.0 * JUMP_HEIGHT * abs(self.scene.space.gravity.y)) self.body.velocity.y = ground_velocity.y + jumpVel self.remaining_jumps -= 1 # if on ground if self.platformBody != None: # if slide key and on slope (normal is (0,1) when on level ground) if self.slide == True and (self.platformNormal.x / self.platformNormal.y) != 0.0: self.feet.friction = 0 else: self.feet.friction = abs(PLAYER_GROUND_ACCEL / self.scene.space.gravity.y) self.head.friciton = HEAD_FRICTION # apply target x velocity to surface velocity of feet.. self.feet.surface_velocity = targetXVel, 0 else: self.feet.friction, self.head.friction = 0, 0 self.body.apply_impulse((targetXVel / 6, 0)) # fall rate limiter self.body.velocity.y = max(self.body.velocity.y, -FALL_VELOCITY) # clamp upwards as well? super(Avatar, self).update(dt)
def __init__(self): Entity.__init__(self, 2) self.head = pymunk.Circle(self, 18) self.head2 = pymunk.Circle(self, 18) self.head2.elasticity = 0.95 self.feet = pymunk.Circle(self, 18) self.head.color = pygame.Color(200, 78, 0) self.head2.color = pygame.Color(200, 78, 0) self.feet.color = pygame.Color(200, 78, 0) self.head.layers = self.head2.layers = 0b1000 self.feet.collision_type = 1 self.reset_rotation() self.moveStyle = MoveStyle.PHYSICS_DRIVEN self.direction = 1 self.jumpsLeft = 1 self.onGround = False self.helpless = False self.isBusy = False self.controller = Controller(self) self.__currentAttack = None self.__groundVelocity = Vec2d.zero()
def initPhysics(self): self.feet = pymunk.Circle(self.body, 20) self.mid = pymunk.Circle(self.body, 20, (0,40)) self.head = pymunk.Circle(self.body, 20, (0,75)) self.feet.collisionType = platform_collType self.feet.elasticity = 1. self.platformNormal = Vec2d.zero() self.platformBody = None self.slide = False
def __init__(self): platform = pyglet.window.get_platform() display = platform.get_default_display() screen = display.get_default_screen() template = pyglet.gl.Config(double_buffer=True) config = screen.get_best_config(template) context = config.create_context(None) self.clock = pyglet.clock.Clock() self.kb_handler = pyglet.window.key.KeyStateHandler() super(Main, self).__init__(resizable=True, width=WIDTH, height=HEIGHT, caption="pymunk test" , context=context) self.push_handlers(self.kb_handler) self.batch = pyglet.graphics.Batch() self.direction = 1 self.remaining_jumps = 2 self.landing = {'p':Vec2d.zero(), 'n':0} self.landed_previous = False # box walls self.space = world.World() self.space.load() def passthrough_handler(space, arbiter): if arbiter.shapes[0].body.velocity.y < 0: return True else: return False self.space.add_collision_handler(1,2, begin=passthrough_handler) # player self.body = pymunk.Body(5, pymunk.inf) self.body.position = 100,100 self.head = pymunk.Circle(self.body, 10, (0,5)) self.head2 = pymunk.Circle(self.body, 10, (0,13)) self.feet = pymunk.Circle(self.body, 10, (0,-5)) self.head.layers = self.head2.layers = 0b1000 self.feet.collision_type = 1 self.feet.ignore_draw = self.head.ignore_draw = self.head2.ignore_draw = True self.space.add(self.body, self.head, self.feet, self.head2) self.target_vx = 0
def prep_new_run(self): """"resets the engine to a new game""" # initial_load_x = np.random.uniform(10, 15) * np.random.choice([-1, 1]) initial_load_x = 0 # initial_bumper_x = np.random.uniform(5, 7) * np.random.choice([-1, 1]) initial_bumper_x = 5.5 # initial_hoist_len = np.random.uniform(50, 60) initial_hoist_len = 60 # Make world self.space = pymunk.Space() # self.load = pymunk.Body(1000, 1000 * 30 *30) self.load = pymunk.Body(1000, 10000 * 30 * 30) self.barge = pymunk.Body(body_type=pymunk.Body.KINEMATIC) self.hook = pymunk.Body(body_type=pymunk.Body.KINEMATIC) self.space.add(self.load) self.space.add(self.barge) ## Contact shapes # give contact shapes a thickness for better stability th = 2 barge_deck = pymunk.Segment( self.barge, [self.barge_upper_left[0], self.barge_upper_left[1] + th], [self.barge_upper_right[0], self.barge_upper_right[1] + th], th) barge_deck.collision_type = 1 barge_deck.friction = self.friction self.space.add(barge_deck) # Load contact shape radius = 0.1 shape1 = pymunk.Circle(self.load, radius, self.load_lower_left) shape2 = pymunk.Circle(self.load, radius, self.load_lower_right) shape1.collision_type = 2 shape2.collision_type = 2 shape1.friction = self.friction shape2.friction = self.friction self.space.add(shape1) self.space.add(shape2) # Load contact shape bottom load_bottom_shape = pymunk.Segment(self.load, self.load_lower_left, self.load_lower_right, 0) load_bottom_shape.collision_type = 2 load_bottom_shape.friction = self.friction self.space.add(load_bottom_shape) # Load contact shape left side load_left_shape = pymunk.Segment(self.load, self.load_lower_left, self.load_upper_left, 0) load_left_shape.collision_type = 2 load_left_shape.friction = self.friction self.space.add(load_left_shape) # Load contact shape right side load_right_shape = pymunk.Segment(self.load, self.load_lower_right, self.load_upper_right, 0) load_right_shape.collision_type = 2 load_right_shape.friction = self.friction self.space.add(load_right_shape) # Guide contact shape self.bumper_lower = Vec2d(initial_bumper_x, -4) self.bumper_upper = Vec2d(initial_bumper_x, -10) bumper = pymunk.Segment( self.barge, [self.bumper_lower[0] + 2, self.bumper_lower[1]], [self.bumper_upper[0] + 2, self.bumper_upper[1]], 2) bumper.collision_type = 3 self.space.add(bumper) # spring-damper between hook and load damper = pymunk.DampedSpring(self.hook, self.load, (0, 0), self.poi, 0, 0, 5000) adamper = pymunk.DampedRotarySpring(self.hook, self.load, 0, 0, 400) self.space.add(damper, adamper) handler_barge_contact = self.space.add_collision_handler( 1, 2) # barge is type 1, load is type 2 handler_barge_contact.post_solve = self.barge_contact handler_bumper_contact = self.space.add_collision_handler( 2, 3) # bumper is type 3, load is type 2 handler_bumper_contact.post_solve = self.bumper_contact self.space.gravity = Vec2d(0, 9.81) self.space.damping = 0.98 n = int(self.t_motions / self.dt_motions) temp = self.wave_spectrum.make_time_trace(associated=self.associated, n=n, dt=self.dt_motions, locations=self.wave_location) self.wave_elevation = temp['response'] self.motions_t = temp['t'] R = temp['associated'] self.motions_sway_block = R[0] self.motions_heave_block = R[1] self.motions_302_surge = R[2] self.motions_302_heave = R[3] self.motions_302_pitch = R[4] * self.magic_pitch_factor # TODO: Temp start with stationary env # self.motions_sway_block = np.zeros((10000,)) # self.motions_heave_block = np.zeros((10000,)) # self.motions_302_surge = np.zeros((10000,)) # self.motions_302_heave = np.zeros((10000,)) # self.motions_302_pitch = np.zeros((10000,)) self.hoist_length = initial_hoist_len self.crane_sway = 0 self.barge_impulse = [] self.bumper_impulse = [] self.has_barge_contact = False self.has_bumper_contact = False self.setdown_counter = 0 self.is_done = False self.load.position = Vec2d(initial_load_x, self.hoist_length - self.poi[1]) self.time_lookup_index = 0 self.max_impact = 0
def __init__(self, points): self.poly = [Vec2d(point) for point in points] self.triangles = triangulate(self.poly) self.convexes = convexise(self.triangles)
def main(): ### PyGame init pygame.init() screen = pygame.display.set_mode((width,height)) clock = pygame.time.Clock() running = True font = pygame.font.SysFont("Arial", 16) sound = pygame.mixer.Sound("sfx.wav") img = pygame.image.load("xmasgirl1.png") ### Physics stuff space = pymunk.Space() space.gravity = 0,-1000 # box walls static = [pymunk.Segment(space.static_body, (10, 50), (300, 50), 5) , pymunk.Segment(space.static_body, (300, 50), (325, 50), 5) , pymunk.Segment(space.static_body, (325, 50), (350, 50), 5) , pymunk.Segment(space.static_body, (350, 50), (375, 50), 5) , pymunk.Segment(space.static_body, (375, 50), (680, 50), 5) , pymunk.Segment(space.static_body, (680, 50), (680, 370), 5) , pymunk.Segment(space.static_body, (680, 370), (10, 370), 5) , pymunk.Segment(space.static_body, (10, 370), (10, 50), 5) ] static[1].color = pygame.color.THECOLORS['red'] static[2].color = pygame.color.THECOLORS['green'] static[3].color = pygame.color.THECOLORS['red'] # rounded shape rounded = [pymunk.Segment(space.static_body, (500, 50), (520, 60), 5) , pymunk.Segment(space.static_body, (520, 60), (540, 80), 5) , pymunk.Segment(space.static_body, (540, 80), (550, 100), 5) , pymunk.Segment(space.static_body, (550, 100), (550, 150), 5) ] # static platforms platforms = [pymunk.Segment(space.static_body, (170, 50), (270, 150), 5) #, pymunk.Segment(space.static_body, (270, 100), (300, 100), 5) , pymunk.Segment(space.static_body, (400, 150), (450, 150), 5) , pymunk.Segment(space.static_body, (400, 200), (450, 200), 5) , pymunk.Segment(space.static_body, (220, 200), (300, 200), 5) , pymunk.Segment(space.static_body, (50, 250), (200, 250), 5) , pymunk.Segment(space.static_body, (10, 370), (50, 250), 5) ] for s in static + platforms+rounded: s.friction = 1. s.group = 1 space.add(static, platforms+rounded) # moving platform platform_path = [(650,100),(600,200),(650,300)] platform_path_index = 0 platform_body = pymunk.Body(pymunk.inf, pymunk.inf) platform_body.position = 650,100 s = pymunk.Segment(platform_body, (-25, 0), (25, 0), 5) s.friction = 1. s.group = 1 s.color = pygame.color.THECOLORS["blue"] space.add(s) # pass through platform passthrough = pymunk.Segment(space.static_body, (270, 100), (320, 100), 5) passthrough.color = pygame.color.THECOLORS["yellow"] passthrough.friction = 1. passthrough.collision_type = 2 passthrough.layers = passthrough.layers ^ 0b1000 space.add(passthrough) def passthrough_handler(space, arbiter): if arbiter.shapes[0].body.velocity.y < 0: return True else: return False space.add_collision_handler(1,2, begin=passthrough_handler) # player body = pymunk.Body(5, pymunk.inf) body.position = 100,100 head = pymunk.Circle(body, 10, (0,5)) head2 = pymunk.Circle(body, 10, (0,13)) feet = pymunk.Circle(body, 10, (0,-5)) head.layers = head2.layers = 0b1000 feet.collision_type = 1 feet.ignore_draw = head.ignore_draw = head2.ignore_draw = True space.add(body, head, feet,head2) direction = 1 remaining_jumps = 2 landing = {'p':Vec2d.zero(), 'n':0} frame_number = 0 landed_previous = False while running: grounding = { 'normal' : Vec2d.zero(), 'penetration' : Vec2d.zero(), 'impulse' : Vec2d.zero(), 'position' : Vec2d.zero(), 'body' : None } # find out if player is standing on ground def f(arbiter): n = -arbiter.contacts[0].normal if n.y > grounding['normal'].y: grounding['normal'] = n grounding['penetration'] = -arbiter.contacts[0].distance grounding['body'] = arbiter.shapes[1].body grounding['impulse'] = arbiter.total_impulse grounding['position'] = arbiter.contacts[0].position body.each_arbiter(f) well_grounded = False if grounding['body'] != None and abs(grounding['normal'].x/grounding['normal'].y) < feet.friction: well_grounded = True remaining_jumps = 2 ground_velocity = Vec2d.zero() if well_grounded: ground_velocity = grounding['body'].velocity for event in pygame.event.get(): if event.type == QUIT or \ event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]): running = False elif event.type == KEYDOWN and event.key == K_p: pygame.image.save(screen, "platformer.png") elif event.type == KEYDOWN and event.key == K_d: feet.ignore_draw = not feet.ignore_draw head.ignore_draw = not head.ignore_draw head2.ignore_draw = not head2.ignore_draw elif event.type == KEYDOWN and event.key == K_UP: if well_grounded or remaining_jumps > 0: jump_v = math.sqrt(2.0 * JUMP_HEIGHT * abs(space.gravity.y)) body.velocity.y = ground_velocity.y + jump_v; remaining_jumps -=1 elif event.type == KEYUP and event.key == K_UP: body.velocity.y = min(body.velocity.y, JUMP_CUTOFF_VELOCITY) # Target horizontal velocity of player target_vx = 0 if body.velocity.x > .01: direction = 1 elif body.velocity.x < -.01: direction = -1 keys = pygame.key.get_pressed() if (keys[K_LEFT]): direction = -1 target_vx -= PLAYER_VELOCITY if (keys[K_RIGHT]): direction = 1 target_vx += PLAYER_VELOCITY if (keys[K_DOWN]): direction = -3 feet.surface_velocity = target_vx,0 if grounding['body'] != None: feet.friction = -PLAYER_GROUND_ACCEL/space.gravity.y head.friciton = HEAD_FRICTION else: feet.friction,head.friction = 0,0 # Air control if grounding['body'] == None: body.velocity.x = cpflerpconst(body.velocity.x, target_vx + ground_velocity.x, PLAYER_AIR_ACCEL*dt) body.velocity.y = max(body.velocity.y, -FALL_VELOCITY) # clamp upwards as well? # Move the moving platform destination = platform_path[platform_path_index] current = Vec2d(platform_body.position) distance = current.get_distance(destination) if distance < PLATFORM_SPEED: platform_path_index += 1 platform_path_index = platform_path_index % len(platform_path) t = 1 else: t = PLATFORM_SPEED / distance new = current.interpolate_to(destination, t) platform_body.position = new platform_body.velocity = (new - current) / dt ### Clear screen screen.fill(pygame.color.THECOLORS["black"]) ### Helper lines for y in [50,100,150,200,250,300]: color = pygame.color.THECOLORS['darkgrey'] pygame.draw.line(screen, color, (10,y), (680,y), 1) ### Draw stuff draw(screen, space) if feet.ignore_draw: direction_offset = 48+(1*direction+1)/2 * 48 if grounding['body'] != None and abs(target_vx) > 1: animation_offset = 32 * (frame_number / 8 % 4) elif grounding['body'] is None: animation_offset = 32*1 else: animation_offset = 32*0 position = body.position +(-16,28) screen.blit(img, to_pygame(position, screen), (animation_offset, direction_offset, 32, 48)) # Did we land? if abs(grounding['impulse'].y) / body.mass > 200 and not landed_previous: sound.play() landing = {'p':grounding['position'],'n':5} landed_previous = True else: landed_previous = False if landing['n'] > 0: pygame.draw.circle(screen, pygame.color.THECOLORS['yellow'], to_pygame(landing['p'], screen), 5) landing['n'] -= 1 # Info and flip screen screen.blit(font.render("fps: " + str(clock.get_fps()), 1, THECOLORS["white"]), (0,0)) screen.blit(font.render("Move with Left/Right, jump with Up, press again to double jump", 1, THECOLORS["darkgrey"]), (5,height - 35)) screen.blit(font.render("Press D to toggle sprite draw, ESC or Q to quit", 1, THECOLORS["darkgrey"]), (5,height - 20)) pygame.display.flip() frame_number += 1 ### Update physics space.step(dt) clock.tick(fps)
def run_rotate(): ''' Runs the simulations and saves the JSON files with an arbitrary rotation about the center of the screen. ''' def rotate(obj,theta=-20,origin=(500,300)): ''' Rotates objects about a center ''' # Translate w/r to visual origin (500,300) obj.body.position -= Vec2d(origin) # Radians to degrees theta = radians(theta) x, y = obj.body.position x_ = x*cos(theta) - y*sin(theta) y_ = y*cos(theta) + x*sin(theta) obj.body.position = [x_,y_] # Translate w/r to actual origin (0,0) obj.body.position += Vec2d(origin) video = False thetas = list(range(-19,-9))+list(range(10,19)) for scene in scenarios.__experiment3__: theta = choice(thetas) sim = getattr(scenarios, scene) env = sim(True) env.run() # Gather position data pos = env.position_dict agent_positions = env.position_dict['agent'] patient_positions = env.position_dict['patient'] fireball_positions = env.position_dict['fireball'] # Setup pygame and pymunk space = pymunk.Space() space.damping = 0.05 screen = pygame.display.set_mode((1000,600)) options = pymunk.pygame_util.DrawOptions(screen) clock = pygame.time.Clock() if video: save_screen = make_video(screen) # Setup empty agents agent = Agent(0,0,'blue',0,[]) patient = Agent(0,0,'green',0,[]) fireball = Agent(0,0,'red',0,[]) # Add agent to space space.add(agent.body, agent.shape, patient.body, patient.shape, fireball.body, fireball.shape) pygame.init() running = True while running: # print(agent_positions[0]) try: # Extract position data a_pos = agent_positions.pop(0) p_pos = patient_positions.pop(0) f_pos = fireball_positions.pop(0) # Set positions of objects agent.body.position = Vec2d(a_pos['x'],a_pos['y']) patient.body.position = Vec2d(p_pos['x'],p_pos['y']) fireball.body.position = Vec2d(f_pos['x'],f_pos['y']) # Rotate objects about the center rotate(agent,theta) rotate(patient,theta) rotate(fireball,theta) # Render space on screen (if requested) screen.fill((255,255,255)) space.debug_draw(options) pygame.display.flip() clock.tick(60) space.step(1/60.0) if video: next(save_screen) except Exception as e: running = False pygame.quit() pygame.display.quit() if video: vid_from_img("final_"+scene)
def jump(self): # jump if the object is properly grounded # set grounded to False if self.grounded: self.grounded = False self.body.apply_impulse_at_local_point(Vec2d(0, self.jump_impulse))
def testConversion(self): b = p.Body(1, 1) b.position = 10, 20 self.assertEqual(b.local_to_world((1, 1)), Vec2d(11, 21)) self.assertEqual(b.world_to_local((1, 1)), Vec2d(-9, -19))
def genererSommetsRelatifsPymunk(self): yield Vec2d(-self.largeur / 2, -self.hauteur / 2) yield Vec2d(+self.largeur / 2, -self.hauteur / 2) yield Vec2d(+self.largeur / 2, +self.hauteur / 2) yield Vec2d(-self.largeur / 2, +self.hauteur / 2)
def __init__(self, p0, size=(20, 20), color=None): w, h = Vec2d(size) / 2 vertices = [(-w, -h), (w, -h), (w, h), (-w, h)] super().__init__(p0, vertices, color)
def position(self, vec): self._position = Vec2d(*vec)
def update(self, delta): self.controller.update() self.isBusy = self.__currentAttack is not None if len(self.controller.events) > 0: inputEvent = self.controller.pop() if not self.isBusy and not self.helpless: self.onInput(inputEvent) if self.isBusy: try: self.__currentAttack.next() except StopIteration: self.__currentAttack = None self.onGround = False grounding = { 'normal' : Vec2d.zero(), 'penetration' : Vec2d.zero(), 'impulse' : Vec2d.zero(), 'position' : Vec2d.zero(), 'body' : None, } def onHit(arbiter): n = -arbiter.contacts[0].normal if n.y > grounding['normal'].y: grounding['normal'] = n grounding['penetration'] = -arbiter.contacts[0].distance grounding['body'] = arbiter.shapes[1].body grounding['impulse'] = arbiter.total_impulse grounding['position'] = arbiter.contacts[0].position self.each_arbiter(onHit) if grounding['body'] != None and abs(grounding['normal'].x/grounding['normal'].y) < self.feet.friction: self.onGround = True self.helpless = False self.jumpsLeft = 1 if self.moveStyle == MoveStyle.PHYSICS_DRIVEN: self.__groundVelocity = Vec2d.zero() if self.onGround: self.__groundVelocity = grounding['body'].velocity target_vx = 0 if not self.isBusy: xdir = self.controller.xdir if xdir != 0: if self.onGround: self.direction = xdir target_vx += PLAYER_VELOCITY * xdir self.feet.surface_velocity = target_vx,0 if grounding['body'] != None: self.feet.friction = -PLAYER_GROUND_ACCEL/self.scene.space.gravity.y self.head.friciton = HEAD_FRICTION else: self.feet.friction, self.head.friction = 0,0 # Air control if not self.isBusy: if grounding['body'] == None: self.velocity.x = cpflerpconst(self.velocity.x, target_vx + self.__groundVelocity.x, PLAYER_AIR_ACCEL*delta) self.velocity.y = max(self.velocity.y, -FALL_VELOCITY)
def step(self, t_simulation, dt, action): dt_physics = dt / self.n_inner self.current_bumper_contact = False for i in range(self.n_inner): if action == 'right': self.crane_sway += self.sway_speed * dt_physics elif action == 'left': self.crane_sway -= self.sway_speed * dt_physics elif action == 'down': self.hoist_length += self.hoist_speed * dt_physics elif action == 'up': self.hoist_length -= self.hoist_speed * dt_physics elif action == 'hold': pass else: raise ValueError('Unknown action') t = t_simulation + i * dt_physics (crane_x, crane_y, barge_x, barge_y, barge_rotation) = self.get_external_movements(t) self.hook.position = Vec2d(crane_x + self.crane_sway, crane_y) # motions are already scaled self.barge.position = (barge_x, barge_y) self.barge.angle = np.deg2rad(barge_rotation) c = self.hook.local_to_world( (0, 0)) - self.load.local_to_world(self.poi) actual_length = c.length dir = c.normalized() if actual_length <= self.hoist_length: t = 0 else: t = self.EA * actual_length / self.hoist_length force = t * dir global_poi_position = self.load.local_to_world(self.poi) self.load.apply_force_at_world_point(force, global_poi_position) self.update_instant_geometry(global_poi_position) # Time-stepping and damping self.has_barge_contact = False self.has_bumper_contact = False self.space.step(dt_physics) # for the game to end we need a minimum period of continuous contact if self.has_barge_contact: # self.setdown_counter += 1 # if self.setdown_counter > ((self.time_in_position_till_end / dt) * self.n_inner): # # print('Ready') # self.is_done = True # break self.is_done = True else: self.setdown_counter -= 1 self.setdown_counter = max(self.setdown_counter, 0) # never less and 0
def _move_dynamic(self): for obj in self.dynamic: speed = np.random.randint(20, 100) obj.body.angle -= np.random.randint(-1, 1) direction = Vec2d(1, 0).rotated(obj.body.angle) obj.body.velocity = speed * direction
def _step(self, action): self.last_position = copy.copy(self.car.body.position) go = 0 left = 0 right = 0 if action == 0: go = 1 elif action == 1: left = 1 elif action == 2: right = -1 # elif action == 3: # go = -1 self.car.body.angle += .2 * (left + right) # Move dynamic objects if self.num_steps % 5 == 0: self._move_dynamic() driving_direction = Vec2d(1, 0).rotated(self.car.body.angle) self.car.body.velocity = int(100 * go) * driving_direction # Update the screen and stuff. self.space.step(1. / 10) self.screen.fill(THECOLORS["black"]) draw(self.screen, self.space) if self.draw_screen: pygame.display.flip() self.clock.tick() # Get the current location and the readings there. x, y = self.car.body.position xt, yt = self.target.body.position readings = self._get_sonar_readings(x, y, self.car.body.angle) distance = np.sqrt((x - xt)**2 + (y - yt)**2) / 100. readings += [self._get_angle(), distance] state = np.array(readings) if self.crashed or self._out_of_bounds(): if self.num_steps == 0: self.reset() return self.step(action) elif self._out_of_bounds(): self.crashed = True self.num_steps += 1 r = self.get_reward(action) if self.memory_steps > 0: self.full_state = shift(self.full_state, self.action_dim + self.observation_dim) self.full_state[self.observation_dim:self.observation_dim+self.action_dim] = \ bin_from_int(self.old_action, self.action_dim) self.full_state[:self.observation_dim] = state state = self.full_state else: self.full_state = state self.old_action = action return state, r, self.crashed, {}
def run(self): pygame.init() count = 0 last_time = time.time() last_molecule_time = time.time() done = False while not done: self.screen.fill((0, 0, 0)) current_time = time.time() elapsed_time = current_time - last_time last_time = current_time self.space.step(elapsed_time) curr_molecule_time = time.time() elapsed_molecule_time = curr_molecule_time - last_molecule_time if elapsed_molecule_time > 2: init_molecule_pos = Vec2d( random.uniform(-2000, 2000), random.uniform(-2000, 2000) ) new_molecule = FoodMolecule(init_position=init_molecule_pos) self.molecules.append(new_molecule) self.space.add(new_molecule.shape.body, new_molecule.shape) last_molecule_time = time.time() for molecule in self.molecules: draw_pymunk_circle( molecule.shape, self.screen, scale=self.camera_zoom, camera_position=self.camera_position, ) for cell in self.cells: cell.move() for cell in self.cells: draw_pymunk_circle( cell.shape, self.screen, scale=self.camera_zoom, camera_position=self.camera_position, ) for cell in self.cells: for mitochondrion in cell.mitochondria: for snake_part in mitochondrion.snake: draw_pymunk_poly( snake_part, self.screen, relative_to=cell.shape.body.position, scale=self.camera_zoom, camera_position=self.camera_position, ) for ATP in cell.ATP: draw_pymunk_circle( ATP.shape, self.screen, relative_to=cell.shape.body.position, scale=self.camera_zoom, camera_position=self.camera_position, ) for food_molecule in cell.molecules: draw_pymunk_circle( food_molecule.shape, self.screen, relative_to=cell.shape.body.position, scale=self.camera_zoom, camera_position=self.camera_position, ) draw_pymunk_circle( cell.nucleus.shape, self.screen, relative_to=cell.shape.body.position, scale=self.camera_zoom, camera_position=self.camera_position, ) for cell in self.cells: cell.time_step() for cell in self.cells: new_cell = cell.split_check() if new_cell != None: self.cells.append(new_cell) self.space.add(new_cell.shape.body, new_cell.shape) keystate = pygame.key.get_pressed() if keystate[pygame.K_LEFT]: self.camera_position.x += 1 * (self.camera_zoom ** 10 + 1) if keystate[pygame.K_RIGHT]: self.camera_position.x -= 1 * (self.camera_zoom ** 10 + 1) if keystate[pygame.K_UP]: self.camera_position.y -= 1 * (self.camera_zoom ** 10 + 1) if keystate[pygame.K_DOWN]: self.camera_position.y += 1 * (self.camera_zoom ** 10 + 1) if keystate[pygame.K_a]: print("key pressed") if keystate[pygame.K_d]: print("key pressed") if keystate[pygame.K_w]: print("key pressed") if keystate[pygame.K_s]: print("key pressed") if keystate[pygame.K_z]: print("z key pressed") self.camera_zoom += 0.01 if keystate[pygame.K_x]: print("x key pressed") self.camera_zoom -= 0.01 for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: cell = Cell(self) self.space.add(cell.shape.body, cell.shape) self.cells.append(cell) print("Space pressed") pygame.display.flip()
Text.font = pygame.font.Font(None, 24) self.render() App.current.objects.append(self) def render(self): self.img = self.font.render(self.text, True, BLACK) def draw(self): screen = pygame.display.get_surface() screen.blit(self.img, self.pos) if __name__ == '__main__': app = App() p0 = Vec2d(200, 120) v = Vec2d(100, 0) Space('Cercle', gravity=(0, 0)) Circle(p0) Circle(p0 + v, 20) Circle(p0 + 2 * v, 50, RED) Space('Segment', gravity=(0, 0)) Segment(p0, v) Segment(p0 + (50, 50), 2 * v, 5, RED) Space('Poly', gravity=(0, 0)) triangle = [(-30, -30), (30, -30), (0, 30)] Poly(p0, triangle) square = [(-30, -30), (30, -30), (30, 30), (-30, 30)]
def vector(angle): return Vec2d(math.cos(angle),math.sin(angle))
def velocity(self, vec): self._velocity = Vec2d(*vec)
def get_top_left(self): return Vec2d(-self.get_width() / 2, -self.get_height() / 2) + self.pos
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._velocity = Vec2d(0, 0) self._position = Vec2d(self.center_x, self.center_y)
def get_bottom_left(self): return Vec2d(-self.get_width() / 2, self.get_height() / 2) + self.pos
def update(self, information): self.info_robot_pose = None self.info_destination_geom = None self.info_spatial_map = None self.info_stuck = None for info in information: if info.type == 'robot_pose': self.info_robot_pose = info info.read = True elif info.type == 'destination_geom': self.info_destination_geom = info info.read = True elif info.type == 'spatial_map': self.info_spatial_map = info info.read = True elif info.type == 'stuck': self.info_stuck = info info.read = True if self.info_robot_pose is None or self.info_destination_geom is None or self.info_spatial_map is None: self.valid = False else: self.valid = True if not self.valid: return [] self.setTarget(self.info_destination_geom.point) if self.spatial_map_id != self.info_spatial_map.spatial_map_id: map_updated = True self.spatial_map_id = copy.copy( self.info_spatial_map.spatial_map_id) else: map_updated = False #print self.updated_target if self.updated_target or map_updated: self.dist, self.prev = self.dijkstra(self.target_idx) self.path = self.findShortestPath(self.info_robot_pose.position) self.updated_target = False self.ignored_nodes = set() print "BehaviorSpatialPathPlanner: new path (target changed)" if not self.info_stuck is None: print "BehaviorSpatialPathPlanner: new path (stuck)" # we need to choose another path # cut the graph at current position current_s_idx = self.info_spatial_map.tri.find_simplex( np.asarray([self.info_robot_pose.position]))[0] #print "path", self.path #print "current_s_idx", current_s_idx next_s_idx = None for p_idx in range(len(self.path) - 1): if self.path[p_idx] == current_s_idx: next_s_idx = self.path[p_idx + 1] break #print "next_s_idx", next_s_idx if not next_s_idx is None: self.ignored_nodes.add(next_s_idx) self.dist, self.prev = self.dijkstra(self.target_idx) self.path = self.findShortestPath( self.info_robot_pose.position) #print "new path", self.path info_path = InformationPathGeom(self.path) info_path.prev = self.prev info_path.autoremove = True info_path.meancenters = self.info_spatial_map.meancenters info_path.circumcenters = self.info_spatial_map.circumcenters info_path.tri = self.info_spatial_map.tri self.debug_info = [] for p_idx in range(len(self.path)): s_idx = self.path[p_idx] s = self.info_spatial_map.tri.simplices[s_idx, :] p1 = array2Vec2d(self.info_spatial_map.tri.points[s[0], :]) p2 = array2Vec2d(self.info_spatial_map.tri.points[s[1], :]) p3 = array2Vec2d(self.info_spatial_map.tri.points[s[2], :]) self.debug_info.append(("line", "blue", p1, p2)) self.debug_info.append(("line", "blue", p2, p3)) self.debug_info.append(("line", "blue", p3, p1)) p4 = self.info_destination_geom.point self.debug_info.append(("circle", "blue", p4, 20)) if not self.info_destination_geom.angle is None: p5 = p4 + Vec2d(25.0, 0).rotated(self.info_destination_geom.angle) self.debug_info.append(("vector", "blue", p4, p5)) return [info_path]
def get_top_right_target(self): return Vec2d(self.get_width() / 2, -self.get_height() / 2) + self.target
def avoirCentreRelatif(self): return Vec2d(self.largeur / 2, self.hauteur / 2)
def get_bottom_right_target(self): return Vec2d(self.get_width() / 2, self.get_height() / 2) + self.target
def setup(self): x = SCREEN_WIDTH // 2 y = SCREEN_HEIGHT // 2 self.player.position += Vec2d(x, y) self.ghost.position += Vec2d(x, y)
def rePos(self, newX, newY): #self.pos = Vec2d(newX - int(self.get_width()/2), newY - int(self.get_height()/2)) self.pos = Vec2d(newX, newY)
def drop_down(self): self.body.pass_through = True if self.grounded: self.grounded = False self.body.apply_impulse_at_local_point(Vec2d(0, self.jump_impulse/2))
def move(self, newX, newY, mvmtTime): self.target = Vec2d(newX, newY) self.mvmtTime = mvmtTime
def __init__(self, config, scale=1, swing=None, lean=0): # In the json file, the format for limbs is --> "limb": [angle, length, mass]. # The head has format --> "head": [radius, mass] self.theta = swing.theta - 90 - lean self.config = config self.maxLegAngles = [0, np.pi/2] foot_index = 0 hand_index = 1 print(swing.segmentArray[foot_index].position) #Generate foot and ankle #self.anklePosition = config["anklePosition"] self.anklePosition = swing.positionArray[foot_index+1] #Generate lower leg and knee self.lowerLegVector = self.dirVec("lowerLeg", scale) self.lowerLeg = Segment(self.anklePosition, self.lowerLegVector, self.limbMass("lowerLeg")) self.kneePosition = self.vectorSum(self.anklePosition, self.lowerLegVector) self.lowerLegMotor = pymunk.SimpleMotor(b0, self.lowerLeg.body, 0) space.add(self.lowerLegMotor) #Generate upper leg self.upperLegVector = self.dirVec("upperLeg", scale) self.upperLeg = Segment(self.kneePosition, self.upperLegVector, self.limbMass("upperLeg")) self.knee = PivotJoint(self.lowerLeg.body, self.upperLeg.body, self.lowerLegVector) """ self.upperLegMotor = pymunk.SimpleMotor(b0, self.upperLeg.body, 0) space.add(self.upperLegMotor) """ #Generate pelvis and torso self.pelvisPosition = self.vectorSum(self.kneePosition, self.upperLegVector) self.torsoVector = self.dirVec("torso", scale) self.torso = Segment(self.pelvisPosition, self.torsoVector, self.limbMass("torso")) self.pelvis = PivotJoint(self.upperLeg.body, self.torso.body, self.upperLegVector) self.torsoMotor = pymunk.SimpleMotor(b0, self.torso.body, 0) space.add(self.torsoMotor) #Generate shoulder and upper arm self.shoulderPosition = self.vectorSum(self.pelvisPosition, self.torsoVector) self.upperArmVector = self.dirVec("upperArm", scale) self.upperArm = Segment(self.shoulderPosition, self.upperArmVector, self.limbMass("upperArm")) self.shoulder = PivotJoint(self.torso.body, self.upperArm.body, self.torsoVector) #Generate elbow and lower arm self.elbowPosition = self.vectorSum(self.shoulderPosition, self.upperArmVector) self.lowerArmVector = self.dirVec("lowerArm", scale) self.lowerArm = Segment(self.elbowPosition, self.lowerArmVector, self.limbMass("lowerArm")) self.elbow = PivotJoint(self.upperArm.body, self.lowerArm.body, self.upperArmVector) #Generate head headRadius = config["head"][0] headPosition = self.shoulderPosition + (headRadius * Vec2d(np.sin(theta * np.pi/180), -np.cos(theta * np.pi/180))) self.head = Circle(headPosition, headRadius) self.headJoint = PivotJoint(self.torso.body, self.head.body, self.torsoVector + (headRadius * Vec2d(np.sin(theta * np.pi/180), -np.cos(theta * np.pi/180)))) self.headPosition = self.shoulderPosition + (headRadius * Vec2d(np.sin(theta * np.pi/180), -np.cos(theta * np.pi/180))) self.head = Circle(self.headPosition, headRadius) self.headJoint = PivotJoint(self.torso.body, self.head.body, self.torsoVector + (headRadius * Vec2d(np.sin(theta * np.pi/180), -np.cos(theta * np.pi/180)))) #Attack stick figure to swing """ self.holdHand = PinJoint(self.lowerArm.body, swing.getJointByNumber(hand_index), self.lowerArmVector) self.holdFoot = PinJoint(self.lowerLeg.body, swing.getJointByNumber(foot_index), (0, 0)) """ v = [-100, -200] self.holdFoot = PinJoint(self.lowerLeg.body, swing.segmentArray[foot_index]) self.upKey = 0 self.downKey = 0
def main(): # initialize the environment pm.pygame_util.positive_y_is_up = False pygame.init() screen = pygame.display.set_mode((1600, 960)) clock = pygame.time.Clock() space = pm.Space() space.gravity = (0.0, 0.0) # draw_options = pm.pygame_util.DrawOptions(screen) fps = 144 static = [ pm.Segment(space.static_body, (0, 0), (0, 960), 5), pm.Segment(space.static_body, (0, 960), (1600, 960), 5), pm.Segment(space.static_body, (1600, 960), (1600, 0), 5), pm.Segment(space.static_body, (0, 0), (1600, 0), 5), ] for s in static: s.collision_type = 0 space.add(static) mouse_joint = None mouse_body = pm.Body(body_type=pm.Body.KINEMATIC) # Draw daylight map in to space # Test code start##########Enable this to test in Pycharm################ f = open( 'D:/Delft Courses/Graduation/PythonProject/daylighthour_layout_pathfinding/4_5_info_exchange.txt', mode='r', encoding='utf-8') daylighthours = [] for line in f: line = line.strip() daylighthours.append(int(line)) map_height = 96 map_width = 160 # Test code end######################################################## sdmap = site_daylight_map(daylighthours, map_height) pixel_list = draw_map(space, sdmap, map_width, map_height) # rooms_shape_list, spring_list = room_placement(screen, space, G, order) rooms_shape_list, rooms_body_list, connection_list = room_placement_dlh( screen, space, G, phase_index, rooms_shape_list_pos, body_type_list, order) spring_list = [] while True: pause = False for event in pygame.event.get(): if event.type == KEYUP: if event.key == K_p: pause = True if event.type == QUIT: exit() elif event.type == KEYDOWN and event.key == K_ESCAPE: exit() elif event.type == MOUSEBUTTONDOWN: if mouse_joint != None: space.remove(mouse_joint) mouse_joint = None p = Vec2d(event.pos) hit = space.point_query_nearest(p, 5, pm.ShapeFilter()) if hit != None and hit.shape.body.body_type == pm.Body.DYNAMIC: shape = hit.shape # Use the closest point on the surface if the click is outside # of the shape. if hit.distance > 0: nearest = hit.point else: nearest = p mouse_joint = pm.PivotJoint( mouse_body, shape.body, (0, 0), shape.body.world_to_local(nearest)) mouse_joint.max_force = 50000000 mouse_joint.error_bias = (1 - 0.15)**60 space.add(mouse_joint) elif event.type == MOUSEBUTTONUP: if mouse_joint != None: space.remove(mouse_joint) mouse_joint = None while pause == True: for event in pygame.event.get(): if event.type == KEYUP: if event.key == K_p: pause = False if event.type == QUIT: exit() elif event.type == KEYDOWN and event.key == K_ESCAPE: exit() elif event.type == KEYDOWN and event.key == K_c: spring_list = connect_rooms(space, G, rooms_body_list, order, phase_index) elif event.type == KEYDOWN and event.key == K_g: # 判断按下g rooms_shape_list_pos_out = [] body_type_list_out = [] room_info_lst = [] order_generate = [] for shape in rooms_shape_list: i = rooms_shape_list.index(shape) room = order[i] v = shape.body.position vx = int(v.x) vy = int(v.y) body_type = shape.body.body_type shape_pos = (vx, vy) room_info = (room, shape_pos, body_type, i, vy) room_info_lst.append(room_info) order_info_lst = sorted(room_info_lst, key=lambda x: (-x[4], x[3])) for i in range(len(order_info_lst)): room_node = order_info_lst[i][0] shape_pos_order = order_info_lst[i][1] body_type_order = order_info_lst[i][2] order_generate.append(room_node) rooms_shape_list_pos_out.append(shape_pos_order) body_type_list_out.append(body_type_order) f = open( 'D:/Delft Courses/Graduation/PythonProject/daylighthour_layout_pathfinding/4_5_info_exchange.txt', mode='w', encoding='utf-8') f.write(f'{phase_index}') f.write('\n') f.write(f'{rooms_shape_list_pos_out}') f.write('\n') f.write(f'{body_type_list_out}') f.write('\n') f.write(f'{order_generate}') f.write('\n') f.write(f'{rooms}') f.write('\n') f.write(f'{sizes}') f.write('\n') f.write(f'{lights}') f.write('\n') f.write(f'{door_direction}') f.write('\n') f.write(f'{circulations}') f.write('\n') f.write(f'{cir_Weight}') for shape in rooms_shape_list: i = rooms_shape_list.index(shape) v = shape.body.position x = order[i] name = G.nodes[x]['room'] print(f'{name} pos = ', v) screen.fill(pygame.color.THECOLORS["white"]) draw_map_pg(screen, pixel_list) draw_room(screen, G, rooms_shape_list, connection_list) draw_helptext(screen) mouse_pos = pygame.mouse.get_pos() mouse_body.position = mouse_pos space.step(1. / fps) # space.debug_draw(draw_options) pygame.display.flip() clock.tick(fps) pygame.display.set_caption("fps: " + str(clock.get_fps()))
def movement(self): grounding = { 'normal' : Vec2d.zero(), 'penetration' : Vec2d.zero(), 'impulse' : Vec2d.zero(), 'position' : Vec2d.zero(), 'body' : None } # find out if player is standing on ground def f(arbiter): n = -arbiter.contacts[0].normal if n.y > grounding['normal'].y: grounding['normal'] = n grounding['penetration'] = -arbiter.contacts[0].distance grounding['body'] = arbiter.shapes[1].body grounding['impulse'] = arbiter.total_impulse grounding['position'] = arbiter.contacts[0].position self.body.each_arbiter(f) self.well_grounded = False if grounding['body'] != None and abs(grounding['normal'].x/grounding['normal'].y) < self.feet.friction: self.well_grounded = True self.remaining_jumps = 2 self.ground_velocity = Vec2d.zero() if self.well_grounded: self.ground_velocity = grounding['body'].velocity self.target_vx = 0 if self.body.velocity.x > .01: self.direction = 1 elif self.body.velocity.x < -.01: self.direction = -1 if self.kb_handler[pyglet.window.key.LEFT]: self.direction = -1 self.target_vx -= PLAYER_VELOCITY if self.kb_handler[pyglet.window.key.RIGHT]: self.direction = 1 self.target_vx += PLAYER_VELOCITY if self.kb_handler[pyglet.window.key.DOWN]: self.direction = -3 self.feet.surface_velocity = self.target_vx, 0 if grounding['body'] != None: self.feet.friction = -PLAYER_GROUND_ACCEL/self.space.gravity.y #IGNORE:E1101 self.head.friciton = HEAD_FRICTION else: self.feet.friction, self.head.friction = 0, 0 # Air control if grounding['body'] == None: self.body.velocity.x = cpflerpconst(self.body.velocity.x, self.target_vx + self.ground_velocity.x, PLAYER_AIR_ACCEL * DT) self.body.velocity.y = max(self.body.velocity.y, -FALL_VELOCITY) # clamp upwards as well? # Move the moving platform destination = self.space.platform_path[self.space.platform_path_index] current = Vec2d(self.space.platform_body.position) distance = current.get_distance(destination) if distance < PLATFORM_SPEED: self.space.platform_path_index += 1 self.space.platform_path_index = self.space.platform_path_index % len(self.space.platform_path) t = 1 else: t = PLATFORM_SPEED / distance new = current.interpolate_to(destination, t) self.space.platform_body.position = new self.space.platform_body.velocity = (new - current) / DT # Did we land? if abs(grounding['impulse'].y) / self.body.mass > 200 and not self.landed_previous: #sound.play() self.landing = {'p':grounding['position'],'n':5} self.landed_previous = True else: self.landed_previous = False if self.landing['n'] > 0: #pygame.draw.circle(screen, pygame.color.THECOLORS['yellow'], to_pygame(landing['p'], screen), 5) self.landing['n'] -= 1
def zoom(position, scale, screen): total_pix = screen.get_height() + screen.get_width() height_frac = total_pix / screen.get_height() width_frac = total_pix / screen.get_width() return Vec2d(position.x * (1 + scale), position.y * (1 + scale))
web_group = 1 bs = [] dist = .3 cb = pymunk.Body(1,1) cb.position = c s = pymunk.Circle(cb, 15) # to have something to grab s.filter = pymunk.ShapeFilter(group = web_group) s.ignore_draw = True space.add(cb, s) #generate each crossing in the net for x in range(0,101): b = pymunk.Body(1, 1) v = Vec2d.unit() v.angle_degrees = x*18 scale = window.height / 2. / 6. * .5 dist += 1/18. dist = dist ** 1.005 offset = 0 offset = [0.0, -0.80, -1.0, -0.80][((x*18) % 360)/18 % 4] offset = .8 + offset offset *= dist**2.8 / 100. #print "offset", offset v.length = scale * (dist + offset)
def move_cat(self): speed = random.randint(50, 120) self.cat_body.angle -= random.randint(-1, 1) direction = Vec2d(1, 0).rotated(self.cat_body.angle) self.cat_body.velocity = speed * direction