def __init__(self, first_level="test", reset_save=False): if util.settings.fullscreen: super(AerthianWindow,self).__init__(fullscreen=True, vsync=True) else: super(AerthianWindow,self).__init__(width=gamestate.norm_w, height=gamestate.norm_h, vsync=False) self.set_caption(gamestate.name) pyglet.gl.glEnable(pyglet.gl.GL_BLEND) pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA, pyglet.gl.GL_ONE_MINUS_SRC_ALPHA) pyglet.gl.glEnable(pyglet.gl.GL_LINE_SMOOTH) pymunk.init_pymunk() if reset_save: try: shutil.rmtree(os.path.join(gamestate.save_path, "autosave")) except OSError: pass # Directory didn't exist but we don't care gamestate.main_window = self # Make main window accessible to others. # Necessary for convenient event juggling. gamestate.init_scale() # Set up scaling transformations to have # a consistent window size self.scene_handler = scenehandler.SceneHandler(first_level) self.fps_display = pyglet.clock.ClockDisplay() # Schedule drawing and update functions. # Draw really only needs 60 FPS, update can be faster. pyglet.clock.schedule_interval(self.on_draw, 1/72.0) pyglet.clock.schedule_interval(self.scene_handler.update, 1/72.0)
def main(): pymunk.init_pymunk() space = pymunk.Space() space.gravity = (0.0, -900.0) ball = add_ball(space) print(ball.x) running = True while running: screen.fill(THECOLORS['white']) screen.blit(image,[0,0]) for event in pygame.event.get(): if event.type == QUIT: running = False elif event.type == KEYDOWN and event.key == K_ESCAPE: running = False lines = add_static_L(space) lines.eleasticity = .95 draw_lines(screen, lines) draw_ball(screen, ball) dt = 1.0/60.0 for x in range(1): space.step(dt) pygame.display.flip() clock.tick(50)
def __init__(self, demo=False, start_level=state.start_level): super(GameLayer,self).__init__() self.schedule( self.step ) self.demo_mode = demo state.set_level( start_level ) self.level = state.level pm.init_pymunk() self.space = pm.Space( iterations=10) self.space.gravity = self.level.gravity self.space.damping = 0.8 self.chain = [] self.goals = [] self.add_segments() self.add_balls() if not self.demo_mode: self.add_goal() self.space.add_collisionpair_func( COLL_TYPE_TAIL, COLL_TYPE_GOAL, self.collision_tail_goal, None) self.space.add_collisionpair_func( COLL_TYPE_HEAD, COLL_TYPE_GOAL, self.collision_head_goal, None)
def __init__(self): self.actor = None self.actors = [] # Setup PyGame pygame.init() self.screen = pygame.display.set_mode((300, 400)) self.clock = pygame.time.Clock() # Setup PyMunk pymunk.init_pymunk() self.space = pymunk.Space(50, 50) self.space.gravity = (0.0, -900.0) self.space.resize_static_hash() self.space.resize_active_hash() # Set the stage def wall_height(pos_x): """ Function to define our wall """ if pos_x <= 10: return 400 elif pos_x >= 210: return 400 else: pos_x = pos_x - 110 return 110 - math.cos(math.asin(pos_x / 100.0)) * 100.0 self.actors.append( Wall(self.space, (0.0, 0.0), 300, wall_height, mass=pymunk.inf)) self.spawn() self.space.set_default_collision_handler(self.collision, None, None, None)
def init_physics(self): pm.init_pymunk() self.space = pm.Space() #3 self.space.gravity = (0.0, 300.0) self.space.resize_static_hash() self.space.resize_active_hash() # collisions between different colors self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_RED, gameobject.OBJECT_TYPE_GREEN, None) #self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_GREEN, gameobject.OBJECT_TYPE_RED, None) self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_GREEN, gameobject.OBJECT_TYPE_BLUE, None) #self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_BLUE, gameobject.OBJECT_TYPE_GREEN, None) self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_RED, gameobject.OBJECT_TYPE_BLUE, None) #self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_BLUE, gameobject.OBJECT_TYPE_RED, None) # key collisions self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_PLAYER, gameobject.OBJECT_TYPE_KEY_RED, self.handle_key_collisions, self.screen) self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_PLAYER, gameobject.OBJECT_TYPE_KEY_GREEN, self.handle_key_collisions, self.screen) self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_PLAYER, gameobject.OBJECT_TYPE_KEY_BLUE, self.handle_key_collisions, self.screen) # win collisions self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_PLAYER, gameobject.OBJECT_TYPE_GOAL, self.handle_win_collisions, self.screen) # info collisions self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_PLAYER, gameobject.OBJECT_TYPE_INFO, self.handle_info_collisions, self.screen) # collisions between self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_PLAYER, gameobject.OBJECT_TYPE_RED, self.handle_collision, self.screen) self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_PLAYER, gameobject.OBJECT_TYPE_GREEN, self.handle_collision, self.screen) self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_PLAYER, gameobject.OBJECT_TYPE_BLUE, self.handle_collision, self.screen) self.space.add_collisionpair_func(gameobject.OBJECT_TYPE_PLAYER, gameobject.OBJECT_TYPE_BW, self.handle_collision, self.screen)
def __init__(self, gravity=(0.0,-900.0)): """ Init function: init pymunk, get screen size, init space, ... Parameter: gravity == (int(x), int(y)) Returns: pymunx() """ self.run_physics = True self.gravity = gravity # Python Stuff self.font = pygame.font.Font(None, 32) self.font_xxl = pygame.font.Font(None, 38) # Physics Init pm.init_pymunk() # Init Colors self.init_colors() # This string will be blit in the top left corner at each update self.set_info("") # Get Screen Size self.autoset_screen_size() # Space Init self.space = pm.Space() self.space.gravity = Vec2d(gravity) self.space._space.contents.elasticIterations = 10 self.space.resize_static_hash() self.space.resize_active_hash()
def __init__(self): import pymunk pymunk.init_pymunk() self.window = GameWindow(game=self) self.controlling = None self.current_level = levels.Fun(game=self) pyglet.clock.schedule_interval(self.update, 1/60.)
def __init__(self): self.items = [] self.words = [] self.springs = [] init_pymunk() self.space = Space() self.space.resize_static_hash() self.space.resize_active_hash()
def __init__(self, *args, **kwargs): pyglet.window.Window.__init__(self, *args, **kwargs) self.keys = key.KeyStateHandler() self.push_handlers(self.keys) pymunk.init_pymunk() self.space = pymunk.Space() self.space.gravity = (0.0, -800.0) self.lines = add_static_L(self.space) self.boxes = []
def __init__(self): self.items = [] init_pymunk() self.space = Space() self.space.gravity = (0, -0.5) self.space.resize_static_hash() self.space.resize_active_hash() self.leaves = [] self.end_game = False
def init_pymunk(self): """ setup our space """ pm.init_pymunk() pm.reset_shapeid_counter() self.space = pm.Space() if self.gravity: self.space.gravity = pm.Vec2d(self.gravity) self.space.resize_static_hash(100, 2000) self.space.resize_active_hash(100, 2000)
def reset(self): # we need to reset the lists and flags self.balls = [] self.pads = [] self.lines = [] self.ball_position_lookup = {} pm.init_pymunk() pm.reset_shapeid_counter() self.__init__()
def __init__(self, callback=None, physics=False): pm.init_pymunk() self._space = pm.Space() # for now, we just use a single generic collision handler self._space.set_default_collisionpair_func(self._on_collide) self._active_objects = {} self._static_objects = {} # this is the callback we call when a collision has happened self.callback = callback self.physics = physics
def setup(name, width, height, flags=pygame.DOUBLEBUF): pygame.init() pygame.display.gl_set_attribute(pygame.GL_STENCIL_SIZE, 2) screen = pygame.display.set_mode((width, height), pygame.OPENGL | flags) pygame.display.set_caption(name) VG.create_context((width, height)) VG.set(VG_CLEAR_COLOR, (1.0, 1.0, 1.0, 1.0)) pm.init_pymunk() return screen
def __init__(self, *args, **kwargs): """ Initializes the physics engine and the PhysicsService. """ pymunk.init_pymunk() self.space = pymunk.Space() self.physical_objects = [] self.bounds = kwargs.get('bounds', None) self.space.set_default_collision_handler(self.on_collision, None, None, None) # prepare the debug drawing of a sphere self.debug_draw = False
def clear(self): """ Clear & Reset the Physic Space (Remove all Elements) """ pm.init_pymunk() # Space Init self.space = pm.Space() self.space.gravity = Vec2d(self.gravity) self.space.resize_static_hash() self.space.resize_active_hash() self.element_count = 0 self.filecounter = 0
def __init__(self, **kwargs): super(LTWorld, self).__init__(**kwargs) self.size = getWindow().size try: pm.init_pymunk() except: pass self.space = pm.Space() self.space.gravity = (0., 0.) #self.space.resize_static_hash() #self.space.resize_active_hash() getClock().schedule_interval(self.update_world, 1. / 60)
def main(): pygame.init() screen = pygame.display.set_mode((600, 600)) pygame.display.set_caption("Joints. Just wait and the L will tip over") clock = pygame.time.Clock() running = True pymunk.init_pymunk() space = pymunk.Space() space.gravity = (0.0, -900.0) space.add_collision_handler(2, 2, collision, None, None, None) lines = add_L(space) balls = [] ticks_to_next_ball = 10 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 ticks_to_next_ball -= 1 if ticks_to_next_ball <= 0: ticks_to_next_ball = 25 ball_shape = add_ball(space) balls.append(ball_shape) screen.fill(THECOLORS["white"]) balls_to_remove = [] for ball in balls: if ball.body.position.y < 150: balls_to_remove.append(ball) draw_ball(screen, ball) for ball in balls_to_remove: space.remove(ball, ball.body) balls.remove(ball) draw_lines(screen, lines) pygame.draw.circle(screen, THECOLORS["red"], (300, 300), 5) pygame.draw.circle(screen, THECOLORS["green"], (200, 300), 25, 2) space.step(1 / 50.0) pygame.display.flip() clock.tick(50)
def __init__(self): super(HelloWorldWindow, self).__init__() pm.init_pymunk() self.space = world.World() self.tilebatch = pyglet.graphics.Batch() self.textures = {"dirt.gif":pyglet.image.load('../img/dirt.gif'), "smilie-small.gif":pyglet.image.load('../img/smilie-small.gif')} #load level #level_tiles = [{'x': x, 'y' : 1, 'texture': 'dirt.gif'} for x in range(1,30)] level_tiles = self.load_level('blarf') tile_renderer = renderers.TileRenderer(self.textures, level_tiles, camera) level = entity.Terrain(level_tiles=level_tiles,renderer = tile_renderer) self.space.addStaticEntity(level) self.mouse_body = pm.Body(pm.inf, pm.inf) self.mouse_shape = pm.Circle(self.mouse_body, 3, Vec2d(0,0)) self.mouse_shape.sensor = True self.mouse_shape.collision_type = MOUSE_COLLTYPE self.space.add(self.mouse_shape) self.line_point1 = None self.line_point2 = None self.run = True self.keyboard = key.KeyStateHandler() self.push_handlers(self.keyboard) self.input_manager = inputmanager.KeyboardManager() self.keyboard_agent = agent.KeyboardAgent(self.input_manager) self.fps = 60 pyglet.clock.schedule_interval(self.update, 1.0/self.fps) pyglet.clock.schedule_interval(self.update_keys, 1.0/self.fps) pyglet.clock.set_fps_limit(self.fps*2) self.fps_display = pyglet.clock.ClockDisplay() self.ball_spawn_point = (50, 300) self.ball = entity.Ball(self.ball_spawn_point, 10, 10, 100, .5, agent=self.keyboard_agent,renderer = circle_renderer) #self.evilcat = entity.EvilCat((evilcat_renderer.cat_sprite.x, evilcat_renderer.cat_sprite.y), 64, 64, renderer=evilcat_renderer) #self.evilcat = entity.EvilCatSquare((evilcat_renderer.cat_sprite.x, evilcat_renderer.cat_sprite.y), 32, renderer=evilcat_renderer) self.evilcat = entity.RespawnSquare((evilcat_renderer.cat_sprite.x, evilcat_renderer.cat_sprite.y), 32, renderer=evilcat_renderer) self.space.addEntity(self.ball) #self.space.addEntity(self.evilcat) self.space.addStaticEntity(self.evilcat) self.hud_manager = hud.HudManager() #music = pyglet.resource.media('music.mp3') #music.play self.space.add_collision_handler(PLAYER_COLLTYPE, RESPAWN_COLLTYPE, self.respawnCallBack, None, None, None, player_entity=self.ball)
def __init__(self): # pylint: disable-msg=W0212 # Access to a protected member '_space': ack init_pymunk() self.space = Space() self.space.gravity = (0, 0) self.space._space.contents.elasticIterations = 10 self.static_body = Body(inf, inf) self.rooms = {} self.ents = set() self.chunks = set() self.player = None self.material = granite
def __init__(self, **kwargs): kwargs.setdefault('do_scale', False) kwargs.setdefault('do_rotation', False) super(MusicPlane, self).__init__(**kwargs) self.dt = 0 self.delete_queue = [] self.pads = [] # initialize physics pymunk.init_pymunk() space = pymunk.Space() #space.gravity = (0.0, -900.0) space.gravity = (0.0, 0.0) space.set_default_collision_handler(self.collide_found, None, None, None) self.space = space
def __init__(self, **kwargs): super(CircleVisualisation, self).__init__(**kwargs) self.fg_color = (1.0, 1.0, 1.0) pm.init_pymunk() self.space = pm.Space() self.space.gravity = (0.0, 900.0) self.lines = [] for j in xrange(0,5): for i in xrange(0,10): x1 = -200 + i * 80 y1 = j * 100 x2 = x1 + random.randint(-60,60) y2 = y1 + random.randint(-60,60) self.lines.append(add_static_L(self.space, x1, y1, x2, y2)) self.balls = [] self.off = False
def __init__(self): self.frame = 0; pygame.init() self.clock = pygame.time.Clock() pymunk.init_pymunk() self.space = pymunk.Space() self.space.gravity = (0.0, GRAVITITY) info = pygame.display.Info() self.screen_width, self.screen_height = info.current_w, info.current_h self.grid_width = info.current_w / ICON_WIDTH + 1 self.grid_height = info.current_h / ICON_HEIGHT + 1 self.drop_height = self.screen_height + 1000 # turn into fullscreen mode self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) pygame.mouse.set_visible(False) self.font = pygame.font.Font(None, 17) # load icons self._load_files() self._load_sprites() self.sprite_bucket = self.sprites[:] self.sprites_on_ground = 0 self.cols = [] self.sprite_cols = [] for i in range(self.grid_width): self.sprite_cols.append([]) # create a ground GROUND_LEVEL = 0.0 self.ground_body = pymunk.Body(pymunk.inf, pymunk.inf) self.ground_body.position = Vec2d(0.0, GROUND_LEVEL) self.ground_shape = pymunk.Segment(self.ground_body, Vec2d(-10000.0, GROUND_LEVEL), Vec2d(10000.0, GROUND_LEVEL), 1.0) for i in range(self.grid_width + 1): body = pymunk.Body(pymunk.inf, pymunk.inf) line = pymunk.Segment(body, Vec2d(i * ICON_WIDTH, GROUND_LEVEL), Vec2d(i * ICON_WIDTH, GROUND_LEVEL + 10000.0), 0.0) self.space.add_static(line) self._init_drop()
def init_content(self): # load turret images, set rotational anchors, store for later pymunk.init_pymunk() self.space = pymunk.Space() self.space.gravity = (0, 0) # This bit of code makes the balls pass through the gravity wells. # There are more efficient ways of doing this but I was experimenting # with collision handlers. def begin(space, arbiter): return False self.space.add_collision_handler(GRAVITY_TYPE, BALL_TYPE, begin, None, None, None) ball = load_and_anchor('ball.png', 2, 2) self.images['ball'] = ball frame = load_and_anchor('blueturret_00.png', 2, 2) self.images['frame'] = frame barrel = load_and_anchor('bluebarrel_00.png', 2, 4) self.images['barrel'] = barrel cathead = load_and_anchor('cathead.png', 2, 3) self.images['cathead'] = cathead catbody = load_and_anchor('catbody.png', 2, 2) self.images['catbody'] = catbody gravity = load_and_anchor('gravity.png', 2, 2) self.images['gravity'] = gravity x = load_and_anchor('x.png', 2, 2) self.images['x'] = x trail = load_and_anchor('trail.png', 2, 2) self.images['trail'] = trail powerbar = load_and_anchor('powerbar.png', 2, 2) self.images['powerbar'] = powerbar
def __init__(self): if util.settings.fullscreen: super(GameWindow,self).__init__(fullscreen=True, vsync=True) else: super(GameWindow,self).__init__(width=gamestate.norm_w, height=gamestate.norm_h, vsync=True) self.set_caption(gamestate.name) pyglet.gl.glEnable(pyglet.gl.GL_BLEND) pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA, pyglet.gl.GL_ONE_MINUS_SRC_ALPHA) pyglet.gl.glEnable(pyglet.gl.GL_LINE_SMOOTH) pymunk.init_pymunk() gamestate.main_window = self # Make main window accessible to others. # Necessary for convenient event juggling. gamestate.init_scale() # Set up scaling transformations to have # a consistent window size gamestate.keys = pyglet.window.key.KeyStateHandler() self.push_handlers(gamestate.keys) self.scene_handler = scenehandler.SceneHandler() fs = imagescene.ImageScene(self.scene_handler) self.scene_handler.set_first_scene(fs) pyglet.gl.glClearColor(0.5, 0.3, 0.255, 1.0) self.scene_draw = self.scene_handler.draw self.fps_display = pyglet.clock.ClockDisplay() # Schedule drawing and update functions. # Draw really only needs 60 FPS, update can be faster. pyglet.clock.schedule_interval(self.on_draw, 1/72.0) pyglet.clock.schedule_interval(self.scene_handler.update, 1/72.0) music = False if music: gamestate.dj = pyglet.media.Player() gamestate.dj.eos_action = 'loop' gamestate.dj.queue(pyglet.resource.media('game/music.wav', streaming=True)) gamestate.dj.play()
def __init(): #PYGAME INIT pygame.init() pygame.font.init() os.environ['SDL_VIDEO_CENTERED'] = '1' #Center Window #PYMUNK INIT pymunk.init_pymunk() cfg.space = pymunk.Space() cfg.space.gravity = (0, 300) #default gravity cfg.space.damping = .2 #WINDOW cfg.window = pygame.display.set_mode((840, 525)) #Window Size cfg.window.fill((0,0,0)) pygame.display.set_caption("Derpy Delivery!") #Window Caption pygame.mouse.set_visible(0) #Mouse Off #CLOCK cfg.clock = pygame.time.Clock() #IMAGE HANDLER cfg.imgH = handle.img.handler() #SOUND HANDLER cfg.sndH = handle.snd.handler() #KEYBOARD HANDLER cfg.keyH = handle.key.handler() #OBJECT HANDLER cfg.objH = handle.obj.handler() #ROOM HANDLER cfg.rmH = handle.room.handler()
def __init(): #PYGAME INIT pygame.init() pygame.font.init() os.environ['SDL_VIDEO_CENTERED'] = '1' #Center Window #PYMUNK INIT pymunk.init_pymunk() cfg.space = pymunk.Space() cfg.space.gravity = (0, 300) #default gravity cfg.space.damping = .2 #WINDOW cfg.window = pygame.display.set_mode((840, 525)) #Window Size cfg.window.fill((0, 0, 0)) pygame.display.set_caption("Derpy Delivery!") #Window Caption pygame.mouse.set_visible(0) #Mouse Off #CLOCK cfg.clock = pygame.time.Clock() #IMAGE HANDLER cfg.imgH = handle.img.handler() #SOUND HANDLER cfg.sndH = handle.snd.handler() #KEYBOARD HANDLER cfg.keyH = handle.key.handler() #OBJECT HANDLER cfg.objH = handle.obj.handler() #ROOM HANDLER cfg.rmH = handle.room.handler()
def init(step=5, run=True, grav=(0.0,0.0)): global frame_time, dt_backlog, run_physics, gravity, space global static_body, bodies, body_update_list, doors global unit_update_list, bullet_deletion_queue global update_bodies_now frame_time = 1.0/60.0/step dt_backlog = 0.0 run_physics = run update_bodies_now = False gravity = grav pymunk.init_pymunk() space = pymunk.Space() space._space.contents.elasticIterations = 5 space.gravity = Vec2d(grav) #space.resize_static_hash() #space.resize_active_hash() static_body = pymunk.Body(pymunk.inf, pymunk.inf) body_update_list = [] unit_update_list = [] doors = [] bullet_deletion_queue = []
def init(self): init_pymunk() self.space = Space() self.space.gravity = (0, -0.002) self.space.resize_static_hash() self.space.resize_active_hash()
def main(): # Variables that need to be initialized pygame.init() screen = pygame.display.set_mode((800, 600)) clock = pygame.time.Clock() running = True selection = 1 background_play = load_image("play.png") background_sandbox = load_image("sandbox.png") background_help = load_image("help.png") background_quit = load_image("quit.png") screen.blit(background_play, (0, 0)) pymunk.init_pymunk() space = pymunk.Space() space.gravity = (0.0, -400.0) next_shape = 0 display_help = False winner = False cur_help = 0 score = 0 font = pygame.font.Font(None, 60) """ Music by Rudy Vessup Song name : .:: jUsT dO it::. Downloaded from: http://www.flashkit.com/loops/Sales/Techno_breed/_jUsT-Rudy_Ves-8003/index.php""" music = sandbox.load_sound("main_menu.wav") music.play(-1) # Keep track of balls, triangles and boxes balls = [] triangles = [] boxes = [] # Load the main menu help pictures help_menu = [] for n in range(1, 9): img = load_image("help" + str(n) + ".png") help_menu.append(img) congrats = load_image("congrats.png") # Lines that correspond to the main menu for objects colliding with words sandbox.line(space, 193, 415, 337, 415) sandbox.line(space, 270, 320, 528, 320) sandbox.line(space, 442, 134, 582, 134) # Start the running loop while running: screen.fill(THECOLORS["white"]) pygame.display.set_caption("Welcome to SandBox!") # Capture events for event in pygame.event.get(): if event.type == QUIT: running = False if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False if event.key == K_UP: selection -= 1 if event.key == K_DOWN: selection += 1 if event.key == K_RIGHT: if display_help: cur_help += 1 if event.key == K_LEFT: if display_help: cur_help -= 1 # Click or hit enter on selection to start it if event.type == MOUSEBUTTONDOWN and event.button == 1 or event.type == KEYDOWN and event.key == K_RETURN: if not display_help: if not winner: if selection == 1: music.fadeout(1000) score = sandbox.main() winner = True music.play(-1) elif selection == 2: music.fadeout(1000) sandbox.sandbox() music.play(-1) elif selection == 3: display_help = True elif selection == 4: running = False else: # Close score screen winner = False score = 0 # Progress through the help menu if event.type == MOUSEBUTTONDOWN and event.button == 1: if display_help: x, y = pygame.mouse.get_pos() if x > 115 and x < 180 and y > 465 and y < 500: cur_help -= 1 elif x > 620 and x < 685 and y > 465 and y < 500: cur_help += 1 if selection == 0: selection = 4 elif selection == 5: selection = 1 # Use mouse location to select menu items x, y = pygame.mouse.get_pos() if not winner: if x > 193 and x < 337 and y > 170 and y < 240: selection = 1 if x > 270 and x < 528 and y > 262 and y < 343: selection = 2 if x > 356 and x < 510 and y > 366 and y < 430: selection = 3 if x > 442 and x < 582 and y > 463 and y < 515: selection = 4 # Start shapes falling, and add more when next_shape == 30 if next_shape == 30: x = random.randint(100, 700) s = random.randint(10, 30) b = sandbox.add_ball(space, s, x, -100) balls.append(b) x = random.randint(100, 700) s = random.randint(10, 50) t = sandbox.add_triangle(space, s, x, -200) t.friction = 0.0 triangles.append(t) x = random.randint(100, 700) s = random.randint(10, 50) s2 = random.randint(10, 50) r = sandbox.add_box(space, s, s2, x, -150) r.friction = 0.0 boxes.append(r) next_shape = 0 else: next_shape += 1 # Remove the objects when they get to a certain point (y == -100), otherwise # game slows to a crawl for ball in balls: if ball.body.position.y < -100: space.remove(ball, ball.body) balls.remove(ball) else: sandbox.draw_ball(screen, ball) for box in boxes: if box.body.position.y < -100: space.remove(box, box.body) boxes.remove(box) else: sandbox.draw_poly(screen, box, THECOLORS["red"]) for tri in triangles: if tri.body.position.y < -100: space.remove(tri, tri.body) triangles.remove(tri) else: sandbox.draw_poly(screen, tri, THECOLORS["green"]) # Show the correct picture for what is being selected if not winner: if selection == 1: screen.blit(background_play, (0, 0)) elif selection == 2: screen.blit(background_sandbox, (0, 0)) elif selection == 3: screen.blit(background_help, (0, 0)) elif selection == 4: screen.blit(background_quit, (0, 0)) # Show score after playing the game text = font.render(str(score), 20, THECOLORS["black"]) if winner: screen.blit(congrats, (0, 0)) screen.blit(text, (400, 300)) # Show help menu if display_help == True: if cur_help >= 0 and cur_help <= 7: screen.blit(help_menu[cur_help], (0, 0)) else: display_help = False cur_help = 0 space.step(1 / 60.0) clock.tick(60) pygame.display.flip() pygame.quit()
r = random.uniform(-0.2, 0.2) elif evt.keysym == 'Right': l = random.uniform(-0.2, 0.2) r = random.uniform(0.7, 1.0) elif evt.keysym == 'Up': l = random.uniform(0.7, 1.0) r = random.uniform(0.7, 1.0) elif evt.keysym == 'Down': l = -random.uniform(0.7, 1.0) r = -random.uniform(0.7, 1.0) else: return self.world.update({'left' : l, 'right' : r}) def update_obj(self, name, pos, verts, color): p = (pos[0] * Display.SCALE, pos[1] * Display.SCALE) if name in self.objs: poly, oldpos = self.objs[name] self.canvas.delete(poly) self.canvas.create_line(oldpos, p, fill=color) sverts = [ (x * Display.SCALE, y * Display.SCALE) for x, y in verts ] poly = self.canvas.create_polygon(sverts, fill='', outline=color) self.objs[name] = (poly, p) if __name__ == '__main__': munk.init_pymunk() disp = Display() tk.mainloop()
def init_physics(self): pymunk.init_pymunk() self.space = pymunk.Space() self.space.gravity = (0,0)
# # Number of channels of audio - pygame default is 8 but # it looks like this can easily be reached and causes # some sounds to cut out. The following number is large # enough to avoid that. NUM_AUDIO_CHANNELS = 32 # # Look for Pymunk try: import pymunk # # Looks like the following is not needed on pymunk 2.1 if hasattr(pymunk, 'init_pymunk'): pymunk.init_pymunk() PYMUNK_OK = True except ImportError: import simplevecs as pymunk PYMUNK_OK = False # The following needed for pygame and py2exe try: import pygame._view except ImportError: pass DETAIL = 5 class Filtering(logging.Filter): """A nice filtering formatter than can show certain types of log"""
def sandbox(): # Variables that need to be initialized pygame.init() screen = pygame.display.set_mode((800, 600)) clock = pygame.time.Clock() running = True pygame.key.set_repeat(400, 10) mouse_old = to_pygame2(0, 0) mouse_new = to_pygame2(0, 0) pymunk.init_pymunk() space = pymunk.Space() gravity_x = 0.0 gravity_y = -400.0 space.gravity = (0.0, -400.0) run_physics = True current_level = 1 width = 20 height = 20 font = pygame.font.Font(None, 16) # Lists to keep track of all objects balls = [] balls_remove = [] boxes = [] boxes_remove = [] triangles = [] tri_remove = [] lines = [] outer_lines = [] finishball = [] # Keeps track of making new lines with mouse second = False """ Music by calpomatt (Author's name not given) Song name: Searching For Truth - Solo Downloaded from: http://www.flashkit.com/loops/Ambient/Ambient/SFT-calpomat-4638/index.php""" music = load_sound("sandbox.wav") music.play(-1) #Outer lines must be different than regular lines, # otherwise they can be deleted l = line(space, 0, 0, 800, 0) outer_lines.append(l) l = line(space, 0, 0, 0, 600) outer_lines.append(l) l = line(space, 0, 600, 800, 600) outer_lines.append(l) l = line(space, 800, 600, 800, 0) outer_lines.append(l) finish = load_level(1, space, balls, boxes, triangles, lines, finishball, False) # Start the main running loop while running: # Keep track of mouse vector for adding impulse to objects mouse_old = mouse_new xx, yy = pygame.mouse.get_pos() mouse_new = to_pygame2(xx, yy) pygame.display.set_caption("Welcome to the Sandbox! Have fun!") # Get keyboard and mouse comands 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_SPACE: run_physics = not run_physics elif event.type == KEYDOWN: if event.key == K_b: ball = add_ball(space, width, xx, yy) balls.append(ball) if event.key == K_r: rect = add_box(space, width, height, xx, yy) boxes.append(rect) if event.key == K_t: tri = add_triangle(space, width, xx, yy) triangles.append(tri) if event.key == K_UP: if pygame.key.get_mods() & KMOD_SHIFT: height += 1 else: gravity_y += 1 space.gravity = (gravity_x, gravity_y) if event.key == K_DOWN: if pygame.key.get_mods() & KMOD_SHIFT: if height > 5: height -= 1 else: gravity_y -= 1 space.gravity = (gravity_x, gravity_y) if event.key == K_LEFT: if pygame.key.get_mods() & KMOD_SHIFT: if width > 5: width -= 1 else: gravity_x -= 1 space.gravity = (gravity_x, gravity_y) if event.key == K_RIGHT: if pygame.key.get_mods() & KMOD_SHIFT: width += 1 else: gravity_x += 1 space.gravity = (gravity_x, gravity_y) if event.key == K_DELETE or event.key == K_d: if pygame.key.get_mods() & KMOD_SHIFT: width = 20 height = 20 gravity_x = 0.0 gravity_y = -400.0 space.gravity = (0.0, -400.0) else: fake_lines = [] clear_lists(space, balls, boxes, triangles, fake_lines, finishball) elif event.type == KEYDOWN and event.key == K_c: for box in boxes: boxes.remove(box) num_shapes -= 1 for ball in balls_remove: space.remove(ball, ball.body) balls.remove(ball) num_shapes -= 1 elif event.type == MOUSEBUTTONDOWN and event.button == 1: if pygame.key.get_mods() & KMOD_SHIFT: if not second: x1, y1 = pygame.mouse.get_pos() x1, y1 = to_pygame2(x1, y1) second = True else: x2, y2 = pygame.mouse.get_pos() x2, y2 = to_pygame2(x2, y2) l = line(space, x1, y1, x2, y2) lines.append(l) second = False # Check if mouse is in an object, and if released after being picked up, # apply a force in the mouse vector direction if pygame.mouse.get_pressed()[0]: t, y = pygame.mouse.get_pos() x = to_pygame2(t, y) test = (Vec2d(mouse_new) - Vec2d(mouse_old)) for ball in balls: if ball.point_query(x): none = False ball.body.position = x ball.body.velocity = Vec2d(0, 0) ball.body.apply_impulse(40 * test) for ball in finishball: if ball.point_query(x): none = False ball.body.position = x ball.body.velocity = Vec2d(0, 0) ball.body.apply_impulse(40 * test) for box in boxes: if box.point_query(x): none = False box.body.position = x box.body.velocity = Vec2d(0, 0) box.body.apply_impulse(40 * test) for tri in triangles: if tri.point_query(x): none = False xx, yy = x tri.body.position = (xx, yy - 4) tri.body.velocity = Vec2d(0, 0) tri.body.apply_impulse(100 * test) # Delete items by right-clicking on them if pygame.mouse.get_pressed()[2]: x, y = pygame.mouse.get_pos() x = to_pygame2(x, y) test = (Vec2d(mouse_new) - Vec2d(mouse_old)) for ball in balls: if ball.point_query(x): space.remove(ball, ball.body) balls.remove(ball) for box in boxes: if box.point_query(x): space.remove(box, box.body) boxes.remove(box) for tri in triangles: if tri.point_query(x): space.remove(tri, tri.body) triangles.remove(tri) for l_line in lines: if l_line.point_query(x): space.remove_static(l_line) lines.remove(l_line) screen.fill(THECOLORS["white"]) # Draw objects to the screen for ball in balls: if ball.body.position.y < -100: balls_remove.append(ball) else: draw_ball(screen, ball) for box in boxes: if box.body.position.y < -100: boxes_remove.append(box) else: draw_poly(screen, box, THECOLORS["red"]) for tri in triangles: draw_poly(screen, tri, THECOLORS["green"]) for l in lines: draw_line(screen, l) # Draw the help text in the upper left text_left = [ "LMB: Grab object", "Shift + LMB: Click twice for new line", "RMB: Delete object", "Space: Change speed to slowmo", "B,R,T: Spawn ball, rect, triangle", "Del or D: Delete all objects from space (add shift to reset variables)", "Up/Down arrow: Change Y gravity]", "Left/Right arrow: Change X gravity", "Shift + Up/Down arrow: Change height", "Shift + Left/Right arrow: Change radius/width", "ESC: Return to main menu" ] y = 5 for t_line in text_left: text = font.render(t_line, 20, THECOLORS["black"]) screen.blit(text, (5, y)) y += 10 # Draw the variables in the uppper right text_right = [ "Gravity: " + str(gravity_x) + "," + str(gravity_y), "Radius/Width = " + str(width), "Height = " + str(height) ] y = 5 for t_line in text_right: text = font.render(t_line, 5, THECOLORS["black"]) screen.blit(text, (650, y)) y += 10 if run_physics: space.step(1 / 60.0) # regular speed else: space.step(1 / 480.0) # slow motion clock.tick(60) pygame.display.flip() music.fadeout(1000)
def main(): # Variables that need initializing pygame.init() screen = pygame.display.set_mode((800, 600)) clock = pygame.time.Clock() running = True pygame.key.set_repeat() mouse_old = to_pygame2(0, 0) mouse_new = to_pygame2(0, 0) pymunk.init_pymunk() #2 space = pymunk.Space() #3 space.gravity = (0.0, -400.0) run_physics = True current_level = 1 windistance = 5 max_level = 9 font = pygame.font.Font(None, 40) time = 0 tick_time = 0 score = 0 """ Music by calpomatt (Author's name not given) Song name: Searching For Truth Downloaded from: http://www.flashkit.com/loops/Ambient/Ambient/Searc-calpomat-4394/index.php""" music = load_sound("game.wav") music.play(-1) # Lists for objects balls = [] boxes = [] triangles = [] lines = [] finishball = [] # Start the first level finish = load_level(1, space, balls, boxes, triangles, lines, finishball, True) # Start main running loop while running: # Mouse vector mouse_old = mouse_new xx, yy = pygame.mouse.get_pos() mouse_new = to_pygame2(xx, yy) pygame.display.set_caption("Level " + str(current_level)) # Capturing mouse and keyboard events 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_SPACE: run_physics = not run_physics if score > 0: score -= 50 elif event.type == KEYDOWN and event.key == K_PAGEUP: if current_level < max_level: time_tick = 0 time = 0 current_level += 1 clear_lists(space, balls, boxes, triangles, lines, finishball) finish = load_level(current_level, space, balls, boxes, triangles, lines, finishball, True) elif event.type == KEYDOWN and event.key == K_PAGEDOWN: if current_level > 1: time_tick = 0 time = 0 current_level -= 1 clear_lists(space, balls, boxes, triangles, lines, finishball) finish = load_level(current_level, space, balls, boxes, triangles, lines, finishball, True) elif event.type == KEYDOWN and event.key == K_d: clear_lists(space, balls, boxes, triangles, lines, finishball) finish = load_level(current_level, space, balls, boxes, triangles, lines, finishball, True) elif event.type == KEYDOWN and event.key == K_c: for box in boxes: boxes.remove(box) num_shapes -= 1 for ball in balls_remove: space.remove(ball, ball.body) balls.remove(ball) num_shapes -= 1 # Check if mouse is in an object, and if released after being picked up, # apply a force in the mouse vector direction if pygame.mouse.get_pressed()[0]: x, y = pygame.mouse.get_pos() x = to_pygame2(x, y) test = (Vec2d(mouse_new) - Vec2d(mouse_old)) for ball in balls: if ball.point_query(x): ball.body.position = x ball.body.velocity = Vec2d(0, 0) ball.body.apply_impulse(40 * test) for ball in finishball: if ball.point_query(x): win = 0 ball.body.position = x ball.body.velocity = Vec2d(0, 0) ball.body.apply_impulse(40 * test) for box in boxes: if box.point_query(x): box.body.position = x box.body.velocity = Vec2d(0, 0) box.body.apply_impulse(40 * test) for tri in triangles: if tri.point_query(x): xx, yy = x tri.body.position = (xx, yy - 4) tri.body.velocity = Vec2d(0, 0) tri.body.apply_impulse(100 * test) screen.fill(THECOLORS["white"]) # Draw the objects to the screen balls_remove = [] for ball in balls: if ball.body.position.y < -100: balls_remove.append(ball) else: draw_ball(screen, ball) for ball in finishball: pos = int(ball.body.position.x), 600 - int(ball.body.position.y) pygame.draw.circle(screen, THECOLORS["purple"], pos, int(ball.radius), 2) if distance(pos, finish) <= windistance: win += 1 else: win = 0 boxes_remove = [] for box in boxes: if box.body.position.y < -100: boxes_remove.append(box) else: draw_poly(screen, box, THECOLORS["red"]) tri_remove = [] for tri in triangles: if tri.body.position.y < -100: tri_remove.append(box) else: draw_poly(screen, tri, THECOLORS["green"]) pygame.draw.circle(screen, THECOLORS["black"], finish, 20, 2) # Remove objects from the space if they happen to get loose for ball in balls_remove: space.remove(ball, ball.body) balls.remove(ball) for box in boxes_remove: boxes.remove(box) for tri in tri_remove: triangles.remove(tri) space.remove(tri, tri.body) for l in lines: draw_line(screen, l) if run_physics: space.step(1 / 60.0) # regular speed else: space.step(1 / 480.0) # slow motion if tick_time == 65: time += 1 tick_time = 0 else: tick_time += 1 # Update timer and score text_right = ["Time: " + str(time) + "s", "Score: " + str(score)] y = 5 for t_line in text_right: text = font.render(t_line, 20, THECOLORS["black"]) screen.blit(text, (600, y)) y += 40 # If the ball is successfully balanced for enough time, you win the level if win == 60 and run_physics: score += int(10000 / (time + 1)) # time+1 just in case time is 0 win = 0 time = 0 time_tick = 0 # progress to next level, if not max level if current_level < max_level: current_level += 1 clear_lists(space, balls, boxes, triangles, lines, finishball) finish = load_level(current_level, space, balls, boxes, triangles, lines, finishball, True) else: running = False clock.tick(60) pygame.display.flip() music.fadeout(1000) return score
if msg == None: sys.exit(0) #print('received\n-----\n{}\n-----'.format(msg)) self.inputs = {} for line in msg.split('\n'): if len(line) == 0: continue f = line.split() if len(f) != 2: print('Ignoring input "{}"'.format(line), file=sys.stderr) else: self.inputs[f[0]] = float(f[1]) self.update() def add_object(self, obj): self.objects.append(obj) if __name__ == '__main__': munk.init_pymunk() disp = Display(tk.Tk()) space = munk.Space(iterations=100, elastic_iterations=100) world = World(space, disp, 'env') world.add_object(Splinter(space, 'splinter', (0., 0.))) world.add_object(Block(space, 'block', (1., 1.))) world.update() tk.mainloop()
def __init__(self, level_path): self.game_over = False self.win = False self.camera_pos = Vec2d(0,0) self.on_screen = [] self.particles = [] self.shape_map = {} self.pan_left = False self.pan_right = False self.pan_up = False self.pan_down = False self.move_left = False self.move_right = False self.jump = False self.jump_time = 0 self.swap_lr = False self.set_keys_later = False #Editor events self.mode_edit=False self.del_mode=False self.cmd_x=0 self.cmd_y=0 self.pos_start=None self.pos_end=None self.pos_mouse=None self.snap_radius=5.0 self.dec_snap_radius=0 self.inc_snap_radius=0 #Load Sounds self.music = pygame.mixer.Sound(os.path.join(RES, 'music.ogg')) self.win_sound = pygame.mixer.Sound(os.path.join(RES, 'win.ogg')) self.win_sound.set_volume(0.6) self.lose_sound = pygame.mixer.Sound(os.path.join(RES, 'lose.ogg')) self.coin_sound = pygame.mixer.Sound(os.path.join(RES, 'coin.ogg')) self.music.play(-1) #PHYSICS!!!! pm.init_pymunk() self.space = pm.Space() self.space.gravity = Vec2d(0.0, 0.0) # Load level self.level_path = level_path try: self.level = level.load_level(self.level_path) except: self.level = level.Level() if not hasattr(self.level, 'coins'): self.level.coins = [] for line in self.level.lines: self.shape_map[line.shape] = line self.space.add_static(line.shape) for gvol in self.level.gvols: self.shape_map[gvol.shape] = gvol self.space.add_static(gvol.shape) if self.level.goal: self.shape_map[self.level.goal.shape] = self.level.goal self.space.add_static(self.level.goal.shape) for cn in self.level.coins: self.shape_map[cn.shape] = cn self.space.add_static(cn.shape) #gravity polygons self.mode_gvol=False self.mode_grav_vec=False self.mode_grav_poly=False#check whether we've used this poly yet in list self.grav_set=False self.grav_vec=None self.poly_verts=[] #the player self.player = Player(self) self.space.add(self.player.body, self.player.shape) self.shape_map[self.player.shape] = self.player #the mouse self.mouse_body=pm.Body(pm.inf,pm.inf) mouse_shape=pm.Circle(self.mouse_body,3,Vec2d(0,0)) mouse_shape.collision_type=COLLTYPE_MOUSE self.space.add(self.mouse_body,mouse_shape) self.space.add_collision_handler(COLLTYPE_DEFAULT, COLLTYPE_MOUSE, self.del_line,None,None,None) self.space.add_collision_handler(COLLTYPE_GRAVITY, COLLTYPE_MOUSE, self.del_gvol,None,None,None) self.space.add_collision_handler(COLLTYPE_LETHAL, COLLTYPE_MOUSE, self.del_line,None,None,None) self.space.add_collision_handler(COLLTYPE_COIN, COLLTYPE_MOUSE, self.del_coin,None,None,None) #The screen to collide with what we need to draw self.screen_body = pm.Body(pm.inf, pm.inf) self.screen_shape = None self.set_screen_shape() self.space.set_default_collision_handler(None, self.ignore_collision, None, None) self.space.add_collision_handler(COLLTYPE_DEFAULT, COLLTYPE_PLAYER, None, self.collect_player_collisions, None, None) self.space.add_collision_handler(COLLTYPE_GRAVITY, COLLTYPE_PLAYER, self.enter_gravity_volume, self.handle_gvol_collision, None, self.leave_gravity_volume) self.space.add_collision_handler(COLLTYPE_GRAVITY, COLLTYPE_PARTICLE, None, self.handle_gvol_collision, None, None) self.space.add_collision_handler(COLLTYPE_LETHAL, COLLTYPE_PLAYER, None, self.handle_lethal_collision, None, None) self.space.add_collision_handler(COLLTYPE_GOAL, COLLTYPE_PLAYER, None, self.handle_goal_collision, None, None) self.space.add_collision_handler(COLLTYPE_COIN, COLLTYPE_PLAYER, None, self.handle_coin_collision, None, None)
def main(): # Variables that need to be initialized pygame.init() screen = pygame.display.set_mode((800,600)) clock = pygame.time.Clock() running = True selection = 1 background_play = load_image("play.png") background_sandbox = load_image("sandbox.png") background_help = load_image("help.png") background_quit = load_image("quit.png") screen.blit(background_play, (0, 0)) pymunk.init_pymunk() space = pymunk.Space() space.gravity = (0.0, -400.0) next_shape = 0 display_help = False winner = False cur_help = 0 score = 0 font = pygame.font.Font(None, 60) """ Music by Rudy Vessup Song name : .:: jUsT dO it::. Downloaded from: http://www.flashkit.com/loops/Sales/Techno_breed/_jUsT-Rudy_Ves-8003/index.php""" music = sandbox.load_sound("main_menu.wav") music.play(-1) # Keep track of balls, triangles and boxes balls = [] triangles = [] boxes = [] # Load the main menu help pictures help_menu = [] for n in range(1, 9): img = load_image("help" + str(n) + ".png") help_menu.append(img) congrats = load_image("congrats.png") # Lines that correspond to the main menu for objects colliding with words sandbox.line(space, 193, 415, 337, 415) sandbox.line(space, 270, 320, 528, 320) sandbox.line(space, 442, 134, 582, 134) # Start the running loop while running: screen.fill(THECOLORS["white"]) pygame.display.set_caption("Welcome to SandBox!") # Capture events for event in pygame.event.get(): if event.type == QUIT: running = False if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False if event.key == K_UP: selection -= 1 if event.key == K_DOWN: selection += 1 if event.key == K_RIGHT: if display_help: cur_help += 1 if event.key == K_LEFT: if display_help: cur_help -= 1 # Click or hit enter on selection to start it if event.type == MOUSEBUTTONDOWN and event.button == 1 or event.type == KEYDOWN and event.key == K_RETURN: if not display_help: if not winner: if selection == 1: music.fadeout(1000) score = sandbox.main() winner = True music.play(-1) elif selection == 2: music.fadeout(1000) sandbox.sandbox() music.play(-1) elif selection == 3: display_help = True elif selection == 4: running = False else: # Close score screen winner = False score = 0 # Progress through the help menu if event.type == MOUSEBUTTONDOWN and event.button == 1: if display_help: x,y = pygame.mouse.get_pos() if x > 115 and x < 180 and y > 465 and y < 500: cur_help -= 1 elif x > 620 and x < 685 and y > 465 and y <500: cur_help += 1 if selection == 0: selection = 4 elif selection == 5: selection = 1 # Use mouse location to select menu items x,y = pygame.mouse.get_pos() if not winner: if x > 193 and x < 337 and y > 170 and y < 240: selection = 1 if x > 270 and x < 528 and y > 262 and y < 343: selection = 2 if x > 356 and x < 510 and y > 366 and y < 430: selection = 3 if x > 442 and x <582 and y > 463 and y < 515: selection = 4 # Start shapes falling, and add more when next_shape == 30 if next_shape == 30: x = random.randint(100, 700) s = random.randint(10, 30) b = sandbox.add_ball(space, s, x, -100) balls.append(b) x = random.randint(100, 700) s = random.randint(10, 50) t = sandbox.add_triangle(space, s, x, -200) t.friction = 0.0 triangles.append(t) x = random.randint(100, 700) s = random.randint(10, 50) s2 = random.randint(10, 50) r = sandbox.add_box(space, s, s2, x, -150) r.friction = 0.0 boxes.append(r) next_shape = 0 else: next_shape += 1 # Remove the objects when they get to a certain point (y == -100), otherwise # game slows to a crawl for ball in balls: if ball.body.position.y < -100: space.remove(ball, ball.body) balls.remove(ball) else: sandbox.draw_ball(screen, ball) for box in boxes: if box.body.position.y < -100: space.remove(box, box.body) boxes.remove(box) else: sandbox.draw_poly(screen, box, THECOLORS["red"]) for tri in triangles: if tri.body.position.y < -100: space.remove(tri, tri.body) triangles.remove(tri) else: sandbox.draw_poly(screen, tri, THECOLORS["green"]) # Show the correct picture for what is being selected if not winner: if selection == 1: screen.blit(background_play, (0, 0)) elif selection == 2: screen.blit(background_sandbox, (0, 0)) elif selection == 3: screen.blit(background_help, (0, 0)) elif selection == 4: screen.blit(background_quit, (0, 0)) # Show score after playing the game text = font.render(str(score), 20, THECOLORS["black"]) if winner: screen.blit(congrats, (0,0)) screen.blit(text, (400,300)) # Show help menu if display_help == True: if cur_help >= 0 and cur_help <= 7: screen.blit(help_menu[cur_help], (0,0)) else: display_help = False cur_help = 0 space.step(1/60.0) clock.tick(60) pygame.display.flip() pygame.quit()
class Nivel(): #bordes=Rect(0,0, 100, 100) offset = vec2d(0, 0) old_offset = vec2d(0, 0) enteroAzar = random.randint import pymunk as pm from pymunk.vec2d import vec2d from collision_handler import Collision_State_Handler #sync_list=[] coll_handlers = [] pm.init_pymunk() space = pm.Space() space.gravity = vec2d(0.0, 900.0) physics_step = 40 #in milliseconds from groups import definitions as groups def __init__(self, timer, file=None): #create sprite goups self.enemies = pygame.sprite.Group() self.friends = pygame.sprite.Group() self.floors = pygame.sprite.Group() self.with_body = pygame.sprite.Group() self.all = pygame.sprite.OrderedUpdates() self.visible = pygame.sprite.OrderedUpdates() #connects actors with current level sprites.Basic_Actor.set_level(self) #setups physics engine self.space.resize_static_hash() self.space.resize_active_hash() self.space.set_damping(0.2) self.background = pygame.Surface(SCREENRECT.size).convert() self.temp_background = self.background.copy() self.last_time = 0 if file is not None: self.populate_from_file(file, timer) def set_as_BG(self, item): position = vec2d(item.rect) - self.offset self.background.blit(item.image, position) def set_offset(self, new_offset): self.old_offset = self.offset self.offset = new_offset def get_background(self): #if not self.old_offset==self.offset: # self.temp_background.blit(self.background, self.offset) return self.temp_background def transform_Y(self, Ycoord): return Ycoord def embody_floor(self, floor): vec2d = self.vec2d transform_Y = self.transform_Y rect = floor.rect point_a = floor.rect.topleft point_b = floor.rect.topright width = floor.rect.height / 2.0 body = self.pm.Body(1e100, 1e100) shape = self.pm.Segment(body, vec2d(point_a[0], transform_Y(point_a[1])), vec2d(point_b[0], transform_Y(point_b[1])), width) shape.friction = 0 shape.group = self.groups['FLOORS'] shape.collision_type = self.groups['FLOORS'] floor.set_id(shape.id) self.space.add_static_shape(shape) floor.body = body floor.shape = shape body.set_position(vec2d(floor.rect.topleft)) self.with_body.add(floor) def populate_from_file(self, file, timer): config = eval(open(file, 'U').read()) self.sanity_check(config) floors = dict() for floor_id in config['Floors']: placement = list(config['Relative Placement'][floor_id]) placement[1] = 600 - self.transform_Y(placement[1]) floors[floor_id] = sprites.Floor( placement, round(config['Floor Sizes'][floor_id] / 32.0)) self.embody_floor(floors[floor_id]) #self.set_as_BG(floors[floor_id]) gates = dict() for gate1_id in config['Gate Graph']: gate2_id = config['Gate Graph'][gate1_id][0] gates[gate1_id], gates[gate2_id] = sprites.Gate.create_connected() shelters = dict() for shelter_id in config['Shelters']: shelters[shelter_id] = sprites.Shelter() for floor_id in config['Hierarchy']: for item_id in config['Hierarchy'][floor_id]: if item_id in gates.keys(): floors[floor_id].attach_gate( gates[item_id], list(config['Relative Placement'][item_id])) #self.set_as_BG(gates[item_id]) elif item_id in shelters.keys(): floors[floor_id].attach_gate( shelters[item_id], list(config['Relative Placement'][item_id])) #self.set_as_BG(shelters[item_id]) num_walkers = config['Options'].get('Walkers', 50) for floor in floors.values(): self.floors.add(floor) for i in range(num_walkers): caminante = sprites.Caveman([ self.enteroAzar(50, 700), 600 - config['Relative Placement']['A'][1] - 50 ]) self.enemies.add(caminante) #personaje=sprites.Volador([400,500], False) #nivel_actual.friends.add(personaje) for floor_id in config['Initial Bodycount']: floors[floor_id].death_toll = config['Initial Bodycount'].get( floor_id, 0) #Register collision function to handle colisions with floor: self.coll_handlers.append( self.Collision_State_Handler(self.space, self.groups['FLOORS'], self.groups['CAVEMEN'], timer).get_table()) engine.State_Machine.set_collision_handlers() #self.space.add_collisionpair_func(self.groups['FLOORS'], self.groups['INCORPOREAL'], None) self.all.add([x.items for x in self.floors]) self.all.add(self.floors) self.all.add(self.friends) self.all.add(self.enemies) self.visible.add(self.floors) self.visible.add([x.items for x in self.floors]) self.visible.add(self.friends) self.visible.add(self.enemies) #self.Space.add_collisionpair_func(self.groups['CAVEMEN'], self.groups['FLOORS'], ) def sanity_check(self, conf_module): main_keys = [ 'Floors', 'Gates', 'Hierarchy', 'Relative Placement', 'Gate Graph', 'Floor Sizes', 'Options' ] for key in main_keys: assert conf_module.has_key(key), 'Module key ' + key + ' missing' Floors = conf_module['Floors'] Gates = conf_module['Gates'] Placements = conf_module['Relative Placement'] Graph = conf_module['Gate Graph'] Sizes = conf_module['Floor Sizes'] Hierarchy = conf_module['Hierarchy'] for floor in Floors: #checks all floors have a position assert Placements.has_key( floor), 'Floor ' + floor + ' position not defined.' assert Sizes.has_key( floor), 'Floor ' + floor + ' size not defined.' if not Sizes[floor] % 32 == 0: print 'Warning, ' + floor + ' size is not multiple of tile size 32' assert 0 <= list(Placements[floor])[0] < SCREENRECT.size[ 0], 'Floor ' + floor + ' x-coordinate out of range' assert 0 <= list(Placements[floor])[1] < SCREENRECT.size[ 1], 'Floor ' + floor + ' y-coordinate out of range' assert 0 <= list( Placements[floor])[0] + Sizes[floor] <= SCREENRECT.size[ 0], 'Floor ' + floor + ' out of bounding box' assert 0 <= list(Placements[floor])[1] + 32 <= SCREENRECT.size[ 1], 'Floor ' + floor + ' out of bounding box' Parents_graph = self.invert(Hierarchy) Inverse_graph = self.invert(Graph) for gate in Gates: assert Parents_graph.has_key( gate), 'Gate ' + gate + ' is an orphan :\'(' assert len( Parents_graph[gate] ) == 1, 'Gate ' + gate + ' has more than one parent: ' + str( Parents_graph[gate]) assert Placements.has_key( gate), 'Gate ' + gate + ' position not defined.' assert 32 <= list(Placements[gate])[0] <= round( Sizes[Parents_graph[gate][0]] / 32.0 ) * 32 - 32, 'Gate ' + gate + ' outside parent colision box' assert 0 == list( Placements[gate] )[1], 'Gate ' + gate + ' coordinate is not 0 (Must be)' assert gate in Inverse_graph or gate in Graph, 'Gate ' + gate + ' not connected to other gate' for floor_id in conf_module['Initial Bodycount']: assert floor_id in Floors, floor_id + ' not defined in floors list' def invert(self, graph): inv = {} for k, v_list in graph.iteritems(): for v in v_list: keys = inv.setdefault(v, []) keys.append(k) return inv def set_visible(self, sprite): if sprite in self.all and not sprite in self.visible: self.visible.add(sprite) def set_invisible(self, sprite): if sprite in self.all and sprite in self.visible: self.visible.remove(sprite) def update(self, current_time): self.all.update(current_time) #print current_time, self.last_time+self.physics_step if current_time > self.last_time + self.physics_step: self.space.step(self.physics_step / 1000.0) self.last_time = current_time #ok... now sincronizes sprites with pymunk. Should use a new group for sprites with body for sprite in self.visible: rel_pos = sprite.body.position + self.offset sprite.rect.topleft = [rel_pos[0], rel_pos[1]]
def main(): global stage_width, stage_height, sidebar_width, wall_gap, gap_size, padding, colors, screen, stage, stage2, barrel_cannon1, child_bonus, grandchild_bonus stage_width, stage_height = 550, 720 sidebar_width = 150 # sidebar displays statistics wall_gap = 20.0 # space between the walls and the edge of the window gap_size = 350.0 # how big the gap in the middle is padding = 5.0 # segment padding gravity = (0.0, -100.0) bound_color = "lightgray" # boundary walls color bg_color = "black" # window background color ball_spacing = 10 # used to space initially fixed balls ball_radius = 20 bullet_color = "green" child_bonus = 1.5 grandchild_bonus = 2.0 # used in collisions to change ball color colors = ["red", "orange", "yellow", "green", "blue", "purple"] pygame.init() screen = pygame.display.set_mode((stage_width + sidebar_width, stage_height)) clock = pygame.time.Clock() running = True pm.init_pymunk() matt = Player("Matt", 1) stage = Stage( matt, screen, K_LEFT, K_RIGHT, K_UP, stage_width, stage_height, wall_gap, gap_size, padding, bound_color, gravity, 0, 100, bullet_color, ) stage.space.add_collisionpair_func(1, 3, barrelcannon_load) spinner1 = Spinner(stage, 150, 100, 25, 25, 1, 1, math.pi / 120, 1, 0.2 * stage_width, 0.5 * stage_width) spinner2 = Spinner(stage, 275, 200, 25, 25, 1, 1, -math.pi / 60, 2, 0.5 * stage_width, 0.8 * stage_width) poly_swing1 = Polyswing(stage, 100, 600, 1, 10, 10, 500, 1, 10, 20, 1, 3, None, 3, 1, "orange") poly_swing2 = Polyswing(stage, 275, 650, 1, 10, 10, 500, 1, 10, 20, 1, 3, None, 3, 1, "red") poly_swing3 = Polyswing(stage, 450, 600, 1, 10, 10, 500, 1, 10, 20, 1, 3, None, 3, 1, "orange") stage.swing_limit = len(stage.swings) * 10 barrel_cannon1 = Barrelcannon(stage, 275, 300, 20, 30, 1, 1, -math.pi / 60, 1, 0.2 * stage_width, 0.8 * stage_width) ticks_to_next_reload = 0 ticks_to_next_respawn = 120 swing_index = 0 last_swing_spawn = 0 start_time = time.time() while running: # main game loop pg_time = pygame.time.get_ticks() / 1000.0 # =============================================================================== # ball_spawn_interval should decrease with time # =============================================================================== if pg_time < 30: ball_spawn_interval = 3 elif pg_time < 60: ball_spawn_interval = 2.75 elif pg_time < 90: ball_spawn_interval = 2.5 elif pg_time < 120: ball_spawn_interval = 2.25 elif pg_time < 150: ball_spawn_interval = 2 elif pg_time < 180: ball_spawn_interval = 1.75 elif pg_time < 210: ball_spawn_interval = 1.5 elif pg_time < 240: ball_spawn_interval = 1.25 elif pg_time < 270: ball_spawn_interval = 1 elif pg_time < 300: ball_spawn_interval = 0.75 elif pg_time < 330: ball_spawn_interval = 0.5 if pg_time - last_swing_spawn >= ball_spawn_interval: last_swing_spawn = pg_time stage.spawn_swing() for event in pygame.event.get(): try: 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_UP and stage.running == True: stage.gun.shoot(1000) # upgrades elif event.type == KEYDOWN and event.key == K_e and stage.running == True: selected_swing.destroy_joint(child_bonus, grandchild_bonus) elif event.type == KEYDOWN and event.key == K_s and stage.running == True: # SECRET WEAPONNNNN!!!! for swing in stage.swings: swing.destroy_joint(child_bonus, grandchild_bonus) elif event.type == KEYDOWN and event.key == K_r and stage.running == True: # If there is no ball, respawn the ball if selected_swing.ball == None: selected_swing.respawn_ball(selected_swing.circle_mass, selected_swing.radius, 1, "red") else: # If there is a ball create a new child # the masses of the segments and balls are determined by which tier the swing is # Tier1 swing is the original swing and can have 3 children. Has 3 segments # Tier2 swings are children of tier1 swings and can have 2 children. Masses are 1/3 of the tier1. Has 2 segments # Tier3 swings are children of tier2 swings and can't have children. Masses are 1/2 of tier2. Has 1 segment new_tier = selected_swing.tier + 1 if new_tier == 2: new_swing = Polyswing( stage, 200, 550, 1, 10, 0.33 * selected_swing.section_mass, 500, 1, 0.33 * selected_swing.circle_mass, 15, 1, 2, selected_swing, 2, new_tier, "red", ) else: # its tier 3 new_swing = Polyswing( stage, 200, 550, 1, 10, 0.5 * selected_swing.section_mass, 500, 1, 0.5 * selected_swing.circle_mass, 10, 1, 1, selected_swing, 0, new_tier, "red", ) elif event.type == KEYDOWN and event.key == K_t: # toggle through the swings try: selected_swing.selected = False except UnboundLocalError: print "no selected swing yet" try: selected_swing = stage.swings[swing_index] except IndexError: print "the swing that was selected isn't there anymore" selected_swing.selected = True if swing_index + 1 > len(stage.swings) - 1: swing_index = 0 else: swing_index = swing_index + 1 elif event.type == KEYDOWN and event.key == K_SPACE: barrel_cannon1.shoot(1200, bullet_color) # new_ball = Bullet(stage, f275, 36 ,2.0,10,0.5,bullet_color) except UnboundLocalError: print "im too lazy to fix this problem right now" # cant release or make the ball for poly_swing2 unless it exists if stage.running == True: barrel_cannon1.move() spinner1.move() spinner2.move() screen.fill(THECOLORS[bg_color]) stage.process_input() stage.draw_stats() # create new threads for these calls? if stage.running == True: # two of these need to be done because step must be infront of draw stage.bullet_reload(pg_time) stage.space.step(1 / 60.0) else: stage.set_end_time() stage.draw_self() pygame.display.flip() clock.tick(60) pygame.display.set_caption("FPS: " + str(clock.get_fps()))
def init_space(self): global __SPACE__ pm.init_pymunk() self.space = pm.Space() self.space.gravity = Vec2d(0.0, -900.0) __SPACE__ = self.space