Reputation: 65
Trying to select a random map from my maps folder when certain conditions are met, how would I go about selecting a new map.
MAP = ['map.tmx', 'map2.tmx', 'map3.tmx']
self.map_folder = path.join(game_folder, 'maps')
self.map = TiledMap(path.join(self.map_folder, MAP))
class TiledMap:
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
def render(self, surface):
ti = self.tmxdata.get_tile_image_by_gid
for layer in self.tmxdata.visible_layers:
if isinstance(layer, pytmx.TiledTileLayer):
for x, y, gid, in layer:
tile = ti(gid)
if tile:
surface.blit(tile, (x * self.tmxdata.tilewidth,
y * self.tmxdata.tileheight))
def make_map(self):
surface = py.Surface((self.width, self.height))
self.render(surface)
return surface
Upvotes: 0
Views: 166
Reputation: 143216
To get something random you need module random
You can use choice()
to get random item from list
import random
MAP = ['map.tmx', 'map2.tmx', 'map3.tmx']
map = random.choice(MAP)
print(map)
But if you use again choice()
then sometimes you may get the same map. To get different map you would have to remove already used map from MAP
before next choice()
OR you can do this in different way. Using shuffle()
you get list with items in random order and then you can use for
-loop to get always unique and random map
import random
MAP = ['map.tmx', 'map2.tmx', 'map3.tmx']
random.shuffle(MAP)
for map in MAPS:
print(map)
EDIT: to keep first map always as first and shuffle only other maps
import random
MAP = ['map.tmx', 'map2.tmx', 'map3.tmx', 'map4.tmx', 'map5.tmx']
first = MAP[:1] # list with one element - it need `first + rest` instead of `[first] + rest`
rest = MAP[1:]
random.shuffle(rest)
MAP = first + rest
print(MAP)
BTW: in the same way you can keep first and second map in place
first = MAP[:2]
rest = MAP[2:]
EDIT: After shuffling
To load only first map
map = MAP[0]
fullpath = path.join(self.map_folder, map)
self.map = TiledMap(fullpath)
To work with all maps you may run in loop
for map in MAP:
fullpath = path.join(self.map_folder, map)
self.map = TiledMap(fullpath)
# ... run game with this map ...
OR use variable with level
# first level
level = 0
map = MAP[level]
fullpath = path.join(self.map_folder, map)
self.map = TiledMap(fullpath)
# ... run game with this map ...
# next level
level += 1
map = MAP[level]
fullpath = path.join(self.map_folder, map)
self.map = TiledMap(fullpath)
# ... run game with this map ...
# next level
level += 1
map = MAP[level]
fullpath = path.join(self.map_folder, map)
self.map = TiledMap(fullpath)
# ... run game with this map ...
# etc.
Upvotes: 1