def main(): pygame.init() screen = pygame.display.set_mode((600, 600)) clock = pygame.time.Clock() running = True ### Physics stuff space = pm.Space() space.gravity = Vec2d(0.0, -900.0) draw_options = pymunk.pygame_util.DrawOptions(screen) ## Balls balls = [] ### walls static_lines = [pm.Segment(space.static_body, Vec2d(111.0, 280.0), Vec2d(407.0, 246.0), 1.0) ,pm.Segment(space.static_body, Vec2d(407.0, 246.0), Vec2d(407.0, 343.0), 1.0) ] space.add(static_lines) ticks_to_next_ball = 10 while running: for event in pygame.event.get(): if event.type == QUIT: running = False pygame.quit() elif event.type == KEYDOWN and event.key == K_ESCAPE: running = False elif event.type == KEYDOWN and event.key == K_p: pygame.image.save(screen, "point_query.png") ticks_to_next_ball -= 1 if ticks_to_next_ball <= 0: ticks_to_next_ball = 100 mass = 10 radius = 25 inertia = pm.moment_for_circle(mass, 0, radius, Vec2d(0,0)) body = pm.Body(mass, inertia) x = random.randint(115,350) body.position = x, 400 shape = pm.Circle(body, radius, Vec2d(0,0)) shape.color = THECOLORS["lightgrey"] space.add(body, shape) balls.append(shape) ### Clear screen screen.fill(THECOLORS["white"]) ### Draw stuff space.debug_draw(draw_options) balls_to_remove = [] for ball in balls: if ball.body.position.y < 200: balls_to_remove.append(ball) for ball in balls_to_remove: space.remove(ball, ball.body) balls.remove(ball) mouse_pos = pymunk.pygame_util.get_mouse_pos(screen) shape = space.point_query_nearest(mouse_pos, pymunk.inf, pymunk.ShapeFilter()).shape if shape is not None: if hasattr(shape, "radius"): r = shape.radius + 4 else: r = 10 p = pymunk.pygame_util.to_pygame(shape.body.position, screen) pygame.draw.circle(screen, THECOLORS["red"], p, int(r), 2) ### Update physics dt = 1.0/60.0 for x in range(1): space.step(dt) ### Flip screen pygame.display.flip() clock.tick(50) pygame.display.set_caption("fps: " + str(clock.get_fps()))
def create(self): ''' Generate swing and robot and add to space. ''' self.actions = [0, 0, 0, 0, 0] self.velocity = 0 self.angle = 0 self.time = 0 # Define initial angle angle = Angle(self.theta) self.max_angle = 0 # Define bodies self.top = pymunk.Body(50, 10000, pymunk.Body.STATIC) self.bottom = pymunk.Body(50, 10000, pymunk.Body.STATIC) self.rod1 = pymunk.Body(10, 10000) self.rod2 = pymunk.Body(10, 10000) self.rod3 = pymunk.Body(10, 10000) self.seat = pymunk.Body(15, 10000) self.torso = pymunk.Body(10, 10000) self.legs = pymunk.Body(10, 10000) self.head = pymunk.Body(5, 10000) # Create shapes self.top_shape = pymunk.Poly.create_box(self.top, size=(1200, 50)) self.bottom_shape = pymunk.Poly.create_box(self.bottom, size=(1200, 50)) self.rod1_shape = pymunk.Segment(self.rod1, (0, 0), angle.rod1, radius=3) self.rod2_shape = pymunk.Segment(self.rod2, (0, 0), angle.rod2, radius=3) self.rod3_shape = pymunk.Segment(self.rod3, (0, 0), angle.rod3, radius=3) self.seat_shape = pymunk.Segment(self.seat, angle.seat[0], angle.seat[1], radius=5) self.torso_shape = pymunk.Poly.create_box(self.torso, size=(10, torso_length)) self.legs_shape = pymunk.Poly.create_box(self.legs, size=(10, legs_length)) self.head_shape = pymunk.Circle(self.head, radius=20) # Set layer of shapes (disables collisions between bodies) self.rod1_shape.filter = pymunk.ShapeFilter( categories=0b100, mask=pymunk.ShapeFilter.ALL_MASKS ^ 0b100) self.rod2_shape.filter = pymunk.ShapeFilter( categories=0b100, mask=pymunk.ShapeFilter.ALL_MASKS ^ 0b100) self.rod3_shape.filter = pymunk.ShapeFilter( categories=0b100, mask=pymunk.ShapeFilter.ALL_MASKS ^ 0b100) self.seat_shape.filter = pymunk.ShapeFilter( categories=0b100, mask=pymunk.ShapeFilter.ALL_MASKS ^ 0b100) self.torso_shape.filter = pymunk.ShapeFilter( categories=0b100, mask=pymunk.ShapeFilter.ALL_MASKS ^ 0b100) self.legs_shape.filter = pymunk.ShapeFilter( categories=0b100, mask=pymunk.ShapeFilter.ALL_MASKS ^ 0b100) self.head_shape.filter = pymunk.ShapeFilter( categories=0b100, mask=pymunk.ShapeFilter.ALL_MASKS ^ 0b100) # Set positions of bodies self.top.position = (600, 720) self.bottom.position = (600, 0) self.rod1.position = (600, 695) self.rod2.position = angle.point1 self.rod3.position = angle.point2 self.seat.position = angle.point4 self.torso.position = (angle.point4[0] + angle.seat[1][0] + (torso_length / 2) * math.sin(angle._theta), angle.point4[1] + angle.seat[1][1] + (torso_length / 2) * math.cos(angle._theta)) self.torso._set_angle(-angle._theta) self.legs.position = (angle.point4[0] + angle.seat[0][0] - (legs_length / 2) * math.sin(angle._theta), angle.point4[1] + angle.seat[0][1] - (legs_length / 2) * math.cos(angle._theta)) self.legs._set_angle(-angle._theta) self.head.position = (angle.point4[0] + angle.seat[1][0] + (torso_length - 10) * math.sin(angle._theta), angle.point4[1] + angle.seat[1][1] + (torso_length - 10) * math.cos(angle._theta)) # Create pivot joints for bodies self.pivot1 = pymunk.PivotJoint(self.top, self.rod1, (600, 695)) self.pivot2 = pymunk.PivotJoint(self.rod1, self.rod2, angle.point1) self.pivot3 = pymunk.PivotJoint(self.rod2, self.rod3, angle.point2) self.pivot4 = pymunk.PivotJoint(self.rod3, self.seat, angle.point4) self.pivot5 = pymunk.PinJoint(self.rod3, self.seat, anchor_a=angle.rod3, anchor_b=angle.seat[0]) self.pivot6 = pymunk.PinJoint(self.rod3, self.seat, anchor_a=angle.rod3, anchor_b=angle.seat[1]) self.pivot7 = pymunk.PivotJoint(self.torso, self.seat, (angle.point4[0] + angle.seat[1][0], angle.point4[1] + angle.seat[1][1])) self.pivot8 = pymunk.PivotJoint(self.seat, self.legs, (angle.point4[0] + angle.seat[0][0], angle.point4[1] + angle.seat[0][1])) self.pivot9 = pymunk.PivotJoint(self.head, self.torso, self.head.position) # self.arms = pymunk.DampedSpring(self.torso, self.rod3, anchor_a=(0,0), anchor_b=(0,0), rest_length=25, stiffness=100, damping=0.5) self.gear1 = pymunk.RotaryLimitJoint(self.torso, self.seat, -0.1, 0.5) self.gear2 = pymunk.RotaryLimitJoint(self.seat, self.legs, -1.2, 0.9) # Disable collisions between rods self.pivot1.collide_bodies = False self.pivot2.collide_bodies = False self.pivot3.collide_bodies = False self.pivot4.collide_bodies = False self.pivot7.collide_bodies = False self.pivot8.collide_bodies = False self.pivot9.collide_bodies = False # Add bodies and pivots to space self.space.add(self.top, self.top_shape, self.bottom, self.bottom_shape, self.rod1, self.rod1_shape, self.rod2, self.rod2_shape, self.rod3, self.rod3_shape, self.seat, self.seat_shape, self.torso, self.torso_shape, self.legs, self.legs_shape, self.head, self.head_shape, self.pivot1, self.pivot2, self.pivot3, self.pivot4, self.pivot5, self.pivot6, self.pivot7, self.pivot8, self.pivot9, self.gear1, self.gear2)
sling_x, sling_y = 135, 450 sling2_x, sling2_y = 160, 450 score = 0 game_state = 0 bird_path = [] counter = 0 restart_counter = False bonus_score_once = True bold_font = pygame.font.SysFont("arial", 30, bold=True) bold_font2 = pygame.font.SysFont("arial", 40, bold=True) bold_font3 = pygame.font.SysFont("arial", 50, bold=True) wall = False # Static floor static_body = pm.Body(body_type=pm.Body.STATIC) static_lines = [pm.Segment(static_body, (0.0, 060.0), (1200.0, 060.0), 0.0)] static_lines1 = [ pm.Segment(static_body, (1200.0, 060.0), (1200.0, 800.0), 0.0) ] for line in static_lines: line.elasticity = 0.95 line.friction = 1 line.collision_type = 3 for line in static_lines1: line.elasticity = 0.95 line.friction = 1 line.collision_type = 3 space.add(static_lines) def to_pygame(p):
def create_wall(self, x1, y1, x2, y2): env_b = self.env.static_body wall_shape = pymunk.Segment(env_b, Vec2d(x1,y1), Vec2d(x2,y2), \ self.wall_thickness) wall_shape.filter = ShapeFilter(categories=WALL_MASK) return wall_shape
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 draw_options = pymunk.pygame_util.DrawOptions(screen) # box walls static = [pymunk.Segment(space.static_body, (10, 50), (300, 50), 3) , pymunk.Segment(space.static_body, (300, 50), (325, 50), 3) , pymunk.Segment(space.static_body, (325, 50), (350, 50), 3) , pymunk.Segment(space.static_body, (350, 50), (375, 50), 3) , pymunk.Segment(space.static_body, (375, 50), (680, 50), 3) , pymunk.Segment(space.static_body, (680, 50), (680, 370), 3) , pymunk.Segment(space.static_body, (680, 370), (10, 370), 3) , pymunk.Segment(space.static_body, (10, 370), (10, 50), 3) ] 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), 3) , pymunk.Segment(space.static_body, (520, 60), (540, 80), 3) , pymunk.Segment(space.static_body, (540, 80), (550, 100), 3) , pymunk.Segment(space.static_body, (550, 100), (550, 150), 3) ] # static platforms platforms = [pymunk.Segment(space.static_body, (170, 50), (270, 150), 3) #, pymunk.Segment(space.static_body, (270, 100), (300, 100), 5) , pymunk.Segment(space.static_body, (400, 150), (450, 150), 3) , pymunk.Segment(space.static_body, (400, 200), (450, 200), 3) , pymunk.Segment(space.static_body, (220, 200), (300, 200), 3) , pymunk.Segment(space.static_body, (50, 250), (200, 250), 3) , pymunk.Segment(space.static_body, (10, 370), (50, 250), 3) ] 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(body_type=pymunk.Body.KINEMATIC) 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.filter = pymunk.ShapeFilter(categories=0b1000) space.add(passthrough) def passthrough_handler(arbiter, space, data): 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)) # Since we use the debug draw we need to hide these circles. To make it # easy we just set their color to black. feet.color = 0,0,0,0 head.color = 0,0,0,0 head2.color = 0,0,0,0 mask = pymunk.ShapeFilter.ALL_MASKS ^ passthrough.filter.categories sf = pymunk.ShapeFilter(mask=mask) head.filter = sf head2.filter = sf 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.contact_point_set.normal if n.y > grounding['normal'].y: grounding['normal'] = n grounding['penetration'] = -arbiter.contact_point_set.points[0].distance grounding['body'] = arbiter.shapes[1].body grounding['impulse'] = arbiter.total_impulse grounding['position'] = arbiter.contact_point_set.points[0].point_b 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_UP: if well_grounded or remaining_jumps > 0: jump_v = math.sqrt(2.0 * JUMP_HEIGHT * abs(space.gravity.y)) impulse = (0,body.mass * (ground_velocity.y+jump_v)) body.apply_impulse_at_local_point(impulse) 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 space.debug_draw(draw_options) 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) p = pymunk.pygame_util.to_pygame(position, screen) screen.blit(img, p, (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: p = pymunk.pygame_util.to_pygame(landing['p'], screen) pygame.draw.circle(screen, pygame.color.THECOLORS['yellow'], p, 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 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 _init_robot_body(self): # robot body body_size = (120, 60) self.robot_body = pymunk.Body(10, 1000) self.robot_body.position = (self.base_offset + 190, 340) robot = pymunk.Poly.create_box(self.robot_body, body_size, 1) robot.friction = 1 robot.mass = 8 self.space.add(self.robot_body, robot) # wheel wheel_size = 12 wheel_body = pymunk.Body(1, 10) wheel_body.position = (self.base_offset + 150, 350) wheel = pymunk.Circle(wheel_body, wheel_size) wheel.friction = 2 wheel.mass = 0.5 self.space.add(wheel_body, wheel) # wheel robot bodyjoint wheel_joint = pymunk.PivotJoint(wheel_body, self.robot_body, (0, 0), (-55, 25)) self.space.add(wheel_joint) # upper arm self.ua_body = pymunk.Body(10, 1000) upper_arm_point1 = (self.base_offset + 250, 310) upper_arm_point2 = (self.base_offset + 310, 230) self.upper_arm = pymunk.Segment(self.ua_body, upper_arm_point1, upper_arm_point2, 8) self.upper_arm.mass = 1 self.upper_arm.friction = 10 self.space.add(self.ua_body, self.upper_arm) # lower arm la_body = pymunk.Body(10, 1000) lower_arm_point2 = (self.base_offset + 370, 280) self.lower_arm = pymunk.Segment(la_body, upper_arm_point2, lower_arm_point2, 8) self.lower_arm.mass = 1 self.lower_arm.friction = 10 self.space.add(la_body, self.lower_arm) # joint robot + upper arm joint_robot = pymunk.PivotJoint(self.ua_body, self.robot_body, upper_arm_point1, (60, -30)) self.space.add(joint_robot) # joint upper arm + lower arm joint = pymunk.PivotJoint(self.ua_body, la_body, upper_arm_point2, upper_arm_point2) self.space.add(joint) # motor robot self.motor_robot = pymunk.SimpleMotor(self.robot_body, la_body, 0) self.space.add(self.motor_robot) # motor arm self.motor_arm = pymunk.SimpleMotor(self.ua_body, la_body, 0) self.space.add(self.motor_arm) # filter (to avoid collision) shape_filter = pymunk.ShapeFilter(group=1) self.upper_arm.filter = shape_filter self.lower_arm.filter = shape_filter wheel.filter = shape_filter robot.filter = shape_filter self.last_position = self.robot_body.position.x # fix initial physic body clipping for i in range(100): robot.space.step(0.01)
def add_wall(self, pt_from, pt_to): body = pymunk.Body(body_type=pymunk.Body.STATIC) ground_shape = pymunk.Segment(body, pt_from, pt_to, 0.0) ground_shape.friction = 0.8 ground_shape.elasticity = .99 self.space.add(ground_shape)
def main(): global contact global shape_to_remove pygame.init() screen = pygame.display.set_mode((600, 600)) clock = pygame.time.Clock() running = True ### Physics stuff space = pm.Space() space.gravity = (0.0, -900.0) ## Balls balls = [] ### walls static_lines = [ pm.Segment(space.static_body, (11.0, 280.0), (407.0, 246.0), 0.0), pm.Segment(space.static_body, (407.0, 246.0), (407.0, 343.0), 0.0) ] for l in static_lines: l.friction = 0.5 space.add(static_lines) ticks_to_next_ball = 10 space.add_collision_handler(0, 0, None, None, draw_collision, None, surface=screen) while running: for event in pygame.event.get(): if event.type == QUIT: running = False elif event.type == KEYDOWN and event.key == K_ESCAPE: running = False elif event.type == KEYDOWN and event.key == K_p: pygame.image.save(screen, "contact_with_friction.png") ticks_to_next_ball -= 1 if ticks_to_next_ball <= 0: ticks_to_next_ball = 100 mass = 0.1 radius = 25 inertia = pm.moment_for_circle(mass, 0, radius, (0, 0)) body = pm.Body(mass, inertia) x = random.randint(115, 350) body.position = x, 400 shape = pm.Circle(body, radius, (0, 0)) shape.friction = 0.5 space.add(body, shape) balls.append(shape) ### Clear screen screen.fill(THECOLORS["white"]) ### Draw stuff pymunk.pygame_util.draw(screen, space) balls_to_remove = [] for ball in balls: if ball.body.position.y < 200: balls_to_remove.append(ball) for ball in balls_to_remove: space.remove(ball, ball.body) balls.remove(ball) ### Update physics dt = 1.0 / 60.0 for x in range(1): space.step(dt) ### Flip screen pygame.display.flip() clock.tick(50) pygame.display.set_caption("fps: " + str(clock.get_fps()))
def main(): pygame.init() screen = pygame.display.set_mode(display_size, display_flags) pygame.display.set_caption("Mace Ragdoll Fight") width, height = screen.get_size() def to_pygame(p): """Small hack to convert pymunk to pygame coordinates""" return int(p.x), int(-p.y + height) def from_pygame(p): return to_pygame(p) clock = pygame.time.Clock() keepGoing = True # Physics stuff space = pm.Space() space.gravity = (0.0, -1900.0) space.damping = 0.999 # to prevent it from blowing up. # Add objects to space playerOne = Character.PlayerOne(space, screen) playerTwo = Character.PlayerTwo(space, screen) playerOneVictoryText = Text(screen, "Player 1 Wins!", (0, 0, 0), 500, 100, 100) playerOneVictoryText.setPosition(-1000, -1000) playerTwoVictoryText = Text(screen, "Player 2 Wins!", (0, 0, 0), 500, 100, 100) playerTwoVictoryText.setPosition(-1000, -1000) floor = pm.Segment(space.static_body, (0, 0), (width, 0), 0.5) floor.friction = 0.5 leftWall = pm.Segment(space.static_body, (0, 0), (0, height), 0.5) leftWall.friction = 0.5 roof = pm.Segment(space.static_body, (0, height), (width, height), 0.5) roof.friction = 0.5 rightWall = pm.Segment(space.static_body, (width, 0), (width, height), 0.5) rightWall.friction = 0.5 space.add(floor, leftWall, roof, rightWall) # Play Game music pygame.mixer.music.load('../assets/sound/ThisIsWhoWeAre.mp3') pygame.mixer.music.play(-1) continuePlaying = True while keepGoing: for event in pygame.event.get(): if event.type == QUIT: keepGoing = False continuePlaying = False elif event.type == KEYDOWN and event.key == K_ESCAPE: keepGoing = False continuePlaying = False elif event.type == Character.PLAYERONE_VICTOR: playerOneVictoryText.setPosition(width/3, height/2) pygame.time.set_timer(ENDGAME_EVENT, 2500) elif event.type == Character.PLAYERTWO_VICTOR: playerTwoVictoryText.setPosition(width/3, height/2) pygame.time.set_timer(ENDGAME_EVENT, 2500) elif event.type == ENDGAME_EVENT: pygame.time.set_timer(ENDGAME_EVENT, 0) keepGoing = False # Player one controls elif event.type == KEYDOWN and event.key == K_f: playerOne.kickRFoot() elif event.type == KEYDOWN and event.key == K_d: playerOne.reverseKickRFoot() elif event.type == KEYDOWN and event.key == K_r: playerOne.kickLFoot() elif event.type == KEYDOWN and event.key == K_e: playerOne.reverseKickLFoot() elif event.type == KEYDOWN and event.key == K_v: playerOne.punchRight() elif event.type == KEYDOWN and event.key == K_c: playerOne.reversePunchRight() elif event.type == KEYDOWN and event.key == K_x: playerOne.punchLeft() elif event.type == KEYDOWN and event.key == K_z: playerOne.reversePunchLeft() # Player two controls elif event.type == KEYDOWN and event.key == K_j: playerTwo.kickRFoot() elif event.type == KEYDOWN and event.key == K_k: playerTwo.reverseKickRFoot() elif event.type == KEYDOWN and event.key == K_u: playerTwo.kickLFoot() elif event.type == KEYDOWN and event.key == K_i: playerTwo.reverseKickLFoot() elif event.type == KEYDOWN and event.key == K_n: playerTwo.punchRight() elif event.type == KEYDOWN and event.key == K_m: playerTwo.reversePunchRight() elif event.type == KEYDOWN and event.key == K_COMMA: playerTwo.punchLeft() elif event.type == KEYDOWN and event.key == K_PERIOD: playerTwo.reversePunchLeft() # Clear screen screen.fill(THECOLORS["white"]) playerOne.update() playerTwo.update() playerOneVictoryText.update() playerTwoVictoryText.update() for constraint in space.constraints: if (isinstance(constraint, pm.PinJoint)): pv1 = constraint.a.position + constraint.anchor_a pv2 = constraint.b.position + constraint.anchor_b p1 = to_pygame(pv1) p2 = to_pygame(pv2) pygame.draw.aalines(screen, THECOLORS["lightgray"], False, [p1, p2]) # Update physics fps = 50 iterations = 25 dt = 1.0 / float(fps) / float(iterations) for x in range(iterations): # 10 iterations to get a more stable simulation space.step(dt) pygame.display.flip() clock.tick(fps) return continuePlaying
def main(): pygame.init() screen = pygame.display.set_mode((600, 600)) clock = pygame.time.Clock() space = pymunk.Space() space.gravity = 0, 980 static = [ pymunk.Segment(space.static_body, (0, -50), (-50, 650), 5), pymunk.Segment(space.static_body, (0, 650), (650, 650), 5), pymunk.Segment(space.static_body, (650, 650), (650, -50), 5), pymunk.Segment(space.static_body, (-50, -50), (650, -50), 5), ] for s in static: s.collision_type = 1 space.add(*static) def pre_solve(arb, space, data): s = arb.shapes[0] space.remove(s.body, s) return False space.add_collision_handler(0, 1).pre_solve = pre_solve terrain_surface = pygame.Surface((600, 600)) terrain_surface.fill(pygame.Color("white")) color = pygame.color.THECOLORS["pink"] pygame.draw.circle(terrain_surface, color, (450, 120), 100) generate_geometry(terrain_surface, space) for x in range(25): mass = 1 moment = pymunk.moment_for_circle(mass, 0, 10) body = pymunk.Body(mass, moment) body.position = 450, 120 shape = pymunk.Circle(body, 10) shape.friction = 0.5 space.add(body, shape) draw_options = pymunk.pygame_util.DrawOptions(screen) pymunk.pygame_util.positive_y_is_up = False fps = 60 while True: for event in pygame.event.get(): if ( event.type == pygame.QUIT or event.type == pygame.KEYDOWN and (event.key in [pygame.K_ESCAPE, pygame.K_q]) ): sys.exit(0) elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 3: pass elif event.type == pygame.KEYDOWN and event.key == pygame.K_r: terrain_surface.fill(pygame.Color("white")) for s in space.shapes: if hasattr(s, "generated") and s.generated: space.remove(s) elif event.type == pygame.KEYDOWN and event.key == pygame.K_g: generate_geometry(terrain_surface, space) elif event.type == pygame.KEYDOWN and event.key == pygame.K_p: pygame.image.save(screen, "deformable.png") if pygame.mouse.get_pressed()[0]: if pygame.key.get_mods() & pygame.KMOD_SHIFT: mass = 1 moment = pymunk.moment_for_circle(mass, 0, 10) body = pymunk.Body(mass, moment) body.position = pygame.mouse.get_pos() shape = pymunk.Circle(body, 10) shape.friction = 0.5 space.add(body, shape) else: color = pygame.Color("pink") pos = pygame.mouse.get_pos() pygame.draw.circle(terrain_surface, color, pos, 25) space.step(1.0 / fps) screen.fill(pygame.Color("white")) screen.blit(terrain_surface, (0, 0)) space.debug_draw(draw_options) draw_helptext(screen) pygame.display.flip() clock.tick(fps) pygame.display.set_caption("fps: " + str(clock.get_fps()))
def main(): pygame.init() screen = pygame.display.set_mode((1000, 750)) pygame.display.set_caption("KDC HW2 Parts 5 and 6") clock = pygame.time.Clock() space = pymunk.Space() space.gravity = (0.0, -2000.0) # add floor body = pymunk.Body(body_type=pymunk.Body.STATIC) body.position = (0, 100) floor = pymunk.Segment(body, (-1000, 100), (1000, 100), 1) floor.filter = pymunk.ShapeFilter(mask=pymunk.ShapeFilter.ALL_MASKS ^ 0x1) floor.friction = 1 space.add(floor) # add cart cart_mass = 1 cart_size = (200, 40) cart_moment = pymunk.moment_for_box(cart_mass, cart_size) cart_body = pymunk.Body(cart_mass, cart_moment) cart_body.position = (500, 300) cart_shape = pymunk.Poly.create_box(cart_body, cart_size) cart_shape.color = pygame.color.THECOLORS["red"] cart_shape.filter = pymunk.ShapeFilter(group=1) #add wheels wheel_mass = 0.5 wheel_size = 20 wheel_moment = pymunk.moment_for_circle(wheel_mass, 0, wheel_size) front_wheel_body = pymunk.Body(wheel_mass, wheel_moment) back_wheel_body = pymunk.Body(wheel_mass, wheel_moment) front_wheel_body.position = (575, 260) back_wheel_body.position = (425, 260) front_wheel_shape = pymunk.Circle(front_wheel_body, wheel_size) back_wheel_shape = pymunk.Circle(back_wheel_body, wheel_size) front_wheel_shape.friction = 1 back_wheel_shape.friction = 1 front_wheel_shape.color = pygame.color.THECOLORS["black"] back_wheel_shape.color = pygame.color.THECOLORS["black"] front_wheel_shape.filter = pymunk.ShapeFilter(group=1) back_wheel_shape.filter = pymunk.ShapeFilter(group=1) #add pole pole_mass = 0.1 pole_size = (1, 200) pole_moment = pymunk.moment_for_box(pole_mass, pole_size) pole_body = pymunk.Body(pole_mass, pole_moment) pole_body.position = (500, 220) pole_shape = pymunk.Poly.create_box(pole_body, pole_size) pole_shape.color = pygame.color.THECOLORS["black"] pole_shape.filter = pymunk.ShapeFilter(categories=0x1, group=1) #create joints front_joint = pymunk.constraint.PivotJoint(front_wheel_body, cart_body, (575, 260)) back_joint = pymunk.constraint.PivotJoint(back_wheel_body, cart_body, (425, 260)) pole_joint = pymunk.constraint.PivotJoint(pole_body, cart_body, (500, 320)) #add everything to the world space.add(cart_body, cart_shape, front_wheel_body, front_wheel_shape, back_wheel_body, back_wheel_shape, pole_body, pole_shape, front_joint, back_joint, pole_joint) draw_options = pymunk.pygame_util.DrawOptions(screen) ticks = 0 while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) elif event.type == KEYDOWN and event.key == K_ESCAPE: sys.exit(0) screen.fill((255, 255, 255)) space.debug_draw(draw_options) space.step(1 / 50.0) pygame.display.flip() if ticks == 0: pole_body.apply_impulse_at_local_point((1, 0), (0, 0)) # do control here p = (pole_body.position.x - cart_body.position.x) v = pole_body.velocity_at_local_point((0, 0)).x theta = pole_body.angle dtheta = pole_body.angular_velocity enerr = (0.0125 * (dtheta * dtheta)) - (0.4905 * (1 + math.cos(theta))) a = 7.5 b = 0.25 c = 7.5 d = 1 k = 20 if theta > (math.pi - 0.5) and theta < (math.pi + 0.5): f = (a * p) + (b * v) + (c * (math.pi - theta)) + (d * dtheta) else: f = k * enerr * math.cos(theta) * dtheta cart_body.apply_impulse_at_local_point((f, 0), (0, 0)) ticks += 1 clock.tick(50)
def __init__(self, width, height, title): super().__init__(width, height, title) # Set the working directory (where we expect to find files) to the same # directory this .py file is in. You can leave this out of your own # code, but it is needed to easily run the examples using "python -m" # as mentioned at the top of this program. file_path = os.path.dirname(os.path.abspath(__file__)) os.chdir(file_path) arcade.set_background_color(arcade.color.DARK_SLATE_GRAY) # -- Pymunk self.space = pymunk.Space() self.space.iterations = 35 self.space.gravity = (0.0, -900.0) # Lists of sprites or lines self.sprite_list: arcade.SpriteList[PhysicsSprite] = arcade.SpriteList( ) self.static_lines = [] # Used for dragging shapes around with the mouse self.shape_being_dragged = None self.last_mouse_position = 0, 0 self.draw_time = 0 self.processing_time = 0 # Create the floor floor_height = 80 body = pymunk.Body(body_type=pymunk.Body.STATIC) shape = pymunk.Segment(body, [0, floor_height], [SCREEN_WIDTH, floor_height], 0.0) shape.friction = 0.2 shape.elasticity = 0.7 self.space.add(shape) self.static_lines.append(shape) # Create the stacks of boxes for row in range(10): for column in range(10): size = 32 mass = 1.0 x = 500 + column * 32 y = (floor_height + size / 2) + row * size moment = pymunk.moment_for_box(mass, (size, size)) body = pymunk.Body(mass, moment) body.position = pymunk.Vec2d(x, y) shape = pymunk.Poly.create_box(body, (size, size)) shape.elasticity = 0.7 shape.friction = 0.2 self.space.add(body, shape) # body.sleep() sprite = BoxSprite( shape, ":resources:images/tiles/boxCrate_double.png", width=size, height=size) self.sprite_list.append(sprite)
def main(): pygame.init() screen = pygame.display.set_mode((600, 600)) pygame.display.set_caption("NEAT ball keeper [Press F to turn on/off fast mode, arrow keys to move ball]") ### Physics stuff space = pm.Space() space.gravity = Vec2d(0.0, -500.0) # walls - the left-top-right walls body = pm.Body() walls= [pm.Segment(body, (50, 50), (50, 1550), 10) ,pm.Segment(body, (50, 1550), (560, 1550), 10) ,pm.Segment(body, (560, 1550), (560, 50), 10) ] floor = pm.Segment(body, (50, 50), (560, 50), 10) floor.friction = 1.0 floor.elasticity = 0.0 floor.collision_type = collision_type_floor for s in walls: s.friction = 0 s.elasticity = 0.99 s.collision_type = collision_type_wall space.add(walls) space.add(floor) g = NEAT.Genome(0, 6, 0, 2, False, NEAT.ActivationFunction.TANH, NEAT.ActivationFunction.UNSIGNED_SIGMOID, 0, params) pop = NEAT.Population(g, params, True, 1.0, rnd.randint(0, 1000)) best_genome_ever = None fast_mode = True for generation in range(1000): print("Generation:", generation) now = time.time() genome_list = [] for s in pop.Species: for i in s.Individuals: genome_list.append(i) print('All individuals:', len(genome_list)) for i, g in enumerate(genome_list): total_fitness = 0 for trial in range(20): f, fast_mode = evaluate(g, space, screen, fast_mode, rnd.randint(80, 400), rnd.randint(-200, 200), rnd.randint(80, 400)) total_fitness += f g.SetFitness(total_fitness / 20) print() best = max([x.GetLeader().GetFitness() for x in pop.Species]) print('Best fitness:', best, 'Species:', len(pop.Species)) # Draw the best genome's phenotype if best >= 10000: break # evolution is complete if an individual keeps the ball up for that many timesteps print("Evaluation took", time.time() - now, "seconds.") print("Reproducing..") now = time.time() pop.Epoch() print("Reproduction took", time.time() - now, "seconds.") # Show the best genome's performance forever pygame.display.set_caption("Best genome ever") while True: evaluate(pop.Species[0].GetLeader(), space, screen, False, rnd.randint(80, 400), rnd.randint(-200, 200), rnd.randint(80, 400))
def build_wall(self, point_a, point_b, thickness=5): body = pm.Body(body_type=pm.Body.STATIC) shape = pm.Segment(body, point_a, point_b, thickness) shape.color = GRAY return body, shape
def main(): pygame.init() screen = pygame.display.set_mode((1336, 720)) clock = pygame.time.Clock() running = True gravx = 10 ### Physics stuff space = pymunk.Space() space.gravity = gravx, -900.0 pygame.mixer.music.load("Sans.mp3") pygame.mixer.music.set_volume(1) pygame.mixer.music.play(-1) ## Balls balls = [] ### Mouse mouse_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC) mouse_shape = pymunk.Circle(mouse_body, 3, (0, 0)) mouse_shape.collision_type = COLLTYPE_MOUSE space.add(mouse_shape) space.add_collision_handler(COLLTYPE_MOUSE, COLLTYPE_BALL).pre_solve = mouse_coll_func ### Static line line_point1 = None static_lines = [] run_physics = True dic = {} lone = 1 baka = False while running: gravx += 1 #stop loop if its at the second last instant if lone == len(coordinates) - 1: break # Reading data from file and using coords for it [BALLS] # time.sleep(0.1) if lone % 1336 == 0: lonex = 2 baka = True k.position = (20, 50) # if baka: # space.remove(dic[lonex].body=N) # space.add_post_step_callback(space.remove, ball) # space.add_post_step_callback(space.remove, ball.body) for i in range(len(dic.keys()) - 1): # if dic if i == 1334: break print(list(dic.keys())) index = list(dic.keys())[i] index2 = list(dic.keys())[i] print(index) dic[index] = dic[index2] # p=(int(coordinates[lone][0])%1336,50) # print(p) if (lone == 1 and gravx == 11): p2 = (20, 500) body = pymunk.Body(1, 1) body.position = p2 k = body firstcircle = body shape = pymunk.Circle(body, 1, (0, 0)) # shape.elasticity=1.0 shape.friction = 0.0 shape.collision_type = COLLTYPE_BALL space.add(body, shape) balls.append(shape) # print(list(k.position)) lone += 1 # z=balls[0].body.position # balls[0].body.apply_force_at_world_point((10,0),(z)) changepath = 0 # Reading data from file and using coords for it [LINES] lonex = lone % 1337 if lone % 1336 == 0: continue baka = True line_point1 = Vec2d((int(lonex)), flipy(10 * int(coordinates[lone][0])) - 200) line_point2 = Vec2d(((int(lonex))), flipy(10 * int(coordinates[lone + 1][0])) - 200) body = pymunk.Body(body_type=pymunk.Body.STATIC) shape = pymunk.Segment(body, line_point1, line_point2, 10.0) shape.friction = 0 space.add(shape) static_lines.append(shape) dic[lonex] = shape poscoords = list(k.position) k.apply_force_at_world_point((int(poscoords[0]), int(poscoords[1])), list(k.position)) for event in pygame.event.get(): if event.type == QUIT: running = False elif event.type == KEYDOWN and event.key == K_ESCAPE: running = False elif event.type == KEYDOWN and event.key == K_d: k.apply_force_at_world_point((1000, 0), k.position) elif event.type == KEYDOWN and event.key == K_a: k.apply_force_at_world_point((-1000, 0), k.position) elif event.type == KEYDOWN and event.key == K_p: pygame.image.save(screen, "balls_and_lines.png") elif event.type == MOUSEBUTTONDOWN and pygame.mouse.get_pressed( )[0]: # print(event.pos[X],flipy(event.pos[Y])) p = event.pos[X], flipy(event.pos[Y]) print("HELPPP") relpos = p - (k.position) print(relpos) k.apply_force_at_world_point( (100 * (int(relpos[0])), 100 * (int(relpos[1]))), k.position) # elif event.type == MOUSEBUTTONDOWN and event.button == 3: # if line_point1 is None: # line_point1 = Vec2d(event.pos[X], flipy(event.pos[Y])) elif event.type == MOUSEBUTTONUP and event.button == 3: if line_point1 is not None: line_point2 = Vec2d(event.pos[X], flipy(event.pos[Y])) body = pymunk.Body(body_type=pymunk.Body.STATIC) shape = pymunk.Segment(body, line_point1, line_point2, 1000000000.0) shape.friction = 0.0 space.add(shape) static_lines.append(shape) line_point1 = None elif event.type == KEYDOWN and event.key == K_SPACE: run_physics = not run_physics p = pygame.mouse.get_pos() mouse_pos = Vec2d(p[X], flipy(p[Y])) mouse_body.position = mouse_pos if pygame.key.get_mods() & KMOD_SHIFT and pygame.mouse.get_pressed( )[0]: body = pymunk.Body(10, 10) body.position = mouse_pos shape = pymunk.Circle(body, 5, (0, 0)) shape.collision_type = COLLTYPE_BALL space.add(body, shape) balls.append(shape) ### Update physics if run_physics: dt = 1.0 / 60.0 for x in range(1): space.step(dt) ### Draw stuff screen.fill(THECOLORS["red"]) # Display some text font = pygame.font.Font(None, 16) text = """LMB: Create ball LMB + Shift: Create many balls RMB: Drag to create wall, release to finish Space: Pause physics simulation""" y = 5 for line in text.splitlines(): text = font.render(line, 1, THECOLORS["black"]) screen.blit(text, (5, y)) y += 10 for ball in balls: r = ball.radius v = ball.body.position rot = ball.body.rotation_vector p = int(v.x), int(flipy(v.y)) p2 = Vec2d(rot.x, -rot.y) * r * 0.9 pygame.draw.circle(screen, THECOLORS["blue"], p, int(r), 1) pygame.draw.line(screen, THECOLORS["red"], p, p + p2) # if line_point1 is not None: # p1 = line_point1.x, flipy(line_point1.y) # p2 = mouse_pos.x, flipy(mouse_pos.y) # pygame.draw.lines(screen, THECOLORS["black"], False, [p1,p2]) for i in dic: line = dic[i] body = line.body # print(list(line.a.rotated(body.angle))+["fhfjffjfjh"]) pv1 = body.position + line.a.rotated(body.angle) pv2 = body.position + line.b.rotated(body.angle) p1 = pv1.x, flipy(pv1.y) p2 = pv2.x, flipy(pv2.y) pygame.draw.lines(screen, THECOLORS["lightgray"], False, [p1, p2]) ### Flip screen pygame.display.flip() # clock.tick(50) pygame.display.set_caption("fps: " + str(clock.get_fps()))
import pymunk from pymunk.vec2d import Vec2d from pymunk.pyglet_util import draw config = pyglet.gl.Config(sample_buffers=1, samples=2, double_buffer=True) window = pyglet.window.Window(config=config, vsync=False) space = pymunk.Space() space.gravity = 0, -900 space.damping = .999 c = Vec2d(window.width / 2., window.height / 2.) ### CONTAINER ss = [ pymunk.Segment(space.static_body, (0, 0), (window.width, 0), 5), pymunk.Segment(space.static_body, (window.width, 0), (window.width, window.height), 5), pymunk.Segment(space.static_body, (window.width, window.height), (0, window.height), 5), pymunk.Segment(space.static_body, (0, window.height), (0, 0), 5) ] for s in ss: s.friction = .5 s.layers = s.layers ^ 0b100 space.add(ss) ### WEB web_group = 1
def main(): pygame.init() screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) # pygame.FULLSCREEN) pygame.display.set_caption("BlueYonder challenge") clock = pygame.time.Clock() space.gravity = (0, 0) balls_shapes = [] balls_bodies = [] line_point1 = None static_lines = [] draw_options = pymunk.pygame_util.DrawOptions(screen) ticks_to_next_ball = 10 while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == K_SPACE: p = (pygame.mouse.get_pos()[0], pygame.display.get_surface().get_size()[1] - pygame.mouse.get_pos()[1]) active_shape = None for s in balls_shapes: dist, info = s.point_query(p) if dist < 0: active_shape = s if active_shape != None: s = active_shape r = int(s.radius) pygame.draw.circle(screen, (100, 100, 100), p, r, 3) elif event.type == pygame.KEYUP: if active_shape != None: active_shape.body.position = ( pygame.mouse.get_pos()[0], pygame.display.get_surface().get_size()[1] - pygame.mouse.get_pos()[1]) elif event.type == MOUSEBUTTONDOWN and event.button == 1: ball_shape = add_ball(space) balls_shapes.append(ball_shape[0]) balls_bodies.append(ball_shape[1]) elif event.type == MOUSEBUTTONDOWN and event.button == 3: if line_point1 is None: line_point1 = Vec2d( pygame.mouse.get_pos()[0], pygame.display.get_surface().get_size()[1] - pygame.mouse.get_pos()[1]) elif event.type == MOUSEBUTTONUP and event.button == 3: if line_point1 is not None: line_point2 = Vec2d( pygame.mouse.get_pos()[0], pygame.display.get_surface().get_size()[1] - pygame.mouse.get_pos()[1]) body = pymunk.Body(body_type=pymunk.Body.STATIC) shape = pymunk.Segment(body, line_point1, line_point2, 0.0) shape.friction = 0.99 space.add(shape) static_lines.append(shape) line_point1 = None elif event.type == KEYDOWN: if event.key == K_ESCAPE: sys.exit(0) for outer_body in balls_bodies: dist_x = 0 dist_y = 0 for inner_body in balls_bodies: if inner_body != outer_body: dist_x = outer_body.position[0] - inner_body.position[0] dist_y = outer_body.position[1] - inner_body.position[1] d = math.sqrt(dist_x**2 + dist_y**2) f = G * outer_body.mass * inner_body.mass / (d**2) theta = math.atan2(dist_y, dist_x) fx = math.cos(theta) * f fy = math.sin(theta) * f mutator = 10000000000000000 outer_body.apply_force_at_local_point( (fx * mutator, fy * mutator), (0, 0)) space.step(1 / 50.0) screen.fill((0, 0, 0)) space.debug_draw(draw_options) pygame.display.flip() clock.tick(50)
def run(): pygame.init() pygame.display.set_caption("Launch and Smash") screen = pygame.display.set_mode((width, height)) clock = pygame.time.Clock() font = pygame.font.SysFont("Arial", 16) # We will draw two versions of the Pymunk Space, each on a separate surface # to make it easy to show both at the same time. surf1 = pygame.Surface((300, 300)) # Setup the base Pymunk Space. space1 = pymunk.Space() space1.gravity = 0, -1000 space1.sleep_time_threshold = 0.1 draw_options1 = pymunk.pygame_util.DrawOptions(surf1) box = [(5, 5), (295, 5), (295, 295), (5, 295)] for i, p1 in enumerate(box): if i + 1 >= len(box): p2 = box[0] else: p2 = box[i + 1] l = pymunk.Segment(space1.static_body, p1, p2, 5) l.elasticity = 0.5 l.friction = 1 space1.add(l) template_box = pymunk.Poly.create_box(pymunk.Body(), (20, 20)) template_box.mass = 1 template_box.friction = 1 for x in range(3): for y in range(7): box = template_box.copy() box.body.position = 200 + x * 30, 10 + y * 20 space1.add(box, box.body) b = pymunk.Body() b.position = 30, 100 ball = pymunk.Circle(b, 20) ball.mass = 20 ball.friction = 1 ball.color = THECOLORS['red'] space1.add(ball, b) # this is the same as space2 = copy.deepcopy(space1) space2 = space1.copy() space2.sleep_time_threshold = float('inf') backup1 = space1.copy() backup2 = space2.copy() while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() elif event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]): pygame.quit() elif event.type == KEYDOWN and event.key == K_s: with open("copy_and_pickle.pickle", "wb") as f: pickle.dump([space1, space2], f) elif event.type == KEYDOWN and event.key == K_l: with open("copy_and_pickle.pickle", "rb") as f: (space1, space2) = pickle.load(f) elif event.type == KEYDOWN and event.key == K_r: space1 = backup1 space2 = backup2 backup1 = space1.copy() backup2 = space2.copy() elif event.type == KEYDOWN and event.key == K_SPACE: # find all bodies with a circle shape in all spaces for s in space1.shapes + space2.shapes: if isinstance(s, pymunk.Circle) and s.body != None: s.body.apply_impulse_at_local_point((20000, 0)) elif event.type == KEYDOWN and event.key == K_p: pygame.image.save(screen, "copy_and_pickle.png") ### Clear screen screen.fill(THECOLORS["white"]) ### Draw stuff surf1.fill(THECOLORS["black"]) space1.debug_draw(draw_options1) screen.blit(surf1, (50, 100)) ### Update physics fps = 60 dt = 1. / fps space1.step(dt) space2.step(dt) ### Info and flip screen def dt(txt, pos): screen.blit(font.render(txt, 1, THECOLORS["black"]), pos) #dt("space.sleep_time_threshold set to 0.5 seconds", (50,80)) dt("fps: " + str(clock.get_fps()), (0, 0)) dt("Press SPACE to give an impulse to the ball.", (5, height - 50)) dt("Press S to save the current state to file, press L to load it.", (5, height - 35)) dt("Press R to reset, ESC or Q to quit", (5, height - 20)) pygame.display.flip() clock.tick(fps)
# init pymunk and space space = pymunk.Space() space.gravity = (0.0, -10.0) # setup four side of screen segments = [ (( 0, ScreenSize[1]), (ScreenSize[0], ScreenSize[1])), ((ScreenSize[0], ScreenSize[1]), (ScreenSize[0], 0)), ((ScreenSize[0], 0), ( 0, 0)), (( 0, 0), ( 0, ScreenSize[1])), ] for segment in segments: body = pymunk.Body(pymunk.inf, pymunk.inf) shape = pymunk.Segment(body, InvCoord(segment[0]), InvCoord(segment[1]), 0.0) shape.friction = 0.5 space.add_static(shape) bubbles = [] isRunning = True while isRunning: for event in pygame.event.get(): if event.type == pygame.locals.QUIT: isRunning = False elif event.type == pygame.locals.KEYDOWN: if event.key == pygame.locals.K_ESCAPE: isRunning = False elif (event.key >= pygame.locals.K_a and event.key <= pygame.locals.K_z) or \ (event.key >= pygame.locals.K_0 and event.key <= pygame.locals.K_9): bubbles.append(Bubble(screen, space, chr(event.key)),)
clock = pygame.time.Clock() draw_options = DrawOptions(screen) space = pymunk.Space() space.gravity = 0, -1000 sprites = [] previous = (-100, 100) while previous[0] < 9000: x = previous[0] + random.randint(100, 500) y = previous[1] + random.randint(-100, 100) floor = pymunk.Segment(space.static_body, previous, (x, y), 5) floor.friction = 1.0 space.add(floor) sprites.append((floor.body, floor)) previous = (x, y) pog_car = create_pogo(space, 400, 600) create_pogo(space, 400, 500) create_pogo(space, 400, 700) motors, car = create_rover(space, 200, 600) acc = 8 dec = 8 max_speed = 20 motor_speed = 0
def __init__(self, world): """ Create a Scenery. :return: """ Entity.__init__(self) random.seed() s = world._space_size body = world._space.static_body # outer border self.static_lines = [] self.static_lines.append(pymunk.Segment(body, (0, 0), (s[0], 0), 1.0)) self.static_lines.append( pymunk.Segment(body, (s[0], 0), (s[0], s[1]), 1.0)) self.static_lines.append( pymunk.Segment(body, (s[0], s[1]), (0, s[1]), 1.0)) self.static_lines.append(pymunk.Segment(body, (0, s[1]), (0, 0), 1.0)) # Landscape # bottom ix = [] iy = [] num = random.randrange(20) for _ in range(2 + num + 2): ix.append(random.random() * s[0]) iy.append(random.random() * s[1] * 0.5) ix.sort() ix[0] = 0 ix[len(ix) - 1] = s[0] for i in range(len(ix) - 1): self.static_lines.append( pymunk.Segment(body, (ix[i], iy[i]), (ix[i + 1], iy[i + 1]), 1.0)) # Cave # Top ix = [] iy = [] num = random.randrange(20) for _ in range(2 + num + 2): ix.append(random.random() * s[0]) iy.append(s[1] - random.random() * s[1] * 0.3) ix.sort() ix[0] = 0 ix[len(ix) - 1] = s[0] for i in range(len(ix) - 1): self.static_lines.append( pymunk.Segment(body, (ix[i], iy[i]), (ix[i + 1], iy[i + 1]), 1.0)) #self.static_linesbottom = [pymunk.Segment(body, (0, 10), (s[0]/2, 20.0), 1.0), # pymunk.Segment(body, (s[0]/2,20.0), (s[0],10), 10.0)] for line in self.static_lines: line.elasticity = 0.9 line.friction = 0.9 world._space.add(self.static_lines)
def __init__(self, wnd): self.wnd = wnd self.ctx = ModernGL.create_context() self.prog = self.ctx.program([ self.ctx.vertex_shader(''' #version 330 uniform vec4 Camera; // Per vertex in vec2 in_vert; in vec2 in_texture; // Per instance in vec3 in_pos; in vec2 in_size; in vec4 in_tint; out vec2 v_vert; out vec2 v_texture; out vec4 v_tint; void main() { mat2 rotate = mat2( cos(in_pos.z), sin(in_pos.z), -sin(in_pos.z), cos(in_pos.z) ); v_vert = rotate * (in_vert * in_size) + in_pos.xy; gl_Position = vec4((v_vert - Camera.xy) / Camera.zw, 0.0, 1.0); v_texture = in_texture; v_tint = in_tint; } '''), self.ctx.fragment_shader(''' #version 330 uniform sampler2D Texture; in vec2 v_vert; in vec2 v_texture; in vec4 v_tint; out vec4 f_color; void main() { vec4 tex = texture(Texture, v_texture); vec3 color = tex.rgb * (1.0 - v_tint.a) + v_tint.rgb * v_tint.a; f_color = vec4(color, tex.a); } '''), ]) img = Image.open(local('data', 'crate.png')).convert('RGBA') self.tex1 = self.ctx.texture(img.size, 4, img.tobytes()) self.tex1.use(0) img = Image.open(local('data', 'ball.png')).convert('RGBA') self.tex2 = self.ctx.texture(img.size, 4, img.tobytes()) self.tex2.use(1) vertices = np.array([ -1.0, -1.0, 0.0, 0.0, -1.0, 1.0, 0.0, 1.0, 1.0, -1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, ]) vbo1 = self.ctx.buffer(vertices.astype('f4').tobytes()) self.vbo2 = self.ctx.buffer(reserve=1024 * 1024) vao_content = [ (vbo1, '2f2f', ['in_vert', 'in_texture']), (self.vbo2, '3f2f4f/i', ['in_pos', 'in_size', 'in_tint']), ] self.vao = self.ctx.vertex_array(self.prog, vao_content) self.space = pymunk.Space() self.space.gravity = (0.0, -900.0) shape = pymunk.Segment(self.space.static_body, (5, 100), (595, 100), 1.0) shape.friction = 1.0 self.space.add(shape) self.bodies = [] self.balls = [] for x in range(5): for y in range(10): size = 20 mass = 10.0 moment = pymunk.moment_for_box(mass, (size, size)) body = pymunk.Body(mass, moment) body.position = Vec2d(300 + x * 50, 105 + y * (size + 0.1)) shape = pymunk.Poly.create_box(body, (size, size)) shape.friction = 0.3 self.space.add(body,shape) self.bodies.append(body)
def add_plane(x0, y0, x1, y1, r): body = pymunk.Body(body_type=pymunk.Body.STATIC) shape = pymunk.Segment(body, (x0, y0), (x1, y1), r) shape.elasticity = 0.5 shape.friction = 10 space.add(body, shape)
def testSetNeighbors(self): c = p.Segment(None, (2,2), (2,3), 1) c.set_neighbors((2,2),(2,3))
circle_moment = pymunk.moment_for_circle(mass, 0, radius) circle_body = pymunk.Body(mass, circle_moment) circle_body.position = 100, 100 circle_shape = pymunk.Circle(circle_body, radius) ############# Square(POLY) ############## poly_shape = pymunk.Poly.create_box(None, size=(50,50)) poly_moment = pymunk.moment_for_poly(mass, poly_shape.get_vertices()) poly_body = pymunk.Body(mass, poly_moment) poly_shape.body = poly_body poly_body.position = 250,100 ############# Segment (Line) ########### segment_moment = pymunk.moment_for_segment(mass, (0,0), (0,400), 2) segment_body = pymunk.Body(mass, segment_moment) segment_shape = pymunk.Segment(segment_body, (0,0), (0,400), 2) segment_body.position = 400, 100 ############ Triangle ########### triangle_shape = pymunk.Poly(None, ((0,0), (100,0), (50,100))) triangle_moment = pymunk.moment_for_poly(mass, triangle_shape.get_vertices()) triangle_body = pymunk.Body(mass, triangle_moment) triangle_body.position = 550, 100 triangle_shape.body = triangle_body ########### Pentagon ######### penta_shape = pymunk.Poly(None, ((0,0), (100,0), (150,100), (50,200), (-50, 100))) penta_moment = pymunk.moment_for_poly(mass, penta_shape.get_vertices()) penta_body = pymunk.Body(mass, penta_moment) penta_body.position = 700,100 penta_shape.body = penta_body
def add_oil_unit(space): body = pymunk.Body() body.position = (300,300) #oil storage unit l1 = pymunk.Segment(body, (-278, 270), (-278, 145), 5) #left side line l2 = pymunk.Segment(body, (-278, 145), (-246, 107), 5) l3 = pymunk.Segment(body, (-180, 270), (-180, 145), 5) #right side line l4 = pymunk.Segment(body, (-180, 145), (-215, 107), 5) #pipe to separator vessel l5 = pymunk.Segment(body, (-246, 107), (-246, 53), 5) #left side vertical line l6 = pymunk.Segment(body, (-246, 53), (-19, 53), 5) #bottom horizontal line l7 = pymunk.Segment(body, (-19, 53), (-19, 33), 5) l8 = pymunk.Segment(body, (-215, 107), (-215, 80), 5) #right side vertical line l9 = pymunk.Segment(body, (-215, 80), (7, 80), 5) #top horizontal line l10 = pymunk.Segment(body, (7, 80), (7, 33), 5) #separator vessel l11 = pymunk.Segment(body, (-19, 31), (-95, 31), 5) #top left horizontal line l12 = pymunk.Segment(body, (-95, 31), (-95, -23), 5) #left side vertical line l13 = pymunk.Segment(body, (-95, -23), (-83, -23), 5) l14 = pymunk.Segment(body, (-83, -23), (-80, -80), 5) #left waste exit line l15 = pymunk.Segment(body, (-68, -80), (-65, -23), 5) #right waste exit line l16 = pymunk.Segment(body, (-65, -23), (-45, -23), 5) l17 = pymunk.Segment(body, (-45, -23), (-45, -67), 5) #elevation vertical line l18 = pymunk.Segment(body, (-45, -67), (13, -67), 5) #left bottom line l19 = pymunk.Segment(body, (13, -67), (13, -82), 5) #left side separator exit line l20 = pymunk.Segment(body, (43, -82), (43, -67), 5) #right side separator exit line l21 = pymunk.Segment(body, (43, -67), (65, -62), 5) #rigt side diagonal line l22 = pymunk.Segment(body, (65, -62), (77, 31), 5) #right vertical line l23 = pymunk.Segment(body, (77, 31), (7, 31), 5) #top right horizontal line l24 = pymunk.Segment(body, (-3, -67), (-3, 10), 5) #center separator line #separator exit pipe l25 = pymunk.Segment(body, (43, -85), (43, -113), 5) #right side vertical line l26 = pymunk.Segment(body, (43, -113), (580, -113), 5) #top horizontal line l27 = pymunk.Segment(body, (13, -85), (13, -140), 5) #left vertical line l28 = pymunk.Segment(body, (13, -140), (580, -140), 5) #bottom horizontal line #waste water pipe l29 = pymunk.Segment(body, (-87, -85), (-87, -112), 5) #left side waste line l30 = pymunk.Segment(body, (-60, -85), (-60, -140), 5) #right side waste line l31 = pymunk.Segment(body, (-87, -112), (-163, -112), 5) #top horizontal line l32 = pymunk.Segment(body, (-60, -140), (-134, -140), 5) #bottom horizontal line l33 = pymunk.Segment(body, (-163, -112), (-163, -185), 5) #left side vertical line l34 = pymunk.Segment(body, (-134, -140), (-134, -185), 5) #right side vertical line space.add(l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12, l13, l14, l15, l16, l17, l18, l19, l20, l21, l22, l23, l24, l25, l26, l27, l28, l29, l30, l31, l32, l33, l34) # 3 return (l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12,l13,l14,l15,l16, l17,l18,l19,l20,l21,l22,l23,l24,l25,l26,l27,l28,l29,l30, l31,l32,l33,l34)
720, "Softballs in the Gym Simulation", resizable=False) background = pyglet.image.load('Background.png') background_sprite = pyglet.sprite.Sprite(background) background_sprite.scale_y = 43 background_sprite.scale_x = 61 options = DrawOptions() glScalef(0.07, 0.07, 0.07) # Declare space to put bodies/shapes in, define gravity. space = pymunk.Space() space.gravity = 0, -7000 # Make gym base segment_shape_base = pymunk.Segment(space.static_body, (0, 0), (W, 0), 50) segment_shape_base.color = (118, 82, 19, 0.69) segment_shape_base.body.position = Bottom_Left_Corner segment_shape_base.elasticity = bounce segment_shape_base.friction = 1.0 # Make gym left wall segment_shape_left = pymunk.Segment(space.static_body, (0, H), (0, 0), 50) segment_shape_left.color = (118, 82, 19, 0.69) segment_shape_left.body.position = Bottom_Left_Corner segment_shape_left.elasticity = bounce segment_shape_left.friction = 1.0 # Make gym right wall segment_body_right = pymunk.Body(body_type=pymunk.Body.STATIC) segment_body_right.position = Bottom_Right_Corner
pygame.init() screen = pygame.display.set_mode((600, 600)) clock = pygame.time.Clock() running = True ### Physics stuff space = pymunk.Space() space.gravity = (0.0, -900.0) draw_options = pymunk.pygame_util.DrawOptions(screen) ## Balls balls = [] ### walls static_lines = [ pymunk.Segment(space.static_body, (150, 100.0), (50.0, 550.0), 1.0), pymunk.Segment(space.static_body, (450.0, 100.0), (550.0, 550.0), 1.0), pymunk.Segment(space.static_body, (50.0, 550.0), (300.0, 600.0), 1.0), pymunk.Segment(space.static_body, (300.0, 600.0), (550.0, 550.0), 1.0), pymunk.Segment(space.static_body, (300.0, 420.0), (400.0, 400.0), 1.0) ] for line in static_lines: line.elasticity = 0.7 line.group = 1 space.add(static_lines) fp = [(20, -20), (-120, 0), (20, 20)] mass = 100 moment = pymunk.moment_for_poly(mass, fp) # right flipper
def main(): # global contact # global shape_to_remove pygame.init() screen = pygame.display.set_mode((600, 600)) clock = pygame.time.Clock() running = True # physics space = pm.Space() space.gravity = (0.0, 900.0) balls = [] static_body = pm.Body(body_type=pm.Body.STATIC) static_lines = [ pm.Segment(static_body, (111.0, 320.0), (407.0, 354.0), 0.0), pm.Segment(static_body, (407.0, 354.0), (407.0, 257.0), 0.0) ] space.add(static_lines) ticks_to_next_ball = 10 ch = space.add_collision_handler(0, 0) ch.data['surface'] = screen ch.post_solve = draw_collision while running: for event in pygame.event.get(): if event.type == QUIT: running = False elif event.type == KEYDOWN and event.key == K_ESCAPE: running = False elif event.type == KEYDOWN and event.key == K_p: pygame.image.save(screen, 'contact_and_no_flipy.png') ticks_to_next_ball -= 1 if ticks_to_next_ball <= 0: ticks_to_next_ball = 100 mass = 10 radius = 25 inertia = pm.moment_for_circle(mass, 0, radius, (0, 0)) body = pm.Body(mass, inertia) x = random.randint(115, 350) body.position = x, 200 shape = pm.Circle(body, radius, (0, 0)) space.add(body, shape) balls.append(shape) screen.fill(THECOLORS['white']) # draw stuff balls_to_remove = [] for ball in balls: if ball.body.position.y > 400: balls_to_remove.append(ball) p = tuple(map(int, ball.body.position)) pygame.draw.circle(screen, THECOLORS['blue'], p, int(ball.radius), 2) for ball in balls_to_remove: space.remove(ball, ball.body) balls.remove(ball) for line in static_lines: body = line.body p1 = body.position + line.a.rotated(body.angle) p2 = body.position + line.b.rotated(body.angle) pygame.draw.lines(screen, THECOLORS['lightgray'], False, [p1, p2]) dt = 1.0 / 60.0 for x in range(1): space.step(dt) pygame.display.flip() clock.tick() pygame.display.set_caption('fps: ' + str(clock.get_fps()))
def main(): # Start up the game pygame.init() screen: Surface = pygame.display.set_mode((width, height)) clock = pygame.time.Clock() running = True space = pymunk.Space() # This gravity would be if we wanted to have every object move in one direction, not towards each other space.gravity = (0, 0) # Allow pymunk to draw to pygame screen draw_options = pygame_util.DrawOptions(screen) # Sound to play when planets collide global click_sound click_sound = pygame.mixer.Sound('resources/click.ogg') # Initialize physical objects --------------------------------------------------------------------------- # Ball ball_body = pymunk.Body(mass=1000, moment=pymunk.moment_for_circle( 1000, 0, marble_img.get_width() / 2)) ball_shape = pymunk.Circle(ball_body, marble_img.get_width() / 2) ball_shape.friction = 0.5 ball_shape.elasticity = .9 ball_shape.collision_type = BALL ball_shape.color = color.THECOLORS['coral'] # add ball to the scene space.add(ball_shape) space.add(ball_body) # Planets planets = [] for i in range(num_planets): size = random.randint(10, 15) planet_body, planet_shape = create_planet( space, size, math.pi * size**2, (random.randint(15, screen.get_width() - 15), random.randint(15, screen.get_height() - 15))) space.add(planet_shape) space.add(planet_body) planets.append(planet_body) # Set gravitational constant for planets - more planets means lower starting constant grav_const = 200 / num_planets gravity_enabled = False # Set up collision sounds between planets (see planet_collision) # handler = space.add_collision_handler(PLANET, PLANET) # handler.post_solve = planet_collision # Walls walls = [ pymunk.Segment(space.static_body, (0, 0), (0, screen.get_width()), 2), pymunk.Segment(space.static_body, (0, screen.get_width()), (screen.get_height(), screen.get_width()), 2), pymunk.Segment(space.static_body, (screen.get_height(), screen.get_width()), (screen.get_height(), 0), 2), pymunk.Segment(space.static_body, (screen.get_height(), 0), (0, 0), 2), ] for wall in walls: wall.friction = 0.1 wall.elasticity = 0.999 space.add(walls) music_started = True pygame.mixer.music.load('resources/moon.ogg') pygame.mixer.music.play(-1, 0.0) ball_body.position = (300, 400) # Main game loop ---------------------------------------------------------------------------------------- while running: # Event handling for event in pygame.event.get(): if event.type == QUIT or \ event.type == KEYDOWN and (event.key in [K_ESCAPE, K_q]): running = False if event.type == MOUSEBUTTONDOWN and event.button == 1: print(pygame.mouse.get_pos()) if not music_started: # Background Music pygame.mixer.music.load('resources/moon.ogg') pygame.mixer.music.play(-1, 0.0) music_started = True mouse_position = pymunk.pygame_util.from_pygame( Vec2d(pygame.mouse.get_pos()), screen) mouse_angle = (mouse_position - ball_body.position).angle impulse = ball_body.mass * 1000 * Vec2d(1, 0) impulse.rotate(mouse_angle) ball_body.apply_impulse_at_world_point(impulse, ball_body.position) if event.type == KEYDOWN: # If up or down is pressed, change the gravitational constant by a factor of 10 if event.key == K_UP: grav_const *= 1.5 print("Gravity:", grav_const) if event.key == K_DOWN: print("Gravity:", grav_const) grav_const /= 1.5 # Enable / Disable gravity with space if event.key == K_SPACE: gravity_enabled = not gravity_enabled if gravity_enabled: for i, planet_1 in enumerate(planets): # run_gravity(planet_1, ball_body, grav_const) for planet_2 in planets[i + 1:]: run_gravity(planet_1, planet_2, grav_const) # Graphics --------------------------------------------------------------------------- # Clear Screen screen.fill(pygame.color.THECOLORS['black']) # Use pygame interactivity to draw pymunk stuff space.debug_draw(draw_options) # Draw the rest of the stuff # screen.blit(pygame.transform.rotate(marble_img, ball_body.rotation_vector.angle_degrees), (ball_body.position[0] - ball_shape.radius, screen.get_height() - ball_body.position[1] - ball_shape.radius)) font = pygame.font.SysFont("Arial", 13) # pygame.draw.rect(screen, color.THECOLORS['gray'], Rect(0, 0, 260, 60), 0) screen.blit( font.render( "Click anywhere to fire the red ball towards the mouse", 1, color.THECOLORS["white"]), (5, 5)) screen.blit( font.render( "Press up or down to change the strength of gravity, space to enable/disable", 1, color.THECOLORS["white"]), (5, 20)) screen.blit( font.render("Gravitational Strength:", 1, color.THECOLORS["white"]), (5, 40)) screen.blit( font.render(str(round(grav_const, 3)), 1, color.THECOLORS["yellow"]), (115, 40)) gravity_color, gravity_text = (color.THECOLORS['green'], 'Enabled') if gravity_enabled else ( color.THECOLORS['red'], 'Disabled') screen.blit(font.render("Gravity:", 1, color.THECOLORS["white"]), (5, 55)) screen.blit(font.render(gravity_text, 1, gravity_color), (45, 55)) # Update the screen pygame.display.flip() # Update physics and pygame clock fps = 60 dt = 1. / fps space.step(dt) clock.tick(fps)