Esempio n. 1
0
 def load_location_piece():
     location_pieces = {
         0: pytmx.load_pygame('res\\t0.tmx'),
         1: pytmx.load_pygame('res\\t1.tmx'),
         2: pytmx.load_pygame('res\\t2.tmx')
     }
     return location_pieces
Esempio n. 2
0
 def __init__(self, paths):
     self.path = ""
     for path in paths:
         try:
             pytmx.load_pygame(path, pixelalpha=True)
         except:
             pass
         else:
             self.path = path
             break
     self.tm = pytmx.load_pygame(self.path, pixelalpha=True)
     self.width = self.tm.width * self.tm.tilewidth
     self.height = self.tm.height * self.tm.tileheight
Esempio n. 3
0
    def __init__(self, gameScreen):
        self.gameMap = pytmx.load_pygame("Map/tileMaps/world.tmx",
                                         pixelalpha=True)
        self.width = self.gameMap.width
        self.height = self.gameMap.height
        self.screenSize = gameScreen.get_size()
        self.tileSize = 48
        self.collisionRects = []
        self.minigamePortal = []
        self.informationTiles = []
        self.destinations = {}
        self.universities = []
        self.teleports = []
        self.npc = []

        self.bank = []
        self.slotmachine = []

        for r in self.gameMap.get_layer_by_name("Collision"):
            self.collisionRects.append(pygame.Rect(r.x, r.y, r.width,
                                                   r.height))

        self.start = (self.gameMap.get_layer_by_name("Start")[0].x,
                      self.gameMap.get_layer_by_name("Start")[0].y)

        for p in self.gameMap.get_layer_by_name("Destination"):
            self.destinations[p.name] = (p.x, p.y)

        for p in self.gameMap.get_layer_by_name("InformationTiles"):
            self.informationTiles.append((pygame.Rect(p.x, p.y, p.width,
                                                      p.height), p.name))

        for p in self.gameMap.get_layer_by_name("Education"):
            self.universities.append((pygame.Rect(p.x, p.y, p.width,
                                                  p.height), p.name))

        for p in self.gameMap.get_layer_by_name("Bank"):
            self.bank.append((pygame.Rect(p.x, p.y, p.width, p.height),
                              self.gameMap.get_tile_image_by_gid(p.gid)))

        for p in self.gameMap.get_layer_by_name("Slotmachine"):
            self.slotmachine.append(
                (pygame.Rect(p.x, p.y, p.width, p.height),
                 self.gameMap.get_tile_image_by_gid(p.gid)))

        for p in self.gameMap.get_layer_by_name("Portal"):
            if p.type == "Minigame":
                self.minigamePortal.append(
                    (pygame.Rect(p.x, p.y, p.width, p.height), p.name))
            elif p.type == "Teleport":
                self.teleports.append(
                    (pygame.Rect(p.x, p.y, p.width,
                                 p.height), self.destinations[p.name]))

        for p in self.gameMap.get_layer_by_name("npcLayer"):
            self.npc.append(
                npc(self.gameMap.get_tile_image_by_gid(p.gid),
                    pygame.Rect(p.x, p.y, p.width, p.height), p.type))
            self.collisionRects.append(pygame.Rect(p.x, p.y, p.width,
                                                   p.height))
Esempio n. 4
0
    def __init__(self, screen):
        super().__init__()
        self.filename = 'assets/maps/map.tmx'
        self.game_map = pytmx.load_pygame(
            os.path.join(current_dir, self.filename))
        self.screen = screen

        self.tw = self.game_map.tilewidth
        self.th = self.game_map.tileheight
        self.tw_count = self.game_map.width
        self.th_count = self.game_map.height
        self.width = self.tw * self.tw_count
        self.height = self.th * self.th_count

        self.tiles = []
        self.tree_top_tiles = []
        self.objects = {'terrain': [], 'bushes': [], 'rocks': [], 'other': []}
        self.shaders = []
        self.tile_group = pygame.sprite.Group()
        self.object_group = pygame.sprite.Group()
        self.tree_tops = pygame.sprite.Group()

        self.crafting = {
            'wood': [[500, 300]],
            'stone': [[550, 325]],
            'ore': [[600, 350]]
        }
        self.crafting_group = pygame.sprite.Group()

        self.camera = m.Camera(self.width, self.height)
        self.set_layers()
Esempio n. 5
0
def place_tiles(filename, xwindow, ywindow):#add x and y offset here too.
	#when placex equals screen size restart placex and add 32 to placey
	tmxdata = load_pygame("{}\{}".format(imagelocation, filename))
	tilex = 0#the tile being placed
	tiley = 0
	placex = 0#the location where the tile is being placed
	placey = 0
	tiles = True
	while tiles:#while there are still tiles
		image = (tmxdata.get_tile_image(tilex, tiley, 0))
		window.blit(image, [placex, placey])
		if placey == (ywindow-32) and placex == (xwindow-32):
			tiles = False
		elif placex == (xwindow-32):
			placey += 32
			tilex = 0
			tiley += 1
			placex = 0
		else:
			tilex += 1
			placex += 32
	return_rects = []
	for rect in (pytmx.util_pygame.build_rects(tmxdata, "Collision layer", tileset = None, real_gid=None)):
		return_rects.append(rect)
	return(return_rects)
Esempio n. 6
0
 def __init__(self, filename, free_tile, hero):
     self.map = pytmx.load_pygame(f"maps/{filename}")
     self.height = self.map.height
     self.width = self.map.width
     self.tile_size = self.map.tilewidth
     self.free_tile = free_tile
     self.hero = hero
Esempio n. 7
0
	def __init__(self, map_file_location, map_to_load, player_object):
		super(map, self).__init__()
		pygame.sprite.Sprite.__init__(self)
		#ONLY LOADS bottom layer right now
		self.locate,self.map_load = map_file_location,map_to_load
		self.tmxdata = load_pygame("{}\{}".format(map_file_location, map_to_load))
		
		self.player_object = player_object
		
		self.world_shift_x = 0
		self.world_shift_y = 0
		
		self.left_viewbox = xwindow/2 - xwindow/8
		self.right_viewbox = xwindow/2 + xwindow/8
		self.top_viewbox = ywindow/2 - ywindow/8
		self.bottom_viewbox = ywindow/2 + ywindow/8
		
		self.x_moved = 0
		self.y_moved = 0
		
		self.placex = 0
		self.placey = 0
		
		self.xtilestart = 0
		self.ytilestart = 0	
Esempio n. 8
0
    def __init__(self, map_path, layer, window_width, window_height):

        tmx_data = pytmx.load_pygame(map_path)

        self.width = int(tmx_data.width * tmx_data.tilewidth)
        self.height = int(tmx_data.height * tmx_data.tileheight)

        self.start_pos = []     # start pos is maar één rect, maar moet in een list staan ivm updaten
        self.trees = []         # een lijst van rects van alle bomen
        self.waters = []
        self.heroes = []
        self.obstacles = []
        self.low_obst = []

        for rect in tmx_data.get_layer_by_name("trees"):
            self.add_rect_to_list(rect, self.trees)   # vul die lijst van rects van alle bomen
            self.add_rect_to_list(rect, self.obstacles)

        for rect in tmx_data.get_layer_by_name("water"):
            self.add_rect_to_list(rect, self.waters)
            self.add_rect_to_list(rect, self.low_obst)

        map_data = pyscroll.data.TiledMapData(tmx_data)
        map_layer = pyscroll.BufferedRenderer(map_data, (window_width, window_height), clamp_camera=True)
        self.group = pyscroll.PyscrollGroup(map_layer=map_layer, default_layer=layer)

        self._grid = Grid(self.width, self.height, TILESIZE, GRIDLAYER)
        self._infol = []     # info list, list van classes zoals grid
        self._infob = False  # info boolean
Esempio n. 9
0
 def __init__(self, filename):
     tilemap_data = pytmx.load_pygame(filename, pixelalpha=True)
     self.width = tilemap_data.width * tilemap_data.tilewidth
     self.height = tilemap_data.height * tilemap_data.tileheight
     self.image = pg.Surface((self.width, self.height), pg.SRCALPHA)
     self.rect = self.image.get_rect()
     self.tilemap_data = tilemap_data
Esempio n. 10
0
    def drawTerrain(self):
        self.Blocked = []
        tmxdata = load_pygame("main.tmx")
        self.levelWin = pygame.Surface((3200, 3200))
        for x in range(100):
            for y in range(100):
                image = tmxdata.get_tile_image(x, y, 0)

                self.levelWin.blit(image, (x * 32, y * 32))
        for x in range(100):
            for y in range(100):
                try:
                    image = tmxdata.get_tile_image(x, y, 1)
                    self.levelWin.blit(image, (x * 32, y * 32))
                except:
                    pass
        for x in range(100):
            for y in range(100):
                image = tmxdata.get_tile_image(x, y, 2)

                try:
                    self.levelWin.blit(image, (x * 32, y * 32))
                    self.Blocked.append(
                        (math.floor((x * 32 + self.camera_x) / 32),
                         math.floor((y * 32 + self.camera_y) / 32)))

                except:
                    pass

                # self.gameWin.blit(image, (self.camera_x,self.camera_y))
                # print (image)
        # self.friend.render(self.levelWin, (10 * 32, 10 * 32))
        self.gameWin.blit(self.levelWin, (self.camera_x, self.camera_y))
Esempio n. 11
0
 def __init__(self, filename):
     tm = pytmx.load_pygame(filename, pixelalpha=True)
     self.width = tm.width * tm.tilewidth
     self.height = tm.height * tm.tileheight
     self.tmxdata = tm
     self.players = pytmx.TiledImageLayer
     self.objects = pytmx.TiledImageLayer
Esempio n. 12
0
 def __init__(self, filename):
     tm = pytmx.load_pygame(filename, pixelalpha=True)
     # width is how many tiles across and tilewidth is how many pixels across each tile is
     self.width = tm.width * tm.tilewidth
     #height is how many tiles down and tile height is how many pixels high each tile is
     self.height = tm.height * tm.tileheight
     self.tmxdata = tm
Esempio n. 13
0
	def __init__(self, map_file_location, map_to_load, player_object):
		super(map, self).__init__()
		pygame.sprite.Sprite.__init__(self)
		#ONLY LOADS bottom layer right now
		self.locate,self.map_load = map_file_location,map_to_load
		self.tmxdata = load_pygame("{}\{}".format(map_file_location, map_to_load))
		
		self.player_object = player_object
		
		self.world_shift_x = 0
		self.world_shift_y = 0
		
		self.left_viewbox = 256
		self.right_viewbox = 544
		self.top_viewbox = 224
		self.bottom_viewbox = 416
		
		self.x_moved = 0
		self.y_moved = 0
		
		self.placex = 0
		self.placey = 0
		
		self.xtilestart = 725#where the map starts generating based on tiles.  limit x is 0-800
		self.ytilestart = 200#where the map starts generating based on y.  Limit is 0-640
Esempio n. 14
0
    def __init__(self, filename):
        tm = pytmx.load_pygame(filename, pixlealpha=True)

        self.width = tm.width * tm.tilewidth
        self.height = tm.height * tm.tileheight

        self.tmxdata = tm
Esempio n. 15
0
 def __init__(self, filename, free_tile, finish_tile):
     self.map = pytmx.load_pygame(f"{MAPS_DIR}/{filename}")
     self.height = self.map.height
     self.width = self.map.width
     self.tile_size = self.map.tilewidth
     self.free_tiles = free_tile
     self.finish_tile = finish_tile
Esempio n. 16
0
def load_lvl():
    map_tmx = pytmx.load_pygame('map/Test_map.tmx')
    tile_height = map_tmx.height
    tile_width = map_tmx.width
    for y in range(tile_height):
        for x in range(tile_width):
            tiled = map_tmx.get_tile_image(x, y, 0)
            tiled1 = map_tmx.get_tile_image(x, y, 1)
            if tiled is not None:
                Platform(platforms, x, y, tiled)
            if tiled1 is not None:
                Landing(land, x, y, tiled1)

    m_layer = map_tmx.get_layer_by_name('Monsters')
    for m in m_layer:
        Monsters(monsters, m.x, m.y, m.u_l, m.r_d, m.move_direct, m.image)

    h_layer = map_tmx.get_object_by_name('Knight')
    Player(players, h_layer.pos_x, h_layer.pos_y, h_layer.image)

    c_layer = map_tmx.get_layer_by_name('Coins')
    for c in c_layer:
        Coin(coins, c.x, c.y, c.image)

    ch_layer = map_tmx.get_layer_by_name('Chest')
    for ch in ch_layer:
        Chest(chests, ch.x, ch.y, ch.image, ch.secret)

    f_layer = map_tmx.get_layer_by_name('Finish')
    for f in f_layer:
        Finish(finish, f.x, f.y, f.image)
Esempio n. 17
0
    def __init__(self, filename, tileProportion):
        tiledMap = pytmx.load_pygame(filename, pixelalpha=True)
        self.tileWidth = tiledMap.tilewidth
        self.tileHeight = tiledMap.tileheight
        print(tileProportion)
        print(self.tileWidth)
        self.scale = int(tileProportion / self.tileWidth)
        self.tmxdata = tiledMap
        try:
            self.id = tiledMap.properties['gameId']
            print(self.id)
        except:
            print("no Id")
        self.width = (tiledMap.width * self.scale) * tiledMap.tilewidth
        self.height = (tiledMap.height * self.scale) * tiledMap.tileheight
        self.rect = pygame.Rect(0, 0, self.width, self.height)
        self.framed = False

        self.walls = []
        self.sprites = []
        self.doors = []
        self.triggers = []

        # self.fullArt =

        self.image = pygame.Surface((self.width, self.height))
        self.load()
        self.image  # .convert()

        self.x = 0
        self.y = 0

        self.dialogue = False

        self.events = []
Esempio n. 18
0
    def rendermap(self):
        self.map = pytmx.load_pygame('Maps/3Dtest.tmx')
        self.cubes = []
        cb = 0
        rects = []
        for y in range(0, self.map.height):
            for x in range(0, self.map.width):
                t = self.map.get_tile_properties(x, y, 0)
                if t != None:
                    #image = self.map.get_tile_image_by_gid(gid)/2
                    #image.convert()
                    t = t['TYPE'].upper()

                    if t == 'GRASS': z = 0
                    if t == 'WALL': z = 2
                    '''if len(rects) > 1:
						if rects[cb - 1][0] == ((x * 2) - 2) and rects[cb -1][4] == z: rects[cb - 1][2] += 2
						else: rects.append([x * 2,y * 2,2,2,z])
					else: rects.append([x * 2,y * 2,2,2,z])'''
                    rects.append([x * 2, y * 2, 2, 2, z])
            cb += 1
        for r in rects:
            vertex = []
            for vz in (r[4], r[4] + 2):
                for vy in (r[1], r[1] + r[3]):
                    for vx in (r[0], r[0] + r[2]):
                        vertex.append([vx, vz, vy])
            self.cubes.append(vertex)
Esempio n. 19
0
 def __init__(self, filename):
     tm = pytmx.load_pygame(
         filename, pixelalpha=True
     )  # carrega um arquivo .tmx (pixelapha pra ter transparencia)
     self.width = tm.width * tm.tilewidth  # largura e altura do mapa
     self.height = tm.height * tm.tileheight
     self.tmxdata = tm
Esempio n. 20
0
 def __init__(self, name, game, player=None):
     filename = path.join(path.dirname(__file__), 'maps', name + '.tmx')
     self.map = pytmx.load_pygame(filename, pixelAlpa=True)
     self.width = self.map.width  # in tiles
     self.height = self.map.height  # in tiles
     self.game = game
     self.tile_size = game.tile_size
     #
     # sprite groups
     self.characters = pygame.sprite.Group()
     self.obstacles = pygame.sprite.Group()
     self.interacts = pygame.sprite.Group()
     self.exits = pygame.sprite.Group()
     if player is not None:
         self.characters.add(player)
     #
     # messages
     self.messages = game.messages
     #
     # sprites
     self._load_npcs(name)
     self._load_exits()
     #
     # images
     self.overhead, self.underfoot = self._render()
Esempio n. 21
0
 def __init__(self, filename):
     tm = pytmx.load_pygame(filename, pixelalpha=True)
     self.width = tm.width * tm.tilewidth
     self.height = tm.height * tm.tileheight
     self.tmxdata = tm
     self.image = self.make_map()
     self.rect = self.image.get_rect()
Esempio n. 22
0
    def _init_map(self):
        """
        Laad de tmx data en maak daaruit een group variabele.
        Maak een grid aan en een map.
        Vul bomen, waters en obstacles.
        """
        tmx_data = pytmx.load_pygame(MAPPATH)
        map_data = pyscroll.data.TiledMapData(tmx_data)
        map_layer = pyscroll.BufferedRenderer(map_data, (WINDOWWIDTH, WINDOWHEIGHT), clamp_camera=True)
        self.group = pyscroll.PyscrollGroup(map_layer=map_layer, default_layer=PLAYERLAYER)

        self.grid_sprite = GridSprite(tmx_data.width * tmx_data.tilewidth,
                                      tmx_data.height * tmx_data.tileheight,
                                      GRIDSIZE, GRIDLAYER)

        self.map1 = Map(tmx_data)

        for rect in tmx_data.get_layer_by_name("trees"):
            self.map1.add_rect_to_list(rect, self.map1.tree_rects)
            self.map1.add_rect_to_list(rect, self.map1.obstacle_rects)
        for rect in tmx_data.get_layer_by_name("water"):
            self.map1.add_rect_to_list(rect, self.map1.water_rects)
            self.map1.add_rect_to_list(rect, self.map1.low_obst_rects)
        for rect in tmx_data.get_layer_by_name("warphole"):
            self.map1.warphole_rect = pygame.Rect(rect.x, rect.y, rect.width, rect.height)
Esempio n. 23
0
    def __init__(self):
        super(Intro, self).__init__()

        tmx_data = load_pygame(MAP['intro'])

        map_data = pyscroll.data.TiledMapData(tmx_data)
        self.map_layer = pyscroll.BufferedRenderer(map_data, SCREEN_SIZE)
        self.map_layer.zoom = 0.5

        self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=2)

        self.animations = pg.sprite.Group()
        self.labels = pg.sprite.Group()
        self.letters = pg.sprite.Group()
        self.surface = GFX['intro'].convert_alpha()
        self.cheat = False


        timespan = 3000
        midbottom = (SCREEN_RECT.centerx, SCREEN_RECT.bottom - 20)
        font = FONTS["UbuntuMono-B"]
        self.prompt = Blinker("Press Enter key to continue", {"midbottom": midbottom},
                              500, text_color=(255, 255, 255), font_path=font,
                              font_size= 25)
        Label('UP-UP-DOWN-DOWN-LEFT-RIGHT-LEFT-RIGHT-B-A',{"topleft": (50, 0)},self.labels,font_path=font,font_size = 7)
        task = Task(self.labels.add, timespan, args=(self.prompt,))
        self.animations.add(task)
Esempio n. 24
0
 def __init__(self, filename):
     tm = pytmx.load_pygame(
         filename, pixelalpha=True
     )  # pytmx is just for reading tiled map, we use pixelalpha for transparency that goes with our tiles
     self.width = tm.width * tm.tilewidth  # 50 * 64
     self.height = tm.height * tm.tileheight
     self.tmxdata = tm
Esempio n. 25
0
    def __init__(self, filename):
        tmx_data = load_pygame(os.path.join(os.getcwd(), "map", filename))
        self._mapwidth_tiles = tmx_data.width
        self._mapheight_tiles = tmx_data.height
        self._mapwidth = tmx_data.width * 32
        self._mapheight = tmx_data.height * 32
        self._map_layers = tmx_data.layers
        self._outdoors = tmx_data.outdoors

        self._water_matrix = np.zeros(
            (self._mapwidth_tiles, self._mapheight_tiles))
        self._collision_object_matrix = np.zeros(
            (self._mapwidth_tiles, self._mapheight_tiles))
        self._bridge_matrix = np.zeros(
            (self._mapwidth_tiles, self._mapheight_tiles))

        self._ground_surf = pygame.Surface((self._mapwidth, self._mapheight))
        self._c_object_surfs = []  # collision objects on the map
        self._m_object_surfs = {
        }  # non-collision objects on the map (M-objects)
        self._bridge_surf = pygame.Surface((self._mapwidth, self._mapheight),
                                           pygame.SRCALPHA)
        self._above_surf = pygame.Surface((self._mapwidth, self._mapheight),
                                          pygame.SRCALPHA)
        self._triggers = {}

        self._collision_hitboxes = []
        self._water_hitboxes = []

        self._stored_npcs = []
        self._stored_loot = []
        self._stored_player_position = (0, 0)
        self._stored_camera_positon = (0, 0)

        self.load_layers(filename, tmx_data)
Esempio n. 26
0
def loadTmxFromFile(fileName):
    """
    Loads a TMX file
    :param fileName: name/path of file
    :return: TMX object
    """
    return pytmx.load_pygame(fileName, pixelalpha=True)
Esempio n. 27
0
def load_map(map_file: str):
    """
    Returns loaded map

    :return tmx map_data:
    """
    map_data = pytmx.load_pygame(map_file)
    return map_data
Esempio n. 28
0
 def __init__(self, filename, scale=1):
     self.tm = pytmx.load_pygame(filename, pixelalpha=True)
     self.width = self.tm.width * self.tm.tilewidth
     self.height = self.tm.height * self.tm.tileheight
     self.scale = scale
     if scale > 1:
         self.width *= scale
         self.height *= scale
Esempio n. 29
0
 def __init__(self, filename):
     # Loading the tiledmap file
     tiledmap = pytmx.load_pygame(
         filename,
         pixelalpha=True)  # pixelalpha = True for transparent background
     self.width = tiledmap.width * tiledmap.tilewidth  # width is how many tiles and tilewidth is how many pixels wide is each tile
     self.height = tiledmap.height * tiledmap.tileheight
     self.tmx_data = tiledmap  # Storing the map in a local var.
Esempio n. 30
0
 def __init__(self, filename):
     tm = pytmx.load_pygame(
         filename, pixelalpha=True)
     self.width = tm.width * tm.tilewidth
     self.height = tm.height * tm.tileheight
     self.tmxdata = tm
     self.RayWalls = []
     self.setLimits()
Esempio n. 31
0
 def __init__(self, game, filename):
     tm = pytmx.load_pygame(filename, pixelalpha=True)
     self.width = tm.width * tm.tilewidth
     self.height = tm.height * tm.tileheight
     self.tmxdata = tm
     self.game = game
     self.path = []
     self.tower_foundations_pos = []
Esempio n. 32
0
 def __init__(self, filename):
     '''
     Load the map, create the corresponding map size in the game
     '''
     tm = pytmx.load_pygame(filename, pixelalpha=True)
     self.width = tm.width * tm.tilewidth
     self.height = tm.height * tm.tileheight
     self.tmxdata = tm
Esempio n. 33
0
 def __init__(self, filename, DATAFILE):
     self.dict_tiles = {}
     self.map = load_pygame(f"{DATAFILE}/{filename}")
     self.height = self.map.height
     self.width = self.map.width
     self.tile_height = self.map.tileheight
     self.tile_width = self.map.tilewidth
     self.tile_images_coordinates = {}
Esempio n. 34
0
 def __init__(self, filename, screen):
     self.filename = self.load_data(filename)
     self.tmx_data = pytmx.load_pygame(self.filename, pixelalpha=True)
     self.width = self.tmx_data.width * self.tmx_data.tilewidth
     self.height = self.tmx_data.height * self.tmx_data.tileheight
     self.screen = screen
     self.map_img = self.make_map()
     self.object_tiles = self.get_objects_tiles()
Esempio n. 35
0
	def __init__(self, filename):
		"""
		:param str filename: The name of the file you want to renderer.
		"""
		tm = pytmx.load_pygame(filename, pixelalpha=True)
		self.size = tm.width * tm.tilewidth, tm.height * tm.tileheight
		self.tmx_data = tm
		self.tmx_layers = tm.all_layers
Esempio n. 36
0
 def __init__(self, filename):
     tm  = pytmx.load_pygame(filename, pixelalpha=True)
     self.width = tm.width * tm.tilewidth
     self.height = tm.height * tm.tileheight
     self.tmxdata = tm
     self.matrix = [[0 for x in range(tm.width)] for y in range(tm.height)]
     self.blue_spawns = []
     self.red_spawns = []
Esempio n. 37
0
 def load(self, filename):
     self.tmx = pytmx.load_pygame('%s.tmx' % filename, pixelalpha=True)
     self.properties = {}
     for e in self.tmx:
         self.properties.update(e.properties)
     self.tmap = pyscroll.TiledMapData(self.tmx)
     self.map_layer = pyscroll.BufferedRenderer(self.tmap, size)
     self.group = pyscroll.PyscrollGroup(map_layer=self.map_layer)
     return self
Esempio n. 38
0
    def __init__(self,player,map_name,ctrl,sounds):
        '''Init
        input: player - Player object
               map_name - .tmx-map filename string
               ctrl - Controller object
               sounds - Audio object
        output: none
        '''
        self.player = player
        self.controller = ctrl
        self.sounds = sounds
        self.character_list = pg.sprite.Group()
        self.character_list.add(self.player)
        self.has_level_just_changed=True
    	#TODO: Take these values from actual screen size!
    	self.screen_size = (800,600)
    	self.scroll_rect = pg.Rect(200,200,400,200)
        
        #Load the map
        self.tmx_map = pytmx.load_pygame(os.path.join(os.path.dirname(__file__),map_name), pixelalpha=True)
        self.level_size=[self.tmx_map.width*self.tmx_map.tilewidth,self.tmx_map.height*self.tmx_map.tileheight]
        self.camera_position=[0,0]

        #get obstacles
        self.obstacles=pg.sprite.Group()
        for i in self.tmx_map.objectgroups[0]:
            self.obstacles.add(Obstacle(i,self.tmx_map,self.camera_position))

        #Get items in the level
        self.item_list=pg.sprite.Group()
        for i in self.tmx_map.objectgroups[1]:
            self.item_list.add(Item(i,self.tmx_map,self.camera_position))

        #Get the level changers
        self.level_changers=pg.sprite.Group()
        for i in self.tmx_map.objectgroups[2]:
            self.level_changers.add(LevelChanger(i,self.tmx_map,self.camera_position))

        #Get interactable events (TODO: generalize to all events)
        self.events_interactable=pg.sprite.Group()
        for i in self.tmx_map.objectgroups[3]:
            new_event=Event(i,self.tmx_map,self.camera_position)
            if(new_event.properties['type']=='interact'):
                self.events_interactable.add(new_event)           

        #Get the characters
        for i in self.tmx_map.objectgroups[4]:
            texts=[]
            for j in i.__dict__:
                if j[0:len(j)-1]=="text":
                    texts.append(i.__dict__[j])
            self.character_list.add(NPC(i.name,texts,[i.x,i.y],self.camera_position))
Esempio n. 39
0
 def load_all_maps(self):
     """..."""
     map_path = 'resources/maps/'
     Console.load_all_maps()
     try:
         # noinspection PyTypeChecker
         for map_name in MapTitle:
             map_name.value.append(pytmx.load_pygame(map_path + map_name.name + '.tmx'))
     except pygame.error:
         # bij het sluiten van het spel voordat alle kaarten geladen zijn.
         pass
     self.all_maps_loaded = True
     Console.maps_loaded()
Esempio n. 40
0
    def _initialize(self):
        import pytmx
        import pyscroll.data

        tmx_data = pytmx.load_pygame(self.map_path)
        self.map_data = pyscroll.data.TiledMapData(tmx_data)

        self.width = int(tmx_data.width * tmx_data.tilewidth)
        self.height = int(tmx_data.height * tmx_data.tileheight)

        for rect in tmx_data.get_layer_by_name("trees"):
            self.add_rect_to_list(rect, self.trees)   # vul die lijst van rects van alle bomen
            self.add_rect_to_list(rect, self.obstacles)

        for rect in tmx_data.get_layer_by_name("water"):
            self.add_rect_to_list(rect, self.waters)
            self.add_rect_to_list(rect, self.low_obst)
Esempio n. 41
0
    def buffLvl(self,lvl='lvl1.tmx'):
        self.tmx=pytmx.load_pygame(lvl, pixelalpha=True)
        
        self.lvlSurf=pygame.Surface((64*100,64*100))
        self.lvlSurf.fill(self.bg)

        for k in range(10):
            for i in range(100):
                for j in range(100):
                    try:
                        img=self.tmx.getTileImage(i,j,k)
                        
                        self.lvlSurf.blit(img,(3200+32*(i-j),1616+16*(i+j)-img.get_height())) 
                    except AttributeError:
                        pass
                    except TypeError:
                        pass
                    except ValueError:
                        pass
Esempio n. 42
0
	def __init__(self): 

		self.PLAYER_MOVE_SPEED = 200
		self.screen = init_screen(800, 600)

		#load data from pytmx
		self.tmx_data = pytmx.load_pygame(self.filename)

		w, h = self.screen.get_size()

		#create new data source for pyscroll
		map_data = pyscroll.data.TiledMapData(self.tmx_data)

		self.map_layer = pyscroll.BufferedRenderer(map_data, (w / 2, h / 2), clamp_camera=True)

		self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=0)

		#setup level with pygame rects
		self.blockers = list()
		#self.enemies = dict()
		#self.index = 0
		for object in self.tmx_data.objects:

			if "blockers" in object.properties:
				if object.properties["blockers"] == "1":
					self.blockers.append(pygame.Rect(object.x, object.y, object.width, object.height))
			if object.name == "playerStart":
				self.playerStart = pygame.Rect(object.x, object.y, object.width, object.height)
			if object.name == "enemy":
				self.group.add(Enemy((object.x, object.y)))
				#self.enemies[self.index] = pygame.Rect(object.x, object.y, object.width, object.height)
				#self.index = self.index + 1
				self.blockers.append(pygame.Rect(object.x, object.y, object.width, object.height))

		self.player = Player()

		# put the hero in the center of the map
		self.player.position = [self.playerStart.x, self.playerStart.y]
		# add our hero to the group
		self.group.add(self.player)

		self.temp_surface = pygame.Surface((w / 2, h / 2)).convert()
Esempio n. 43
0
	def __init__(self, map_file_location, map_to_load, player_object):
		super(map, self).__init__()
		pygame.sprite.Sprite.__init__(self)
		#ONLY LOADS bottom layer right now
		self.locate,self.map_load = map_file_location,map_to_load
		self.tmxdata = load_pygame("{}\{}".format(map_file_location, map_to_load))
		
		self.player_object = player_object
		
		self.x_moved = 0
		self.y_moved = 0
		
		self.placex = 0
		self.placey = 0
		
		self.xtilestart = 0#where the map starts generating based on tiles.  limit x is 0-600
		self.ytilestart = 0#where the map starts generating based on y.  Limit is 0-480
		self.xtile_placeholder = self.xtilestart
		self.ytile_placeholder = self.ytilestart
		
		self.loop_times = 0
    def __init__(self):

        # true while running
        self.running = False

        # load data from pytmx
        tmx_data = pytmx.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)

        w, h = screen.get_size()

        # create new renderer (camera)
        # clamp_camera is used to prevent the map from scrolling past the edge
        self.map_layer = pyscroll.BufferedRenderer(map_data,
                                                   (w / 2, h / 2),
                                                   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 1
        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.rect.center

        # add our hero to the group
        self.group.add(self.hero)
Esempio n. 45
0
    def __init__(self, filename):

        # load data from pytmx
        tmx_data = pytmx.load_pygame(filename)

        # create new data source
        map_data = pyscroll.data.TiledMapData(tmx_data)

        # create new renderer
        # pyscroll has two renderers: BufferedRenderer
        #                             ThreadedRenderer
        # the threaded renderer is an experimental feature
        # seems to be picky of OS and python versions

        #self.map_layer = pyscroll.ThreadedRenderer(map_data, screen.get_size())
        self.map_layer = pyscroll.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.rect.width / 2,
                       self.map_layer.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
Esempio n. 46
0
	def __init__(self, filename):
		self.placeable = []
		self.towers = []
		self.enemyQueue = []
		self.bufferedEnemies = []
		self.activeEnemies = []
		self.enemyPath = []
		import pytmx
		self.tiledmap = pytmx.load_pygame(filename, pixelalpha=True)
		for group in self.tiledmap.objectgroups:
			for obj in group:
				if obj.type == "Entrance":
					self.entrance = pygame.Rect(obj.x, obj.y, obj.width, obj.height)
				elif obj.type == "Exit":
					self.exit = pygame.Rect(obj.x, obj.y, obj.width, obj.height)
				elif obj.type == "Path":
					points = obj.points
					x = obj.x
					y = obj.y
					for pt in points:
						self.enemyPath.append(pt)
						
		tw = self.tiledmap.tilewidth
		th = self.tiledmap.tileheight
		# gt = self.tiledmap.get_tile_image(x, y, layer)
		# layers = self.tiledmap.tilelayers
		for l in xrange(0, len(self.tiledmap.layers)):
			for y in xrange(0, self.tiledmap.height):
				for x in xrange(0, self.tiledmap.width):
					if hasattr(self.tiledmap.layers[l], "placeable"):
						if self.tiledmap.layers[l].placeable == "true":
							tile = self.tiledmap.get_tile_image(x, y, l)
							if tile: 
								self.placeable.append(pygame.Rect(x * tw, y * th, tw, th))
		
		self.enemy_delay = self.delay_max
Esempio n. 47
0
def load_level(tmx_file):
    platforms = []
    ropes = []
    ladders = []
    water = []
    player_starts = []
    vines = []
    dirt = []
    sky = []
    jungle = []
    darkness = []
    trees = []
    enemies = []
    fruit_trees = []
    harvest_plants = []
    butterflies = []
    
    classes = {"platform": Platform,
                    "ropeswing": RopeSwing,
                    "water": Water,
                    "player_start": PlayerStart,
                    "ladder": Ladder,
                    "vines": Vines,
                    "dirt": Dirt,
                    "sky": Sky,
                    "jungle": JungleBground,
                    "darkness": Darkness,
                    "tree": Tree,
                    "bigtree": BigTree,
                    "snake": Snake,
                    "bat": Bat,
                    "banana_tree": BananaTree,
                    "papaya_tree": PapayaTree,
                    "taro_plant": TaroPlant,
                    "pineapple_plant": PineapplePlant,
                    "butterfly": Butterfly}
    group_map = {"platform": "platforms",
                          "ropeswing": "ropes",
                          "water": "water",
                          "ladder": "ladders",
                          "player_start": "player_starts",
                          "vines": "vines",
                          "dirt": "dirt",
                          "darkness": "darkness",
                          "jungle": "jungle",
                          "sky": "sky",
                          "tree": "trees",
                          "bigtree": "trees",
                          "enemy": "enemies",
                          "banana_tree": "fruit_trees",
                          "papaya_tree": "fruit_trees",
                          "taro_plant": "harvest_plants",
                          "pineapple_plant": "harvest_plants",
                          "butterfly": "butterflies"}
    groups = {"platforms": platforms,
                    "ropes": ropes,
                    "ladders": ladders,
                    "water": water,
                    "player_starts": player_starts,
                    "vines": vines,
                    "dirt": dirt,
                    "darkness": darkness,
                    "sky": sky,
                    "jungle": jungle,
                    "trees": trees, 
                    "enemies": enemies,
                    "fruit_trees": fruit_trees,
                    "harvest_plants": harvest_plants,
                    "butterflies": butterflies}
    
    tmx = pytmx.load_pygame(tmx_file, colorkey=(0,0,0, 255))
    tile_width, tile_height = tmx.tilewidth, tmx.tileheight
    width, height = tmx.width * tile_width, tmx.height * tile_height
    surface = pg.Surface((width, height)).convert()
    surface.fill(pg.Color("black"))
    surface.set_colorkey(pg.Color("black"))    
    
    for layer in tmx.layers:
        if isinstance(layer, TileLayer):
            for x, y, gid in layer:
                tile = tmx.get_tile_image_by_gid(gid)
                if tile:
                    surface.blit(tile, (x * tile_width, y * tile_height))
                   
                    
    for obj in tmx.objects:
        rect = pg.Rect(obj.x, obj.y, obj.width, obj.height)
        if obj.name == "enemy":
            props = obj.properties
            klass = classes[props["class"]]
            direction = props["direction"]
            groups[group_map[obj.name]].append(klass(rect, direction))
        else:
            klass = classes[obj.name]
            groups[group_map[obj.name]].append(klass(rect))
    return groups, surface
Esempio n. 48
0
 def __init__(self, filename):
     #self.tmx = pytmx.load_pygame(os.path.join(Renderer.dir, filename), pixelalpha=True)
     self.tmx = pytmx.load_pygame(filename, pixelalpha=True)
     self.size = self.tmx.width * self.tmx.tilewidth, self.tmx.height * self.tmx.tileheight
Esempio n. 49
0
        # Crea una imagen en blanco
        imagen = pygame.Surface([ancho, alto]).convert()

        # Copia una parte de la hoja de sprites a la imagen
        imagen.blit(self.sprite_sheet, (0, 0), (fila * ancho, columna * alto, ancho, alto))

        # Asume que el negro es el color transparente
        imagen.set_colorkey(NEGRO)

        # Retorna la imagen
        return imagen
        
hoja_completa = SpriteSheet("./imagenes/completa32.png")

tmxdata = pytmx.load_pygame("plantilla.tmx")

principal = hoja_completa.get_image(1, 8, 32, 32)
pasto = hoja_completa.get_image(14, 1, 32, 32)
agua = hoja_completa.get_image(13, 7, 32, 32)
sombra_agua = hoja_completa.get_image(14, 7, 32, 32)

def llenar_fondo(fondo):
    for cuadro_x in range(ancho):
        for cuadro_y in range(alto):
            pantalla.blit(fondo, [cuadro_x * 32, cuadro_y * 32])

def pintar_mapa(tmxdata,pantalla):
    for capa in range(10):
        for x in range(6):
            for y in range(6):
Esempio n. 50
0
 def cambiar_mapa(self, ruta, n_capas, c_personaje):
     self.datos = pytmx.load_pygame(ruta)
     self.capas = n_capas
     self.personaje = c_personaje
     print("cambie el mapa, ", self)
Esempio n. 51
0
import pygame
pygame.init()
pygame.display.set_mode((768, 512))
from pytmx import load_pygame
tmx_data = load_pygame('C:\Users\\nick.jenkins\Dropbox\Hobbies\Frisbee Golf Game\Map\SKB1.tmx')
Esempio n. 52
0
    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
        #self.data = pytmx.TiledMap(filename)
        self.data = load_pygame(filename, pixelalpha=True)

        # 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':
                conds = []
                acts = []

                # Conditions & actions are stored as Tiled properties.
                # We need to sort them by name, so that "act1" comes before "act2" and so on..
                keys = sorted(obj.properties.keys())

                for k in keys:
                    if k.startswith('cond'):
                        words = obj.properties[k].split(' ', 2)

                        # Conditions have the form 'operator type parameters'.
                        operator, type = words[0:2]

                        args = ''
                        if len(words) > 2:
                            args = words[2]

                        conds.append({
                            'type': type,
                            'parameters': args,
                            'x': int(obj.x / self.tile_size[0]),
                            'y': int(obj.y / self.tile_size[1]),
                            'width': int(obj.width / self.tile_size[0]),
                            'height': int(obj.height / self.tile_size[1]),
                            'operator': operator
                        })
                    elif k.startswith('act'):
                        acts.append(obj.properties[k].split(' ', 1))

                self.events.append({'conds':conds, 'acts':acts})
Esempio n. 53
0
        # Crea una imagen en blanco
        imagen = pygame.Surface([ancho, alto]).convert()

        # Copia una parte de la hoja de sprites a la imagen
        imagen.blit(self.sprite_sheet, (0, 0), (fila * ancho, columna * alto, ancho, alto))

        # Asume que el negro es el color transparente
        imagen.set_colorkey(NEGRO)

        # Retorna la imagen
        return imagen
        
hoja_completa = SpriteSheet("./imagenes/completa32.png")

tmxdata = pytmx.load_pygame("el segundo con tiled.tmx")

principal = hoja_completa.get_image(1, 8, 32, 32)
pasto = hoja_completa.get_image(14, 1, 32, 32)
agua = hoja_completa.get_image(13, 7, 32, 32)
sombra_agua = hoja_completa.get_image(14, 7, 32, 32)

def llenar_fondo(fondo):
    for cuadro_x in range(ancho):
        for cuadro_y in range(alto):
            pantalla.blit(fondo, [cuadro_x * 32, cuadro_y * 32])

def pintar_mapa(tmxdata,pantalla):
    for capa in range(4):
        for x in range(15):
            for y in range(15):
Esempio n. 54
0
    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
        #self.data = pytmx.TiledMap(filename)
        self.data = load_pygame(filename, pixelalpha=True)
        
        # 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 == 'condition':
                self.conditions.append(obj)

            elif obj.type == 'action':
                self.actions.append(obj)
Esempio n. 55
0
 def __init__(self, filename):
     tm = pytmx.load_pygame(filename, pixelalpha=True)
     self.size = tm.width * tm.tilewidth, tm.height * tm.tileheight
     self.tmx_data = tm
     self.tiles = []
Esempio n. 56
0
 def load_map(self, map_name):
     self.map = pytmx.load_pygame('maps/' + map_name + '.tmx')
     self.width = self.map.width
     self.height = self.map.height
     self.size = (self.width, self.height)
                pygame.display.flip()

        except KeyboardInterrupt:
            self.running = False


if __name__ == "__main__":
    pygame.init()
<<<<<<< HEAD
    width = 1280
    height = 720

    mousex, mousey = 0, 0

    #map data
    tmx_data = pytmx.load_pygame("Assets/tileset/untitled.tmx")
    map_data = pyscroll.TiledMapData(tmx_data)
    screen_size = (width, height)
    map_layer = pyscroll.BufferedRenderer(map_data, screen_size)
    group = pyscroll.PyscrollGroup(map_layer=map_layer)

    #color data; not useful
    blue_color = pygame.Color(0, 0, 255)
    black_color = pygame.Color(0, 0, 0)

    #example_image = pygame.image.load('Assets/cat.png')

    fps_clock = pygame.time.Clock()
    font_obj = pygame.font.Font('freesansbold.ttf', 32) #have fang pick a font
    msg = "Begin!"
    sound_obj = pygame.mixer.Sound('Assets/oww.wav') #change
Esempio n. 58
0
    def __init__(self):
        """ Init pygame """
        pygame.init()

        # Boolean values to know where we are in the game
        self.game_started = False
        self.game_paused = False
        self.game_ended = False
        self.text = "Too bad !"
        # Clock
        self.clock = pygame.time.Clock()

        # Setting up the display
        pygame.display.set_caption('Frozen Water Maze')
        icon_path = os.path.dirname(__file__) + os.sep + "assets/ico.png"
        pygame.display.set_icon(pygame.image.load(icon_path))
        self.screen = pygame.display.set_mode((64 * 18, 64 * 12))

        self.font = pygame.font.Font(None, 36)

        # Load data
        tmxpath = os.path.dirname(__file__) + os.sep + "assets/map.tmx"
        tmxdata = pytmx.load_pygame(tmxpath)
        self.game_tiles = []
        self.game_fires = []
        self.game_waters = []
        self.game_collectibles = []
        self.game_grids = []
        for coord_x in range(18):
            for coord_y in range(12):
                img = tmxdata.get_tile_image(coord_x, coord_y, 0)
                if img is not None:
                    self.game_tiles.append(GameTile(img, coord_x, coord_y))
                fire = tmxdata.get_tile_image(coord_x, coord_y, 1)
                if fire is not None:
                    self.game_fires.append(Fire(coord_x, coord_y))
                water = tmxdata.get_tile_image(coord_x, coord_y, 2)
                if water is not None:
                    self.game_waters.append(Water(water, coord_x, coord_y))
                collectible = tmxdata.get_tile_image(coord_x, coord_y, 3)
                if collectible is not None:
                    self.game_collectibles.append(Collectible(coord_x, coord_y))
                grid = tmxdata.get_tile_image(coord_x, coord_y, 4)
                if grid is not None:
                    self.game_grids.append(Grid(grid, coord_x, coord_y))

        # Init music
        music_path = os.path.dirname(__file__) + os.sep + "assets/sfx/bg_music.ogg"
        pygame.mixer.music.load(music_path)
        pygame.mixer.music.set_volume(0.25)
        pygame.mixer.music.play(-1)

        # Init ambient motor sound
        ambient_motor_path = os.path.dirname(__file__) + os.sep + "assets/sfx/motor.ogg"
        ambient_motor = pygame.mixer.Sound(ambient_motor_path)
        ambient_motor.set_volume(0.15)
        ambient_motor.play(loops=-1)

        # Init ambient droplet fall sound
        droplet_path = os.path.dirname(__file__) + os.sep + "assets/sfx/droplet.ogg"
        self.ambient_droplet = pygame.mixer.Sound(droplet_path)
        self.ambient_droplet.set_volume(0.3)

        # Init get sound
        get_path = os.path.dirname(__file__) + os.sep + "assets/sfx/get.ogg"
        self.get_sfx = pygame.mixer.Sound(get_path)
        self.get_sfx.set_volume(0.2)

        # Init game
        # ground
        bg_path = os.path.dirname(__file__) + os.sep + "assets/bg.jpg"
        self.background_img = pygame.image.load(bg_path)

        # Init player
        self.player = Player()

        # Init score
        self.score = 0
        self.score_image = self.font.render(str(self.score), True, (255, 255, 255))
        self.score_rect = self.score_image.get_rect()
        self.score_rect.top = 5
        self.score_rect.left = 64

        # Init timer
        self.timer = 20
        timer_path = os.path.dirname(__file__) + os.sep + "assets/timer.png"
        self.timer_image = pygame.image.load(timer_path)
        self.timer_rect = self.timer_image.get_rect()
        self.timer_rect.top = 5
        self.timer_rect.left = self.screen.get_width() - 64
        self.timer_text_image = self.font.render(str(self.timer), True, (255, 255, 255))
        self.timer_text_rect = self.timer_text_image.get_rect()
        self.timer_text_rect.top = 24
        self.timer_text_rect.left = self.screen.get_width() - 92

        # Startup screen display
        startup_img_path = os.path.dirname(__file__) + os.sep + "assets/title.jpg"
        self.startup_image = pygame.image.load(startup_img_path)
        self.screen.fill((0, 0, 0))
        startup_screen_display = True

        while startup_screen_display:
            self.screen.blit(self.startup_image, Rect(0, 0, self.screen.get_width(), self.screen.get_height()))
            pygame.display.flip()
            pygame.time.wait(3000)
            startup_screen_display = False

        # Init internal event -> droplet fall
        pygame.time.set_timer(pygame.USEREVENT, 5000)

        # Init internal event -> timer decrease
        pygame.time.set_timer(pygame.USEREVENT + 1, 1000)

        # Game loop
        while not self.game_ended:
            self.screen.fill((0, 0, 0))
            self.check_game_event()

            self.screen.blit(self.background_img, Rect(0, 0, 64 * 18, 64 * 12))

            self.screen.blit(self.score_image, self.score_rect)
            self.screen.blit(self.timer_image, self.timer_rect)
            self.screen.blit(self.timer_text_image, self.timer_text_rect)

            is_player_falling = False
            if self.player.current_shape != Player.PLAYER_CLOUD:
                is_player_falling = True

            for tile in self.game_tiles:
                tile.display(self.screen)
                if self.player.rect.bottom == tile.rect.top and self.player.rect.left == tile.rect.left:
                    is_player_falling = False

            for tile in self.game_grids:
                tile.display(self.screen)
                if self.player.rect.bottom == tile.rect.top and self.player.rect.left == tile.rect.left and self.player.current_shape == Player.PLAYER_ICE:
                    is_player_falling = False

            for danger in self.game_waters:
                danger.display(self.screen)
                if self.player.rect.bottom == danger.rect.top and self.player.rect.left == danger.rect.left:
                    if self.player.current_shape != Player.PLAYER_CLOUD:
                        self.game_ended = True
                        is_player_falling = False
                elif collide_rect(self.player, danger):
                    self.game_ended = True
                    is_player_falling = False

            if is_player_falling:
                self.player.fall()

            for danger in self.game_fires:
                danger.display(self.screen)
                if collide_rect(self.player, danger):
                    self.game_ended = True

            for point in self.game_collectibles:
                point.display(self.screen)
                if collide_rect(self.player, point):
                    self.score += 1
                    self.get_sfx.play()
                    self.game_collectibles.remove(point)
                    self.score_image = self.font.render(str(self.score), True, (255, 255, 255))

            if self.game_collectibles.__len__()==0:
                self.game_ended=True
                self.text = "Congrat's !!"
            self.player.display(self.screen)

            pygame.time.wait(50)
            self.clock.tick(60)
            pygame.display.flip()

        self.startup_screen_display = True
        cpt = 0
        while self.startup_screen_display:
            self.screen.blit(self.background_img, (0, 0))
            # Endscreen text ( by default text is "Too bad !" )
            # ( if game_collectibles(len) == 0: "Congrat's!"  )
            font = pygame.font.SysFont('Arial', 100, True)
            text= font.render(self.text, True, (255, 255, 255))
            text_rect = text.get_rect()
            text_rect.midtop = ( 550, 300)
            self.screen.blit(text, text_rect)

            pygame.time.wait(300)
            pygame.display.flip()
            cpt += 1
            if cpt ==10:
                self.startup_screen_display = False
        pygame.quit()
Esempio n. 59
0
 def __init__(self, ruta, n_capas, c_personaje):
     self.datos = pytmx.load_pygame(ruta)
     self.capas = n_capas
     self.personaje = c_personaje
Esempio n. 60
0
 def __init__(self, filename):
     tm = pytmx.load_pygame(filename, pixelalpha=True)
     self.width = tm.width * tm.tilewidth
     self.height = tm.height * tm.tileheight
     self.tmxdata = tm