def __init__(self, state): if state == False: screenMode = pygame.RESIZABLE # true while running. self.running = False self.clock = pygame.time.Clock() self.direction = "still" self.fps = 180 self.counter = 1 self.counter2 = 1 heroPos1 = False # load data from pytmx tmx_data = load_pygame(self.filename) mapPlay = load_pygame(get_map(stats['map'])) # create new data source for pyscroll map_data = pyscroll.data.TiledMapData(mapPlay) # setup level geometry with simple pygame rects, loaded from pytmx. self.walls = list() for object in mapPlay.objects: self.walls.append(pygame.Rect( object.x, object.y, object.width, object.height)) # create new renderer (camera) self.map_layer = pyscroll.BufferedRenderer(map_data, screen.get_size()) self.map_layer.zoom = 2 self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=4) self.hero = Hero('Tiles/character/character_still.png') self.hero.position = stats['pos'] # add our hero to the group self.group.add(self.hero)
def map_change(self, map, target=False): # Does what it says on the tin mapfile = get_map(map) tmx_data = load_pygame(mapfile) self.tmx_data = tmx_data map_data = pyscroll.data.TiledMapData(tmx_data) self.walls = list() for object in tmx_data.objects: self.walls.append(pygame.Rect( object.x, object.y, object.width, object.height)) # creates new 'camera' self.map_layer = pyscroll.BufferedRenderer(map_data, screen.get_size()) self.map_layer.zoom = 2 self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=4) #creates a new Hero to go on our new camera self.hero = Hero('Tiles/hero/character_still.png') try: self.hero.position = (target) except TypeError: self.hero.position = self.map_layer.map_rect.center self.map = stats['map'][:-4].lower() self.map = self.map.lstrip("m") # Fix that stupid bug that changes "maze1" to "ze1" self.map = self.map.lstrip("aps/")
def __init__(self): # true while running self.running = False # load data from pytmx tmx_data = load_pygame(self.filename) # setup level geometry with simple pygame rects, loaded from pytmx self.walls = list() for object in tmx_data.objects: self.walls.append(pygame.Rect( object.x, object.y, object.width, object.height)) # create new data source for pyscroll map_data = pyscroll.data.TiledMapData(tmx_data) # create new renderer (camera) self.map_layer = pyscroll.BufferedRenderer(map_data, screen.get_size()) self.map_layer.zoom = 2 # pyscroll supports layered rendering. our map has 3 'under' layers # layers begin with 0, so the layers are 0, 1, and 2. # since we want the sprite to be on top of layer 1, we set the default # layer for sprites as 2 self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=2) self.hero = Hero() # put the hero in the center of the map self.hero.position = self.map_layer.map_rect.center # add our hero to the group self.group.add(self.hero)
def __init__(self, screen_size, map, bgmusic=None): pygame.init() #pygame.mixer.init() self.screen_size = screen_size self.screen = pygame.display.set_mode(screen_size) self.rect = self.screen.get_rect() self.clock = pygame.time.Clock() self.map = load_pygame(map) self.running = False self.group = pyscroll.PyscrollGroup() self.obstacles = pygame.sprite.Group() # Use pyscroll to ensure that the camera tracks the player and does # not go off the edge. map_data = pyscroll.TiledMapData(self.map) map_layer = pyscroll.BufferedRenderer( map_data, screen_size, clamp_camera=True) self.group = pyscroll.PyscrollGroup( map_layer=map_layer, default_layer=1) if bgmusic: self.music = music.load(bgmusic) print(bgmusic) else: self.music = None
def __init__(self, filename): tm = load_pygame(filename) # self.size will be the pixel size of the map # this value is used later to render the entire map to a pygame surface self.pixel_size = tm.width * tm.tilewidth, tm.height * tm.tileheight self.tmx_data = tm
def __init__(self, filename): # load data from pytmx tmx_data = load_pygame(filename) # create new data source map_data = pyscroll.data.TiledMapData(tmx_data) # create new renderer self.map_layer = pyscroll.orthographic.BufferedRenderer(map_data, screen.get_size()) # create a font and pre-render some text to be displayed over the map f = pygame.font.Font(pygame.font.get_default_font(), 20) t = ["scroll demo. press escape to quit", "arrow keys move"] # save the rendered text self.text_overlay = [f.render(i, 1, (180, 180, 0)) for i in t] # set our initial viewpoint in the center of the map self.center = [self.map_layer.map_rect.width / 2, self.map_layer.map_rect.height / 2] # the camera vector is used to handle camera movement self.camera_acc = [0, 0, 0] self.camera_vel = [0, 0, 0] self.last_update_time = 0 # true when running self.running = False
def load_map_connections(self): c_left_offset = 0 c_right_offset = 0 c_up_offset = 0 c_down_offset = 0 if 'connection_left' in self.map.properties: c_left_map = load_pygame(map_dir + self.map.properties['connection_left'] + ".tmx") if 'outside' in c_left_map.properties: if c_left_map.properties['outside'] == "true": if systime.get_time_of_day() == "Night": print("It's night.") c_left_map.tilesets[0].source = "../Tilesets/GSC overworld johto nite.png" c_left_map.reload_images() if 'c_left_offset' in self.map.properties: c_left_offset = int(self.map.properties['c_left_offset']) connection_left = MapConnection(c_left_map, DIR_LEFT, c_left_offset) self.connections['left'] = connection_left if 'connection_right' in self.map.properties: c_right_map = load_pygame(map_dir + self.map.properties['connection_right'] + ".tmx") if 'outside' in c_right_map.properties: if c_right_map.properties['outside'] == "true": if systime.get_time_of_day() == "Night": print("It's night.") c_right_map.tilesets[0].source = "../Tilesets/GSC overworld johto nite.png" c_right_map.reload_images() if 'c_right_offset' in self.map.properties: c_right_offset = int(self.map.properties['c_right_offset']) connection_right = MapConnection(c_right_map, DIR_RIGHT, c_right_offset) self.connections['right'] = connection_right if 'connection_up' in self.map.properties: c_up_map = load_pygame(map_dir + self.map.properties['connection_up'] + ".tmx") if 'outside' in c_up_map.properties: if c_up_map.properties['outside'] == "true": if systime.get_time_of_day() == "Night": print("It's night.") c_up_map.tilesets[0].source = "../Tilesets/GSC overworld johto nite.png" c_up_map.reload_images() if 'c_up_offset' in self.map.properties: c_up_offset = int(self.map.properties['c_up_offset']) connection_up = MapConnection(c_up_map, DIR_UP, c_up_offset) self.connections['up'] = connection_up if 'connection_down' in self.map.properties: c_down_map = load_pygame(map_dir + self.map.properties['connection_down'] + ".tmx") if 'c_down_offset' in self.map.properties: c_down_offset = int(self.map.properties['c_down_offset']) connection_down = MapConnection(c_down_map, DIR_UP, c_down_offset) self.connections['up'] = connection_down
def __init__(self, filename): self.data = pytmxutil.load_pygame(filename) self.surface = pygame.Surface((self.data.width*self.data.tilewidth, self.data.height*self.data.tileheight)) if "Timelimit" in self.data.properties: self.time_limit = float(self.data.properties["Timelimit"]) else: self.time_limit = None self.refresh(self.surface.get_rect())
def __init__(self, state): if state == False: self.fullscreen = False # true while running. self.running = False self.clock = pygame.time.Clock() # create all the directio variables self.direction = "still" self.EntityDirection = "still" self.EntityDirection1, self.EntityDirection2 = "still", "still" self.fps = 1000 self.bypass = False entityPos1, heroPos1 = False, False # load data from pytmx tmx_data = load_pygame(self.filename) self.tmx_data = tmx_data mapPlay = load_pygame(get_map(stats['map'])) # create new data source for pyscroll map_data = pyscroll.data.TiledMapData(mapPlay) # setup level geometry with simple pygame rects, loaded from pytmx. self.walls = list() for object in mapPlay.objects: self.walls.append(pygame.Rect( object.x, object.y, object.width, object.height)) # create new renderer (camera) self.map_layer = pyscroll.BufferedRenderer(map_data, screen.get_size()) self.map_layer.zoom = 2 self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=4) self.hero = Hero('Tiles/hero/character_still.png') self.entity = Entity('Tiles/hero/character_still.png') self.hero.position = stats['pos'] self.entity.position = stats['pos'] # add our hero to the group self.group.add(self.hero) #self.group.add(self.entity) self.entVel = (0, 0)
def __init__(self): self.score = 0 self.start_screen = True self.start_screen_obj = StartScreen() self.game_over = False self.pause = False self.game_over_music_enabled = False self.fps = 0.0 self.font = pygame.font.Font(os.path.join('fonts', 'PressStart2P.ttf'), 8) self.all_sprites_list = pygame.sprite.Group() self.player_object_list = pygame.sprite.Group() #it contains all enemy sprites including bullets self.enemy_object_list = pygame.sprite.Group() #it contains only ships and monsters self.enemy_list = pygame.sprite.Group() Player.containers = self.all_sprites_list, self.player_object_list EnemySmallSpaceship.containers = self.all_sprites_list, self.enemy_object_list, self.enemy_list Whale.containers = self.all_sprites_list, self.enemy_object_list, self.enemy_list Bullet.containers = self.all_sprites_list, self.enemy_object_list BulletPlayer.containers = self.all_sprites_list, self.player_object_list self.last_time_enemy_killed = pygame.time.get_ticks() self.milliseconds_per_kill = 1500 # Create the player self.player = Player() self.interval_spawn_enemy = 1500 self.last_time_spawn_enemy = pygame.time.get_ticks() self.max_score = 0 # Test boss #add_whale() self.start_screen_obj.play_music() # Load TMX data tmx_data = load_pygame(os.path.join('maps', 'mapcorridor.tmx')) # Make data source for the map map_data = pyscroll.TiledMapData(tmx_data) # Make layer self.map_layer = pyscroll.BufferedRenderer(map_data, (SCREEN_WIDTH, SCREEN_HEIGHT)) self.center_map = [self.map_layer.map_rect.width//2, self.map_layer.map_rect.height - SCREEN_HEIGHT//2]
def load_map(name): global map global dmap dmap = load_pygame(map_dir + name + '.tmx') if 'outside' in dmap.properties: if dmap.properties['outside'] == "true": if systime.get_time_of_day() == "Night": print("It's night.") dmap.tilesets[0].source = "../Tilesets/GSC overworld johto nite.png" dmap.reload_images() map = Map(dmap) del dmap
def __init__(self, fileName): self._tmx = load_pygame(os.path.join('assets', 'levels', fileName)) self.mapSize = (self._tmx.width, self._tmx.height) self.cellSize = (self._tmx.tilewidth, self._tmx.tileheight) self.solidityMap = [None] * self.getTileTotal() self.surfaces = OrderedDict() self.backgroundColor = pygame.Color(self._tmx.background_color) \ if self._tmx.background_color \ else (0, 0, 0, 0) for layer in self._tmx.visible_layers: self.parseLayer(layer)
def __init__(self, filename): tm = load_pygame(filename) # self.size will be the pixel size of the map # this value is used later to render the entire map to a pygame surface self.pixel_size = tm.width * tm.tilewidth, tm.height * tm.tileheight self.tmx_data = tm for layer in self.tmx_data.visible_tile_layers: layer = self.tmx_data.layers[layer] for i in layer.tiles(): print(i) continue
def LoadSprites(self): """Load the sprites that we need""" self.player = Player(self) self.player_sprites = pygame.sprite.RenderPlain((self.player)) self.tiled_map = load_pygame('map.tmx') self.tile_size = 40 obstacles_layer = self.tiled_map.get_layer_by_name("Obstacles") for obj in obstacles_layer: self.PlaceObstacle(obj.x, obj.y) self.Restart()
def __init__(self, map_source): self.all_sprites = pg.sprite.Group() self.visible_sprites = pg.sprite.Group() self.map_sprites = pg.sprite.Group() self.collition_sprites = pg.sprite.Group() self.map_source = load_pygame(bootstrap.MAPS[0]) self.grid = pathfinding.GridWithWeights( self.map_source.width, self.map_source.height) w = self.map_source.width * util.TILE_SIZE h = self.map_source.height * util.TILE_SIZE self.image = pg.Surface((w, h)) self.rect = self.image.get_rect() self.make_map()
def __init__(self, screen): State.__init__(self, screen) self.name = "GameState" self.description = "Draw your game inside here" # A whole Block just to display the Text ... self.font1 = pygame.font.SysFont("Monospaced", 50) self.font2 = pygame.font.SysFont("Monospaced", 32) # Render the text self.text1 = self.font1.render(self.name, True, (255,255, 255), (159, 182, 205)) self.text2 = self.font2.render(self.description, True, (255,255, 255), (159, 182, 205)) # Create Text-rectangles self.text1Rect = self.text1.get_rect() self.text2Rect = self.text2.get_rect() # Center the Text-rectangles self.text1Rect.centerx = self.screen.get_rect().centerx self.text1Rect.centery = self.screen.get_rect().centery self.text2Rect.centerx = self.screen.get_rect().centerx self.text2Rect.centery = self.screen.get_rect().centery+50 self.screen_rect = screen.get_rect() self.done = False self.fps = 60 self.done = False self.keys = pygame.key.get_pressed() # true while running self.running = False # load data from pytmx self.tmx_data = load_pygame(self.filename, pixelalpha=True) #print self.tmx_data.layers.TiledTileLayer.properties['under0'] # setup level geometry with simple pygame rects, loaded from pytmx # create new data source for pyscroll self.map_data = pyscroll.data.TiledMapData(self.tmx_data) w, h = screen.get_size() # create new renderer (camera) # clamp_camera is used to prevent the map from scrolling past the map's edge # cambiar el 1 por el tamano de zoom self.map_layer = pyscroll.BufferedRenderer(self.map_data, (w / 1, h / 1), clamp_camera=True) # pyscroll supports layered rendering. our map has 3 'under' layers # layers begin with 0, so the layers are 0, 1, and 2. # since we want the sprite to be on top of layer 1, we set the default # layer for sprites as 2 self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=2)
def __init__(self, path): Sprite.__init__(self, 0,0) self.map = load_pygame(os.path.join(Assets.RootDir, path)) self.image = pygame.Surface((self.map.width * self.map.tilewidth, self.map.height * self.map.tileheight)) self.image.fill(hex_to_rgb(self.map.background_color)) for layer in self.map.layers: if layer.name != "objects" and layer.name != "collision": for x, y, image in layer.tiles(): self.image.blit(image, (x*self.map.tilewidth,y*self.map.tileheight)) self.collision = [] colLayer = self.map.get_layer_by_name("collision") for x,y,image in colLayer.tiles(): self.collision.append(pygame.Rect(x,y,image.get_width(),image.get_height()))
def __init__(self): # true while running self.running = False # load data from pytmx tmx_data = load_pygame(self.filename) # set the current resolution self.res = get_screen_res() self.up = self.down = self.right = self.left = 0 # set up for declaration for key in config.items('KEY_CONFIG'): # declare config keys exec('self.' + key[0] + ' = K_' + key[1]) # setup level geometry with simple pygame rects, loaded from pytmx self.walls = list() for obj in tmx_data.objects: self.walls.append(pygame.Rect( obj.x, obj.y, obj.width, obj.height)) # create new data source for pyscroll map_data = pyscroll.data.TiledMapData(tmx_data) # create new renderer (camera) self.map_layer = pyscroll.BufferedRenderer(map_data, screen.get_size()) self.map_layer.zoom = 2 # pyscroll supports layered rendering. our map has 3 'under' layers # layers begin with 0, so the layers are 0, 1, and 2. # since we want the sprite to be on top of layer 1, we set the default # layer for sprites as 2 self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=2) # Define characters self.prototype = Prototype(res=self.res) self.enemy = Enemy(enemy_type=enemy.suicide_explode, res=self.res) # Set character positions self.prototype.position = self.map_layer.map_rect.center self.enemy.position = (300, 300) # add our hero to the group self.group.add(self.enemy) self.group.add(self.prototype)
def __init__(self, fname): self.width, self.height = 1024, 768 self.tile_width, self.tile_height = 64, 32 self.fullname = os.path.join('data', '%s.tmx' % fname) self.tmx_data = load_pygame(self.fullname) self.map_data = pyscroll.TiledMapData(self.tmx_data) self.tileset = load_image("iso-64x64-outside.png") self.map_layer = pyscroll.IsometricBufferedRenderer(self.map_data, (self.width, self.height)) self.map_layer.zoom = 2 self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=2)
def map_change(self, map): mapfile = get_map(map) tmx_data = load_pygame(mapfile) print(tmx_data) map_data = pyscroll.data.TiledMapData(tmx_data) self.walls = list() for object in tmx_data.objects: self.walls.append(pygame.Rect( object.x, object.y, object.width, object.height)) self.map_layer = pyscroll.BufferedRenderer(map_data, screen.get_size()) self.map_layer.zoom = 2 self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=4) self.hero = Hero('Tiles/character/character_still.png') self.hero.position = self.map_layer.map_rect.center
def ChangeLevel(self, level): self.obstacles = [] self.obstacle_sprites = pygame.sprite.RenderPlain() self.tiled_map = load_pygame(level) self.tile_size = 40 if "Obstacles" in self.tiled_map.layernames: obstacles_layer = self.tiled_map.get_layer_by_name("Obstacles") for obj in obstacles_layer: self.PlaceObstacle(obj) if "Enemy" in self.tiled_map.layernames: enemies_layer = self.tiled_map.get_layer_by_name("Enemy") for obj in enemies_layer: if obj.image is not None: self.PlaceEnemy(obj) self.Restart()
def run_game(width, height, fps, starting_scene): # global height_pos pygame.init() screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('Racer') clock = pygame.time.Clock() from pytmx.util_pygame import load_pygame active_scene = starting_scene tile_data = load_pygame("road.tmx") while active_scene is not None: # print type(pygame.surfarray.array2d(screen)) pressed_keys = pygame.key.get_pressed() # Event filtering filtered_events = [] for event in pygame.event.get(): quit_attempt = False if event.type == pygame.QUIT: quit_attempt = True elif event.type == pygame.KEYDOWN: alt_pressed = pressed_keys[pygame.K_LALT] or \ pressed_keys[pygame.K_RALT] if event.key == pygame.K_ESCAPE: quit_attempt = True elif event.key == pygame.K_F4 and alt_pressed: quit_attempt = True if quit_attempt: active_scene.terminate() pygame.quit() sys.exit() else: filtered_events.append(event) active_scene.processinput(filtered_events, pressed_keys) active_scene.update() active_scene = active_scene.next clock.tick(fps) # print clock.get_fps() # height_pos += scroll_speed active_scene.render(screen, tile_data) pygame.display.update()
def __init__(self, mapFile = "isometric_grass_and_water2.tmx"): pygame.init() os.environ['SDL_VIDEO_CENTERED'] = '1' self.clock = pygame.time.Clock() self.mapFile = mapFile #This is the filename of the map to be used for the display of this simulation mydir = os.path.dirname(os.path.realpath(__file__)) subdir = 'Maps' mapfilepath = os.path.join(mydir, subdir, self.mapFile) self.tmxdata = TiledMap(mapfilepath) self.tw = int(self.tmxdata.get_tile_properties(0,0,0)['width']) self.th = int(self.tmxdata.get_tile_properties(0,0,0)['height']/2.) self.gridWidth = int(self.tmxdata.properties['Width']) self.gridHeight = int(self.tmxdata.properties['Width']) self.SIZE = [self.gridWidth*self.tw, self.gridHeight*self.th] self.RESIZE = [1600,800] self.screen = pygame.display.set_mode(self.RESIZE, HWSURFACE|DOUBLEBUF|RESIZABLE) pygame.display.set_caption("Creature Simulation") pygame.event.set_allowed(QUIT) self.screen.fill(self.WHITE) self.gameMap = load_pygame(mapfilepath)
def __init__(self, player): self.max_enemies = 18 self.all_sprites = pg.sprite.LayeredUpdates() self.map_sprites = pg.sprite.Group() self.actions = pg.sprite.Group() self.walls = pg.sprite.Group() self.visible_sprites = pg.sprite.LayeredUpdates() self.player_singleton = pg.sprite.GroupSingle() self.world_map = load_pygame(util.MAPS.pop()) w = self.world_map.width*util.WALL_SIZE h = self.world_map.height*util.WALL_SIZE self.image = pg.Surface((w,h)) self.rect = self.image.get_rect() player.add(self.player_singleton, self.all_sprites) self.make_level() tiles = self.map_sprites.sprites() player.rect.topleft = random.choice(tiles).rect.topleft self.enemies = self.make_enemies() self.viewport = Viewport() self.viewport.update(self.player_singleton.sprite, self.rect)
def displayMap(level): #show the map using tmx tiles global screenWidth global screenHeight global screen gameMap = load_pygame(level) for layer in gameMap.visible_layers: if isinstance(layer,pytmx.TiledTileLayer): for x,y,image in layer.tiles(): screen.blit(image,(x*gameMap.tilewidth,y*gameMap.tileheight)) elif isinstance(layer,pytmx.TiledObjectGroup): for obj in layer: if hasattr(obj,'col'): # pygame.draw.lines(screen,poly_color,obj.closed,obj.points,3) pass elif obj.image: screen.blit(obj.image,(obj.x,obj.y)) elif isinstance(layer,pytmx.TiledImageLayer): screen.blit(layer.image,(0,0)) for obj in gameMap.objects: blocker_group.add(Blocks(obj.x,obj.y,obj.width,obj.height))
def loadTMXMap(self, path): self.data = load_pygame(path) # definir mapita self.width = self.data.width self.height = self.data.height layersAmount = len(self.data.layers) for idz in range(layersAmount): for idx, idy, image in self.data.layers[idz].tiles(): tile = Tile() tile.renderImage( image.convert(), pygame.Rect( self.x + idx * self.data.tilewidth, self.y + idy * self.data.tileheight, self.data.tilewidth, self.data.tileheight, ), ) tileID = "x" + str(idx) + "y" + str(idy) + "z" + str(idz) self.tileOrder.append(tileID) self.add(tileID, tile) self.rect = pygame.Rect(self.x, self.y, self.width * self.data.tilewidth, self.height * self.data.tileheight)
def load_all_levels(self): self.levels = {} # name : json_content self.tmx_levels = {} # name : tmx_data self.collisions = {} # name : [array of Rects] self.level = "village" try: self.game.debug("loading levels...") # load json data lvl_files = [f for f in os.listdir(self.lvl_path)] for l in lvl_files: if l.endswith(".json"): ftype = 'json' else: ftype = None level_name = self.get_level_name(l) l = os.path.join(self.lvl_path, l) if ftype == 'json': print "Level name: " + level_name with open(l,'r') as f: self.levels[level_name] = json.loads(f.read()) # load tmx data tmx_files = [f for f in os.listdir(self.tmx_path)] for l in tmx_files: if l.endswith(".tmx"): ftype = "tmx" else: ftype = None level_name = self.get_level_name(l) l = os.path.join(self.tmx_path, l) if ftype == "tmx": with open(l, "r") as f: self.tmx_levels[level_name] = load_pygame(l) except Exception as e: self.game.debug("LevelManager.load_all_levels: " + str(e))
def load(self, filename): """Load map data from a tmx map file and get all the map's events and collision areas. Loading the map data is done using the pytmx library. Specifications for the TMX map format can be found here: https://github.com/bjorn/tiled/wiki/TMX-Map-Format :param filename: The path to the tmx map file to load. :type filename: String :rtype: None :returns: None **Examples:** In each map, there are three types of objects: **collisions**, **conditions**, and **actions**. Here is how an action would be defined using the Tiled map editor: .. image:: images/map/map_editor_action01.png Here is an example of how we use pytmx to load the map data from a tmx file and what those objects would look like after loading: >>> tmx_data = pytmx.TiledMap("pallet_town-room.tmx") >>> for obj in tmx_data.objects: ... pprint.pprint(obj.__dict__) ... {'gid': 0, 'height': 32, 'name': None, 'parent': <TiledMap: "../tuxemon/resources/maps/pallet_town-room.tmx">, 'rotation': 0, 'type': 'collision', 'visible': 1, 'width': 16, 'x': 160, 'y': 48} {'action_id': '9', 'condition_type': 'player_at', 'gid': 0, 'height': 16, 'id': 9, 'name': 'Start Combat', 'operator': 'is', 'parameters': '1,11', 'parent': <TiledMap: "../tuxemon/resources/maps/pallet_town-room.tmx">, 'rotation': 0, 'type': 'condition', 'visible': 1, 'width': 16, 'x': 16, 'y': 176} {'action_type': 'teleport', 'gid': 0, 'height': 16, 'id': 5, 'name': 'Go Downstairs', 'parameters': 'test.tmx,5,5', 'parent': <TiledMap: "../tuxemon/resources/maps/pallet_town-room.tmx">, 'priority': '1', 'rotation': 0, 'type': 'action', 'visible': 1, 'width': 16, 'x': 0, 'y': 0} """ # Load the tmx map data using the pytmx library. self.filename = filename # Scale the loaded tiles if enabled if prepare.CONFIG.scaling == "1": self.data = pytmx.TiledMap(filename, image_loader=scaled_image_loader, pixelalpha=True) self.data.tilewidth, self.data.tileheight = prepare.TILE_SIZE else: self.data = load_pygame(filename, pixelalpha=True) # make a scrolling renderer self.renderer = self.initialize_renderer() # Get the map dimensions self.size = self.data.width, self.data.height # Get the tile size of the map self.tile_size = self.data.tilesets[0].tilewidth, self.data.tilesets[0].tileheight # Load all objects from the map file and sort them by their type. for obj in self.data.objects: if obj.type == 'collision': self.collisions.append(obj) elif obj.type == 'collision-line': self.collision_lines.append(obj) elif obj.type == 'event': self.events.append(self.loadevent(obj)) elif obj.type == 'init': self.inits.append(self.loadevent(obj)) elif obj.type == 'interact': self.interacts.append(self.loadevent(obj))
xPixelPos = tiles[0] * 16 #+ world_offset yPixelPos = tiles[1] * 16 #+ world_offset mapImg = tiles[2] #get img to draw from tmxdata screen.blit(mapImg, (xPixelPos, yPixelPos)) #draw map to screen # end draw_map() # Initialize and run game if __name__ == "__main__": width, height = 640, 640 #init pygame pygame.init() #create screen (width, height) #Game().runGame() # UNCOMMENT THIS TO RUN WITH GAME CLASS INSTEAD -- CURRENTLY UNECESSARY screenSize = (width, height) screen = pygame.display.set_mode(screenSize) # Window title pygame.display.set_caption("Untitled Rogue-Like game") tmxdata = load_pygame("rooms\\basic_room.tmx") # Load map from tmx file fireBallList = [] # list of fire ball sprites fireBallTimer = 0.1 # To set window icon: # icon = pygame.image.load("image.png") # pygame.display.set_icon(icon) clock = pygame.time.Clock() dt = clock.tick(60) / 1000 # dt = time since last tick in milliseconds startTicks = pygame.time.get_ticks() main() pygame.quit()
def __init__(self): self.mapa = load_pygame("sprites/street.tmx") # LE O MAPA self.mapa_width = self.mapa.width * self.mapa.tilewidth # DEFINE SEU WIDTH self.mapa_height = self.mapa.height * self.mapa.tileheight # DEFINE SEU HEIGHT self.mapa_data = self.mapa # DEFINI SUA DATA
def __init__(self): pygame.mixer.pre_init(44100, 16, 1, 4096) pygame.init() pygame.font.init() self.screen = init_screen(800, 600) pygame.display.set_caption('Polaria') # Music channel self.music_channel = pygame.mixer.Channel(1) self.sounds = Sounds() # Store projectiles in a group self.projectiles = Group() # true while running self.running = False # load data from pytmx tmx_data = load_pygame(self.filename) # setup level geometry with simple pygame rects, loaded from pytmx self.walls = list() for object in tmx_data.objects: self.walls.append( pygame.Rect(object.x, object.y, object.width, object.height)) # create new data source for pyscroll map_data = pyscroll.data.TiledMapData(tmx_data) # create new renderer (camera) self.map_layer = pyscroll.BufferedRenderer(map_data, self.screen.get_size()) self.map_layer.zoom = 3.75 # pyscroll supports layered rendering. our map has 3 'under' layers # layers begin with 0, so the layers are 0, 1, and 2. # since we want the sprite to be on top of layer 1, we set the default # layer for sprites as 2 self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=3) self.hero = Hero() self.heroes = list() self.heroes.append(self.hero) # Spawn an npc self.npc = NPC() self.npc.position = self.map_layer.map_rect.move(544, 592).topleft self.group.add(self.npc) self.npcs = list() self.npcs.append(self.npc) # Spawn an elemental below the house self.spawn_elementals() # Spawn the hero outside his house self.hero.position = self.map_layer.map_rect.move(528, 592).topleft # add our hero to the group self.group.add(self.hero) self.projectile_skin = 0 # Which spell the user has selected self.clock = pygame.time.Clock() # Dictionary to hold onto what keys are being held down self.movement_keys = { 'UP': False, 'DOWN': False, 'LEFT': False, 'RIGHT': False }
import pygame from pytmx.util_pygame import load_pygame import CollectionsModule import Tower #global variables clock = pygame.time.Clock() screenWidth = 800 screenHeight = 700 screenSize = screenWidth, screenHeight mainSurface = pygame.display.set_mode(screenSize, pygame.RESIZABLE) tileSelectSprite = pygame.image.load("Assets/selectSprite.gif") #maps map1 = load_pygame('Assets/Maps/testMap.tmx') #function used for primary initialization def mainInit(): #initialize pygame pygame.init() pygame.joystick.init() #set the background color backgroundColor = 66, 61, 60 mainSurface.fill(backgroundColor) initGame() #function used for rendering text - returns a surface and the associated rectangle for that surface
def loadWorld_11(self): tmx_data = load_pygame("worlds/1-1/W11.tmx") self.mapSize = (tmx_data.width, tmx_data.height) self.sky = pg.Surface((WINDOW_W, WINDOW_H)) self.sky.fill((pg.Color('#FFC6D3'))) # 2D List self.map = [[0] * tmx_data.height for i in range(tmx_data.width)] layer_num = 0 for layer in tmx_data.visible_layers: for y in range(tmx_data.height): for x in range(tmx_data.width): # Getting pygame surface image = tmx_data.get_tile_image(x, y, layer_num) # It's none if there are no tile in that place if image is not None: tileID = tmx_data.get_tile_gid(x, y, layer_num) if layer.name == 'Foreground': # 22 ID is a question block, so in taht case we shoud load all it's images if tileID == 22: image = ( image, # 1 tmx_data.get_tile_image(0, 15, layer_num), # 2 tmx_data.get_tile_image(1, 15, layer_num), # 3 tmx_data.get_tile_image( 2, 15, layer_num) # activated ) # Map class has 1)"map" list, which is used in collision system because we can # easily get block by x and y coordinate 2)"obj", "obj_bg" and simular arrays - # they are used in rendering because you don't need to cycle through every # (x, y) pair. Here we are adding the same platform object in 2 different arrays. self.map[x][y] = Platform(x * tmx_data.tileheight, y * tmx_data.tilewidth, image, tileID) self.obj.append(self.map[x][y]) elif layer.name == 'Background': self.map[x][y] = BGObject(x * tmx_data.tileheight, y * tmx_data.tilewidth, image) self.obj_bg.append(self.map[x][y]) layer_num += 1 # Tubes self.spawn_tube(28, 10) self.spawn_tube(37, 9) self.spawn_tube(46, 8) self.spawn_tube(55, 8) self.spawn_tube(163, 10) self.spawn_tube(179, 10) # Mobs self.mobs.append(Goombas(736, 352, False)) self.mobs.append(Goombas(1295, 352, True)) self.mobs.append(Goombas(1632, 352, False)) self.mobs.append(Goombas(1672, 352, False)) self.mobs.append(Goombas(5570, 352, False)) self.mobs.append(Goombas(5620, 352, False)) self.map[21][8].bonus = 'mushroom' self.map[78][8].bonus = 'mushroom' self.map[109][4].bonus = 'mushroom' self.flag = Flag(6336, 48)
def __init__(self, filename): tm = load_pygame(filename, pixelalpha=True) self.width = tm.width * tm.tilewidth self.height = tm.height * tm.tileheight self.tmxdata = tm self.map = [[0 for row in range(tm.height)] for col in range(tm.width)]
pygame.init() ###############CONSTANT############### white = (255, 255, 255) screen_res = (1600, 1600) map = pygame.image.load('Assets/map1.png') clock = pygame.time.Clock() ######Pygame Initialization pygame.display.set_caption('MASON IS A F*****G GOD') display = pygame.display.set_mode(screen_res) # CREATES DISPLAY screen = pygame.display.get_surface() # CREATES SURFACE FROM DISPLAY tmxdata = load_pygame('Assets/map1.tmx') # LOADS TILED MAP DATA. player_group = pygame.sprite.Group() class Main(pygame.sprite.Sprite): state = 'world' def __init__(self): super().__init__ def loop(self): while True: clock.tick(50)
def load_map(filepath): if not os.path.exists(filepath): raise IOError('Failed to load map file %s!' % filepath) return load_pygame(filepath)
def __init__(self, filename, oldEntrance=None, oldmap=None, hero=None): self.portalName = '' self.portalsIn = list() self.portalsOut = list() self.olfFilename = None self.filename = get_map(filename) if self.filename in heroStates: self.mode = heroStates[self.filename] else: self.mode = "Peaceful" if oldmap == None: self.oldMap = filename else: self.oldMap = oldmap overworld = 'BinalOverworld2.tmx' self.oldEntrance = oldEntrance self.battleInstance = False # true while running self.running = False # load data from pytmx tmx_data = load_pygame(self.filename) # setup level geometry with simple pygame rects, loaded from pytmx self.walls = list() for object in tmx_data.objects: self.walls.append( pygame.Rect(object.x, object.y, object.width, object.height)) # create new data source for pyscroll map_data = pyscroll.data.TiledMapData(tmx_data) # create new renderer (camera) self.map_layer = pyscroll.BufferedRenderer(map_data, screen.get_size(), clamp_camera=False, tall_sprites=1) self.map_layer.zoom = 2 # pyscroll supports layered rendering. our map has 3 'under' layers # layers begin with 0, so the layers are 0, 1, and 2. # since we want the sprite to be on top of layer 1, we set the default # layer for sprites as 2 self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=2) self.hero = Hero() # put the hero in the center of the map # self.hero.position = self.map_layer.map_rect.center # self.hero._position[0] += 200 # self.hero._position[1] += 400 # add our hero to the group self.group.add(self.hero) # startpoints self.startpoints = [] for object in tmx_data.objects: if object.name == "startpoint": self.startpoints.append((object.x, object.y)) self.hero.position = (self.startpoints[0][0], self.startpoints[0][1]) self.oldPosition = self.hero.position self.group.add(self.hero) self.steps = 0 self.battle = 1 # set default zoom when not in overworld if self.oldMap == overworld and self.filename != "data/" + overworld: self.map_layer.zoom = self.map_layer.zoom - .25 self.portalNames = list() # add portals to collider lists for object in tmx_data.objects: if object.type == "portalIn": self.portalNames.append(object) self.portalsIn.append( pygame.Rect(object.x, object.y, object.width, object.height)) elif object.type == "portalO": self.portalsOut.append( pygame.Rect(object.x, object.y, object.width, object.height))
def _load(self, path: str) -> TiledMap: return load_pygame(path)
def __init__(self, filename): tm = load_pygame(filename) self.size = tm.width * tm.tilewidth, tm.height * tm.tileheight self.tmx_data = tm
from pytmx.util_pygame import load_pygame import pygame, sys pygame.init() WIDTH = 400 HEIGHT = 400 display = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE) display.fill((0, 0, 0)) tiled_map = load_pygame('test_bigger.tmx') map_scale = 1 / 2 surfs = [] layer = tiled_map.layers[0] tile_width = 0 tile_height = 0 for x, y, image in layer: img = tiled_map.get_tile_image(x, y, 0) # print('x: %s, y: %s, image: %s'%(x, y, img)) # print('width: %s, height: %s'%(img.get_width(), img.get_height())) tile_width = int(img.get_width() * map_scale) tile_height = int(img.get_height() * map_scale) img = pygame.transform.scale(img, (tile_width, tile_height)) surfs.append((x * tile_width, y * tile_height, img)) while True: for e in pygame.event.get(): if e.type == pygame.QUIT: pygame.quit() sys.exit() elif e.type == pygame.VIDEORESIZE: WIDTH = e.w HEIGHT = e.h display = pygame.display.set_mode((WIDTH, HEIGHT),
def __init__(self): filename = self.get_map('level.tmx') # Load data from pyTMX self.tmx_data = pytmx.load_pygame(filename, pixelalpha=True) # Create new data source for pyScroll self.map_data = pyscroll.data.TiledMapData(self.tmx_data)
elements.append( StartButton(100, 100, 64, 64, pygame.image.load("./Assets/UI/play.png"))) # Main Player player_x = 0 player_y = 0 player_width = 64 player_height = 64 objects.append(Player(player_x, player_y, player_width, player_height)) # Left Wall + Right Wall objects.append(Box(-10, 0, 10, display_height)) objects.append(Box(32 * 40, 0, 10, display_height)) # Tiled and Pytmx tiled_map = load_pygame('./Assets/Levels/BasicLevel.tmx') for layer in tiled_map.visible_layers: for x, y, image, in layer.tiles(): if layer.name == "Background": objects.append( Background(x * tiled_map.tilewidth, y * tiled_map.tileheight, tiled_map.tilewidth, tiled_map.tileheight, image)) elif layer.name == "Terrain": objects.append( Ground(x * tiled_map.tilewidth, y * tiled_map.tileheight, tiled_map.tilewidth, tiled_map.tileheight, image)) elif layer.name == "Collectibles": objects.append( Kiwi(x * tiled_map.tilewidth, y * tiled_map.tileheight, tiled_map.tilewidth, tiled_map.tileheight, image))
[15, 4], [16, 4], [17, 4], [18, 4], [19, 4], [20, 4], [21, 4], [12, 8], [13, 8], [14, 8], [15, 8], [17, 8], [18, 8], [19, 8], [20, 8], [12, 12], [13, 12], [14, 12], [15, 12], [17, 12], [18, 12], [19, 12], [20, 12], [12, 16], [13, 16], [14, 16], [15, 16], [15, 18], [15, 19], [16, 19], [17, 19], [18, 19], [19, 19], [20, 19], [6, 6], [6, 7], [8, 6], [8, 7], [4, 6], [4, 7], [4, 3], [4, 4], [6, 3], [6, 4], [8, 3], [8, 4], [7, 19], [6, 19], [5, 19], [4, 19], [3, 19], [2, 19], [1, 19], [0, 19], [0, 20], [0, 21], [0, 22], [0, 23], [0, 24], [0, 25], [0, 26], [0, 27], [0, 28], [0, 29], [1, 29], [2, 29], [3, 29], [4, 29], [5, 29], [6, 29], [7, 29], [7, 28], [7, 27], [7, 26], [7, 25], [7, 24], [7, 23], [7, 22], [7, 21]] flag = [2000, 2000] choice_hero = [26, 11] choice_alien = [[2, 12], [3, 13], [2, 14], [14, 21], [14, 23]] hero = 0 tmxdata = load_pygame("data/map4.tmx") class XCOM: def __init__(self, width, height): self.width = width self.height = height self.board = [[0] * width for _ in range(height)] self.cell_size = 32 def set_view(self, left, top, cell_size): self.left = left self.top = top self.cell_size = cell_size def render(self):
#Load menu images menu_3 = utils.load_image(os.path.join("menus", "menu_3.png")) menu_4 = utils.load_image(os.path.join("menus", "menu_4.png")) menu_3 = (pg.transform.smoothscale(menu_3[0], (screen_width / 2, screen_height / 3)), (0, 0, screen_width / 2, screen_height / 3)) menu_4 = (pg.transform.smoothscale(menu_4[0], (screen_width / 2, screen_height / 3)), (0, 0, screen_width / 2, screen_height / 3)) #Load fonts smallfont = pg.font.Font(os.path.join("data", "fonts", "prstartk.ttf"), 15) medfont = pg.font.Font(os.path.join("data", "fonts", "prstartk.ttf"), 20) largefont = pg.font.Font(os.path.join("data", "fonts", "prstartk.ttf"), 25) #Load the tilemap tile_renderer = load_pygame("dorm.tmx") map_data = pyscroll.data.TiledMapData(tile_renderer) map_layer = pyscroll.BufferedRenderer(map_data, (screen_width, screen_height), clamp_camera=True) #Store blockers rects in a list named blockers for obj in tile_renderer.get_layer_by_name("Blockers"): properties = obj.__dict__ if properties['name'] == 'blocker': x = properties['x'] y = properties['y'] width = properties['width'] height = properties['height'] new_rect = pg.Rect(x, y, width, height) blockers.append(new_rect)
def loadmap( self ): self.map_scene = load_pygame( "Maps/Level2.tmx" ) # load data with Surfaces
import pygame from pytmx.util_pygame import load_pygame pygame.init() screen_width = 1100 screen_height = 700 black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) screen = pygame.display.set_mode([screen_width, screen_height]) tmx_map = load_pygame("track.tmx") pygame.display.set_caption("Don't get caught!!!") clock = pygame.time.Clock() car_img = pygame.image.load('getawaycar.png') car_width = 47 def map_game(): for layer in tmx_map.visible_layers: for x, y, gid, in layer: tile = tmx_map.get_tile_image_by_gid(gid) if tile is None: continue screen.blit(tile, (x * tmx_map.tilewidth, y * tmx_map.tileheight))
def worldmap(game): # Display loading screen until data is loaded with game.load(): # Load map tmx_data = load_pygame("maps/map.tmx") # Map sprites worldmap = Map(game.window, "maps/map.png", 150, 150) worldmap_group = pygame.sprite.Group() worldmap_group.add(worldmap) # Map boundaries(tmx objects) map_objects = solgame.get_objects_from_tmx(tmx_data, Blocks) # Map kingdoms map_named_objects = solgame.get_objects_with_name_from_tmx( tmx_data, Blocks) # Map player images_with_directions = solgame.get_images_with_directions( "sprites/playermap/", 8) map_player = Player(game, "noroi", "noroi", game.WINDOW_WIDTH / 2, game.WINDOW_WIDTH / 2, images_with_directions) # 596 and 296 are coordinates near our Kingdom, WILL CHANGE!! map_player.set_position(596, 296) mp_group = pygame.sprite.Group() mp_group.add(map_player) direction = "down" change_x = 0 change_y = 0 # Events map_on = True while map_on: for event in pygame.event.get(): if event.type == pygame.QUIT: game.quit_game() if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: direction = "down" change_y = 5 if event.key == pygame.K_UP: direction = "up" change_y = -5 if event.key == pygame.K_RIGHT: direction = "right" change_x = 5 if event.key == pygame.K_LEFT: direction = "left" change_x = -5 if event.key == pygame.K_m: return True, "stay" if event.type == pygame.KEYUP: if event.key == pygame.K_DOWN: change_y = 0 if event.key == pygame.K_UP: change_y = 0 if event.key == pygame.K_RIGHT: change_x = 0 if event.key == pygame.K_LEFT: change_x = 0 # for kingdom in KINGDOMS_COORDINATES: # x = KINGDOMS_COORDINATES[kingdom][0] # y = KINGDOMS_COORDINATES[kingdom][1] # if (map_player.rect.x <= x + 5 and map_player.rect.x >= x - 5 and # map_player.rect.y <= y + 5 and map_player.rect.y >= y - 5): # if kingdom == "home": # game.player.set_position(250, 250) # game.player.direction = "down" # return True # Check for bandits bandit_battle = game.encounter_bandits(map_player) if bandit_battle == "win": change_x = 0 change_y = 0 elif bandit_battle == "lose": return True, "stay" # Check if entered any of Kingdoms entered_kingdom = pygame.sprite.spritecollideany( map_player, map_named_objects) if entered_kingdom != None: if len(entered_kingdom.name.split(" ")) > 1: entered_kingdom.name = "_".join( entered_kingdom.name.split(" ")) if entered_kingdom.name == "Tenebrae": return entered_kingdom.name, "leave" elif entered_kingdom.name == "Uwile_Castle": return entered_kingdom.name, "leave" map_player.set_direction() # Draw and update worldmap_group.draw(game.window) mp_group.draw(game.window) map_player.update([map_objects, [], []], direction) # Check if entered the story place story_result = game.entered_story_place("map", map_player) if story_result == False: # This means you lost return True, "lost" try: worldmap.update(map_player, change_x, change_y, map_objects, map_named_objects, game.story.place) except: worldmap.update(map_player, change_x, change_y, map_objects, map_named_objects, None) pygame.display.update() game.clock.tick(game.FPS)
import pygame import sys if __name__ == "__main__": pygame.init() pygame.font.init() pygame.mouse.set_visible(False) pygame.display.set_caption("test") clock = pygame.time.Clock() screen_size = (1024, 700) screen = pygame.display.set_mode(screen_size, pygame.HWSURFACE | pygame.DOUBLEBUF) # Load TMX data tmx_data = load_pygame("sample_map.tmx") for obj in tmx_data.objects: print(obj.name) if not hasattr(obj, "points"): #obj.height #obj.width #obj.x #obj.y obj.__dict__["points"] = [(obj.x, obj.y), (obj.x, obj.y + obj.height), (obj.x + obj.width, obj.y + obj.height), (obj.x + obj.width, 0)] for p in obj.points: print(p)
def start_level(surface): # Code to re-setup the current window surface.fill((0, 0, 0)) # wipe the screen bg = pygame.image.load("img/stage.png").convert() ready_logo = pygame.image.load("img/ready.gif").convert() game_over_logo = pygame.image.load("img/game_over.gif").convert() # set up the music pygame.mixer.music.load('sounds/music/solo_sortie.mp3') # set up sounds victory_tune = pygame.mixer.Sound('sounds/victory.wav') # set up initial sprites hitbox = pygame.sprite.Group() projectiles = pygame.sprite.Group() player = Player(100, 280) # x = 100, y = 280 is the spawn position player.draw(surface) # game settings lives = 3 # player lives, which by default is 3 scroll = True # indicates whether the screen should be scrolled. Since this is a side-scroller game, yes! scroll_x = 0 # indicates the current scroll amount of the background tiled map. The lesser the value, the farther. game_start = True # a flag that is checked before the very first play-through # game pause is caused by user. boss pause is triggered by a game event. game_pause, boss_pause = False, False # flags that pause the game. player_lock = False # locks unit keyboard actions only boss_timer = 0 # a timer that keeps track of the boss's action sequences (see enemy_script.py) boss_pause_timer, win_pause_timer = 0, 0 # timers for pauses caused by game events round_clear = False # a flag for the game to start ending play_win_theme = False # a flag to play the victory theme song enemies = enemy_script.create_enemies(surface, scroll_x) # counters/timers cooldown_counter = 0 # a no-attack sequence/period after the player attacks. rf_counter = 250 # round fail timer after player dies tiled_map = load_pygame( 'tilemap/rtype_tile.tmx' ) # important, as this loads the hitbox of the background. # alpha screen (for smooth fade-in/fade-outs) alpha_surface = pygame.Surface( (800, 600)) # the custom-surface of the size of the alpha screen alpha_surface.fill((0, 0, 0)) alpha = 245 alpha_surface.set_alpha(alpha) while True: # <--- main game loop # Normal Events for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: # enter key game_pause = not game_pause pygame.mixer.Sound('sounds/start.ogg').play() if not game_start and not game_pause: # the following are not needed when the game first starts # Key Events if not player_lock: keys = pygame.key.get_pressed() player_keys_move(surface, player, keys) cooldown_counter = player_keys_shoot(surface, player, keys, projectiles, cooldown_counter) surface.blit( bg, (scroll_x, 0)) # SCROLL the background in +x direction scroll_hitbox(surface, tiled_map, hitbox, scroll_x) # Collisions enemy_handler(surface, player, enemies, hitbox, scroll) update_projectiles(surface, projectiles, hitbox) player.draw(surface) player_handler(surface, player, hitbox, scroll) # UI pygame.draw.rect(surface, BLACK, (0, 560, 800, 40)) for i in range(0, lives): lives_ico = Icon(100 + (i * 30), 565) lives_ico.draw(surface) # Start Round if player.dead or game_start: pygame.mixer.music.stop() rf_counter += 1 if 250 > rf_counter > 200: # fade out alpha += 6 alpha_surface.set_alpha(alpha) elif 300 > rf_counter > 250: scroll_x = 0 # reset scrolling screen scroll = True boss_timer = 0 if not game_start: lives -= 1 # don't deduct life on our first game if lives == 0: alpha_surface.blit(game_over_logo, (surface.get_width() / 2 - game_over_logo.get_width() / 2, surface.get_height() / 2 - game_over_logo.get_height() / 2)) else: alpha_surface.blit( ready_logo, (surface.get_width() / 2 - ready_logo.get_width() / 2, surface.get_height() / 2 - ready_logo.get_height() / 2)) enemies = enemy_script.create_enemies( surface, scroll_x) # spawn/re-spawn new enemies projectiles.empty() rf_counter = 300 elif 400 > rf_counter > 350 and lives > 0: # fade in alpha_surface.fill((0, 0, 0)) alpha -= 6 alpha_surface.set_alpha(alpha) elif rf_counter >= 400 and lives > 0: pygame.mixer.music.load('sounds/music/solo_sortie.mp3') pygame.mixer.music.play(-1, 0.2) # resume music player.respawn() rf_counter = 0 game_start = False elif 600 > rf_counter > 500 and lives == 0: # game over screen alpha_surface.fill((0, 0, 0)) elif rf_counter > 600 and lives == 0: # back to beginning game menu return surface.blit(alpha_surface, (0, 0)) else: if not round_clear: alpha = 0 if not game_start and not game_pause and scroll_x > -5800: scroll_x -= 1 # Scroll the background to the right by decrementing offset scroll_x elif -5850 < scroll_x <= -5800: pygame.mixer.music.fadeout(1000) scroll_x -= 1 elif scroll_x <= -5850: if scroll: pygame.mixer.music.load('sounds/music/boss.mp3') pygame.mixer.music.play() scroll = False boss_pause_timer = 4000 + pygame.time.get_ticks() player_lock = True if pygame.time.get_ticks() >= boss_pause_timer: if player_lock: player_lock = False if not game_pause: boss_timer += 1 if boss_timer > 300: boss_timer = 1 # Enemies follow a script until the stage is cleared (or the game is paused) if not round_clear and not game_pause: round_clear = enemy_script.load(scroll_x, boss_timer, player, enemies, projectiles) if round_clear: if not play_win_theme: player.be_invincible(animation=False) play_win_theme = True pygame.time.wait(1000) victory_tune.play() boss_pause_timer = 6000 + pygame.time.get_ticks() alpha_surface.blit( game_over_logo, (surface.get_width() / 2 - game_over_logo.get_width() / 2, surface.get_height() / 2 - game_over_logo.get_height() / 2)) if pygame.time.get_ticks() >= boss_pause_timer: alpha += 2 alpha_surface.set_alpha(alpha) surface.blit(alpha_surface, (0, 0)) if alpha > 800: return pygame.display.update( ) # Update the display when all events have been processed FPS_CLOCK.tick(FPS)
def __init__(self, map_filename, saved_game=None): pygame.init() self.screen = pygame.display.set_mode(DISPLAY) pygame.display.set_caption("Nautili") self.player = PLAYER1 self.map_filename = map_filename try: self.layers_handler = lh = LayersHandler( load_pygame(os.path.join(MAP_DIR, map_filename + ".tmx")) ) except Exception as ex: print "Unable to read map data. Possibly messed up layers." raise ValueError # Background self.bg_surface = pygame.Surface((MAIN_WIN_WIDTH, MAIN_WIN_HEIGHT), pygame.SRCALPHA).convert_alpha() # Panel self.right_panel = RightPanel(self, (MAIN_WIN_WIDTH - RIGHT_PANEL_WIDTH, MINIMAP_HEIGHT), (RIGHT_PANEL_WIDTH, RIGHT_PANEL_HEIGHT)) self.minimap = MiniMap(self, (MAIN_WIN_WIDTH - MINIMAP_WIDTH, 0), (MINIMAP_WIDTH, MINIMAP_HEIGHT)) self.background = IsometricRenderer(self.layers_handler, self.bg_surface) # Helper variables from layers handler self.sea = lh.sea self.docks = lh.docks self.highlighted_sea = lh.highlighted_sea self.fire = lh.fire self.rocks = lh.rocks self.islands = lh.islands self.wind_type = None self.wind_direction = None self.selected_ship = None self.target_ships = [] # Load game before getting sprites, clickable objects, etc., because loading the game # modifies game layers try: self.load_game(saved_game) except IOError: print "Couldn't load the game" # self.top_panel = TopPanel(self, (0, 0), (TOP_PANEL_WIDTH, TOP_PANEL_HEIGHT)) self.all_sprites = lh.get_all_sprites() self.clickable_objects_list = lh.get_clickable_objects() self.ships = lh.ships self.yellow_ships = lh.yellow_ships self.green_ships = lh.green_ships self.yellow_ports = lh.yellow_ports self.green_ports = lh.green_ports self.ports = lh.ports self.neutral_ports = filter(lambda s: s.player == NEUTRAL_PLAYER, self.ports) self.yellow_royal_ports = lh.yellow_royal_ports self.green_royal_ports = lh.green_royal_ports self.royal_ports = lh.royal_ports # Initial game variables state self._paused = False # Prepare rendering self.background.fill(colors.BACKGROUND_COLOR) # fill with water color self.background.add(self.sea + self.docks + self.rocks + self.islands) self.map_width, self.map_height = self.layers_handler.get_map_dimensions() # Move camera to first yellow royal port yellow_port = self.yellow_royal_ports[0] port_coords = map(lambda x: -x, self.layers_handler.isometric_to_orthogonal(*yellow_port.coords())) self.move_camera((port_coords[0] + MAIN_WIN_WIDTH / 2, port_coords[1] + MAIN_WIN_HEIGHT / 2)) # self._cursor_default = pygame.mouse.get_cursor() self._cursor_close_hand = self._cursor_default self.setup_cursors() self.yellow_docks = [] self.green_docks = [] self.yellow_royal_docks = [] self.green_royal_docks = [] self.update_player_docks() self.win_menu = PauseMenu(self.screen, "Yellow won!", color=colors.GREEN)
def __init__(self, filename): tm = load_pygame(filename, pixelalpha=True) self.width = tm.width * tm.tilewidth self.height = tm.height * tm.tileheight self.tmxdata = tm
def __init__(self): self.mainPlayer = Player("player") self.worldMap = load_pygame(getFile("level")) self.start()
# Eka peli 0.3 # # # platformer made with pygame import pygame import config import classes from pygame.locals import * from config import * from classes import * import random import sys # sys-module will be needed to exit the program import pytmx from pytmx.util_pygame import load_pygame tiled_map = load_pygame("levels/level1.tmx") pygame.init() pygame.display.set_caption("D4 gäng") # Load static images # function for easier visualisation # draws a grid for tiles def drawGrid(): for line in range(0,11): pygame.draw.line(windowGame, (255,255,255), (0, line * tileSize), (windowWidth, line * tileSize)) pygame.draw.line(windowGame, (255,255,255), (line * tileSize, 0), (line * tileSize, windowHeight))
def __init__(self): filename = self.get_map('level.tmx') #load data from pyTMX self.tmx_data = pytmx.load_pygame(filename, pixelalpha=True) #create new data source for pyScroll self.map_data = pyscroll.data.TiledMapData(self.tmx_data)
def preview_new_map(map_name): #Map - This is loading the Tiled Map Editor map we used. tmxdata = load_pygame(map_name, pixelalpha=True) return tmxdata
def tmx_data(self): return load_pygame(self.map_path)
import pytmx import pygame from pytmx.util_pygame import load_pygame pygame.init() SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 SCREEN = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) pygame.display.set_caption("Base code") clock = pygame.time.Clock() tiled_map = load_pygame('resources/level6.tmx', pixelalpha=True) tilewidth = tiled_map.tilewidth tileheight = tiled_map.tileheight player = pygame.image.load('resources/coin.png').convert_alpha() player = pygame.transform.scale(player, (48, 48)) def events(): for event in pygame.event.get(): if event.type == pygame.QUIT: return True for layer in tiled_map.layers: if isinstance(layer, pytmx.TiledTileLayer): for x, y, tile in layer.tiles(): if tile: SCREEN.blit( tile, [(x * tilewidth) - CAMERA.x + (SCREEN_WIDTH / 2),
def load_tmx_map(filename): tmx_data = load_pygame(filename) return tmx_data
red = (255, 0, 0) green = (0, 255, 0) # screen sizes tile_size = 32 tiles = 16 display_width = (tile_size * tiles) display_height = (tile_size * tiles) # Init pygame.init() gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('2D Game') clock = pygame.time.Clock() tiled_map = load_pygame('Maps/test.tmx') background = (tiled_map.get_layer_by_name("Background"), False) scene = (tiled_map.get_layer_by_name("Scene"), True) obj = tiled_map.get_layer_by_name("Objects") class GameObjects(pygame.sprite.Sprite): def __init__(self, id, pos, image): pygame.sprite.Sprite.__init__(self) self.id = id self.image = image self.rect = self.image.get_rect() self.rect.x, self.rect.y = pos def draw(self): gameDisplay.blit(self.image, (self.rect.x, self.rect.y))
def load(self, filename): """Load map data from a tmx map file and get all the map's events and collision areas. Loading the map data is done using the pytmx library. Specifications for the TMX map format can be found here: https://github.com/bjorn/tiled/wiki/TMX-Map-Format :param filename: The path to the tmx map file to load. :type filename: String :rtype: None :returns: None **Examples:** In each map, there are three types of objects: **collisions**, **conditions**, and **actions**. Here is how an action would be defined using the Tiled map editor: .. image:: images/map/map_editor_action01.png Here is an example of how we use pytmx to load the map data from a tmx file and what those objects would look like after loading: >>> tmx_data = pytmx.TiledMap("pallet_town-room.tmx") >>> for obj in tmx_data.objects: ... pprint.pprint(obj.__dict__) ... {'gid': 0, 'height': 32, 'name': None, 'parent': <TiledMap: "../tuxemon/resources/maps/pallet_town-room.tmx">, 'rotation': 0, 'type': 'collision', 'visible': 1, 'width': 16, 'x': 160, 'y': 48} {'action_id': '9', 'condition_type': 'player_at', 'gid': 0, 'height': 16, 'id': 9, 'name': 'Start Combat', 'operator': 'is', 'parameters': '1,11', 'parent': <TiledMap: "../tuxemon/resources/maps/pallet_town-room.tmx">, 'rotation': 0, 'type': 'condition', 'visible': 1, 'width': 16, 'x': 16, 'y': 176} {'action_type': 'teleport', 'gid': 0, 'height': 16, 'id': 5, 'name': 'Go Downstairs', 'parameters': 'test.tmx,5,5', 'parent': <TiledMap: "../tuxemon/resources/maps/pallet_town-room.tmx">, 'priority': '1', 'rotation': 0, 'type': 'action', 'visible': 1, 'width': 16, 'x': 0, 'y': 0} """ # Load the tmx map data using the pytmx library. self.filename = filename # Scale the loaded tiles if enabled if prepare.CONFIG.scaling == "1": self.data = pytmx.TiledMap(filename, image_loader=scaled_image_loader, pixelalpha=True) self.data.tilewidth, self.data.tileheight = prepare.TILE_SIZE else: self.data = load_pygame(filename, pixelalpha=True) # make a scrolling renderer self.renderer = self.initialize_renderer() # Get the map dimensions self.size = self.data.width, self.data.height # Get the tile size of the map self.tile_size = self.data.tilesets[0].tilewidth, self.data.tilesets[ 0].tileheight # Load all objects from the map file and sort them by their type. for obj in self.data.objects: if obj.type == 'collision': self.collisions.append(obj) elif obj.type == 'collision-line': self.collision_lines.append(obj) elif obj.type == 'event': self.events.append(self.loadevent(obj)) elif obj.type == 'init': self.inits.append(self.loadevent(obj)) elif obj.type == 'interact': self.interacts.append(self.loadevent(obj))