diff --git a/.gitignore b/.gitignore index 69cee7b..17241fe 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,5 @@ keys/apiKeys.key *.json *.elm data/worlds/*/* +data/worlds/*/world/backups/* +data/defaultWorld/world/backups/* diff --git a/__main__.py b/__main__.py index f5df63f..05f92fa 100644 --- a/__main__.py +++ b/__main__.py @@ -130,10 +130,10 @@ def edit(_): elif element == 1: # make new world @G.Loading def NW(self): # TODO: make a GUI screen to ask fr title and description - self.world = World('newworld', 'New World', 'a new world', 25, quality=500) + self.world = World('newworld', 'New World', 'a new world', 10, 100) cont, res = NW() if cont: - return self.world(res['world'], True) + return self.world(res['world'], newworld=True) else: G.Container.Selection = G.Container.res['worlds'][element.uid-2].name G.Reload() diff --git a/data/defaultWorld/world.ldtk b/data/defaultWorld/world.ldtk index 5785bef..695a171 100644 --- a/data/defaultWorld/world.ldtk +++ b/data/defaultWorld/world.ldtk @@ -33,13 +33,13 @@ "imageExportMode": "None", "exportLevelBg": true, "pngFilePattern": null, - "backupOnSave": false, - "backupLimit": 10, + "backupOnSave": true, + "backupLimit": 3, "backupRelPath": null, "levelNamePattern": "Level_%idx", "tutorialDesc": "Congrats on finding this!", "customCommands": [], - "flags": [ "ExportOldTableOfContentData", "IgnoreBackupSuggest" ], + "flags": ["ExportOldTableOfContentData"], "defs": { "layers": [ { "__type": "IntGrid", @@ -141,7 +141,7 @@ "intGridValuesGroups": [], "autoRuleGroups": [], "autoSourceLayerDefUid": null, - "tilesetDefUid": null, + "tilesetDefUid": 26, "tilePivotX": 0, "tilePivotY": 0, "biomeFieldUid": null @@ -519,8 +519,8 @@ "embedAtlas": null, "pxWid": 1024, "pxHei": 1024, - "tileGridSize": 128, - "spacing": 0, + "tileGridSize": 16, + "spacing": 112, "padding": 0, "tags": [], "tagsSourceEnumUid": null, @@ -529,7 +529,7 @@ "savedSelections": [], "cachedPixelData": { "opaqueTiles": "1111111111111111111111111111111111111111111111111111111111111111", - "averageColors": "f000f700f770f707f070f007f077f777f700ff00ff70ff07f770f707f777ff77f770ff70fff0ff77f7f0f777f7f7fff7f707ff07ff77ff0ff777f70ff77fff7ff070f770f7f0f777f0f0f077f0f7f7f7f007f707f777f70ff077f00ff07ff77ff077f777f7f7f77ff0f7f07ff0fff7fff777ff77fff7ff7ff7f7f77ff7ffffff" + "averageColors": "f000f800f880f808f080f008f088f888f700ff00ff80ff08f780f708f788ff88f770ff70fff0ff78f7f0f778f7f8fff8f707ff07ff87ff0ff787f70ff78fff8ff070f870f8f0f878f0f0f078f0f8f8f8f007f807f887f80ff087f00ff08ff88ff077f877f8f7f87ff0f7f07ff0fff8fff777ff77fff7ff7ff7f7f77ff7ffffff" } } ], "enums": [{ "identifier": "Food", "uid": 10, "values": [ { "id": "Meat", "tileRect": { "tilesetUid": 7, "x": 48, "y": 320, "w": 16, "h": 16 }, "color": 12470831 }, { "id": "Bread", "tileRect": { "tilesetUid": 7, "x": 16, "y": 320, "w": 16, "h": 16 }, "color": 14120515 } ], "iconTilesetUid": 7, "externalRelPath": null, "externalFileChecksum": null, "tags": [] }], "externalEnums": [], "levelFields": [] }, @@ -708,8 +708,8 @@ "__opacity": 1, "__pxTotalOffsetX": 0, "__pxTotalOffsetY": 0, - "__tilesetDefUid": null, - "__tilesetRelPath": null, + "__tilesetDefUid": 26, + "__tilesetRelPath": "images/Colours.png", "iid": "cce22190-3b70-11ee-849e-c78a24195a27", "levelId": 0, "layerDefUid": 2, @@ -721,7 +721,15 @@ "autoLayerTiles": [], "seed": 926674, "overrideTilesetUid": null, - "gridTiles": [], + "gridTiles": [ + { "px": [336,336], "src": [640,384], "f": 0, "t": 29, "d": [1071], "a": 1 }, + { "px": [272,352], "src": [640,384], "f": 0, "t": 29, "d": [1117], "a": 1 }, + { "px": [288,352], "src": [640,384], "f": 0, "t": 29, "d": [1118], "a": 1 }, + { "px": [304,352], "src": [640,384], "f": 0, "t": 29, "d": [1119], "a": 1 }, + { "px": [320,352], "src": [640,384], "f": 0, "t": 29, "d": [1120], "a": 1 }, + { "px": [256,368], "src": [640,384], "f": 0, "t": 29, "d": [1166], "a": 1 }, + { "px": [272,368], "src": [640,384], "f": 0, "t": 29, "d": [1167], "a": 1 } + ], "entityInstances": [] }, { diff --git a/demos.py b/demos.py index 352d2ef..8b88372 100644 --- a/demos.py +++ b/demos.py @@ -121,7 +121,7 @@ def pressed(elm): def worldsDemo(): from utils import World - World('test', 'Test World', 'A world for testing random stuff', 25, quality=500, override=True) + World('test', 'Test World', 'A world for testing random stuff', 25, override=True) def terrainGenDemo(): from random import randint diff --git a/utils/terrainGen.py b/utils/terrainGen.py index e2c4cbf..7e65b68 100644 --- a/utils/terrainGen.py +++ b/utils/terrainGen.py @@ -14,46 +14,6 @@ from scipy.ndimage.filters import gaussian_filter from scipy.ndimage.morphology import binary_dilation -from utils.conversation_parse import parseKWs - -class Map: - def __init__(self, *args, **kwargs): - self.size = args[0] or kwargs.get('size') - self.g = MapGen(*args, **kwargs) - self.conf = self.g.outs - self.map = self.conf[0][0] - self.trees = self.tolist(self.conf[1]) - self.structures = [] - # self.generate_structures() - def __call__(self, w, h, x=0, y=0): - return [i[x:x+w] for i in self.map[y:y+h]] - def get_structs(self, w, h, x=0, y=0): - #return [i[x:x+w] for i in self.trees[y:y+h]] - return [i[x:x+w] for i in self.structures[y:y+h]] - - def tolist(self, nl, do_tolist=True): - if do_tolist: nl = [[(int(j[0]), int(j[1])) for j in i] for i in nl] - out = np.zeros((self.size, self.size)) - for j in nl: - for i in j: - out[i[0]][i[1]] = 1 - return [[int(j) for j in i] for i in out] - - def generate_structures(self): - print('Generating structures... (0/%i)' % (round(len(self.map))/10)) - outs = [] - done = [] - for x in range(len(self.map)): - for y in range(len(self.map[x])): - if (x, y) not in done: - l = floodfill(self.map, x, y) - outs.append(l) - done.extend(l) - if x % 10 == 0: print('Generating structures... (%i/%i)' % (round(x / 10), round(len(self.map)/10))) - print('Generating structures: sorting and choosing...') - outs.sort(key=lambda x: len(x), reverse=True) - self.structures = self.tolist([outs[0]]) - def floodfill(matrix, x, y): tofill = [(x, y)] filled = [] @@ -352,16 +312,85 @@ def place_trees(n, mask, a=0.5): return output_trees return [np.array(place_trees(densities[i], biome_masks[i])) for i in range(len(biome_names))] + + def __call__(self, w, h, x=0, y=0): + return [i[x:x+w] for i in self.map[y:y+h]] - def one(self): + def get_structs(self, w, h, x=0, y=0): + #return [i[x:x+w] for i in self.trees[y:y+h]] + return [i[x:x+w] for i in self.structures[y:y+h]] + + def tolist(self, nl, do_tolist=True): + if do_tolist: nl = [[(int(j[0]), int(j[1])) for j in i] for i in nl] + out = np.zeros((self.size, self.size)) + for j in nl: + for i in j: + out[i[0]][i[1]] = 1 + return [[int(j) for j in i] for i in out] + + def generate_structures(self): + print('Generating structures... (0/%i)' % (round(len(self.map))/10)) + outs = [] + done = [] + for x in range(len(self.map)): + for y in range(len(self.map[x])): + if (x, y) not in done: + l = floodfill(self.map, x, y) + outs.append(l) + done.extend(l) + if x % 10 == 0: print('Generating structures... (%i/%i)' % (round(x / 10), round(len(self.map)/10))) + print('Generating structures: sorting and choosing...') + outs.sort(key=lambda x: len(x), reverse=True) + self.structures = self.tolist([outs[0]]) + + def __init__(self, size, map_seed=None, n=256, useall=False, showAtEnd=False, generateTrees=True): + """ + Generates a map! :) + + Parameters + ---------- + size : int + The size of the map to generate! + PLEASE NOTE: I am not fully sure what this specifically does. From testing I have found + out a possibility that it is just the resolution of the map and not actually zoomed in. + map_seed : int, optional + The seed of the map, by default None (will make a random seed) + A good seed is '762345' + n : int, optional + I don't know what this is, may/may not be linked to the size above, by default 256 + + useall : bool, optional + Whether or not to use matplotlib to save all steps of the process or just the finished result, by default False (just show finished result) + showAtEnd : bool, optional + Whether or not to show using matplotlib the finished result (and possibly the rest of the steps, see `useall`), by default False + generateTrees : bool, optional + Whether or not to generate trees. If no then will output blanks where the trees output should be below, defaults to True + + Returns + ------- + tuple(list[numpy arrays/lists], numpy array) + [ + out (rounded and scaled from 1-10, list), + colour_map (numpy array, out before rounding and scaling, also contains colours), + rivers_biome_colour_map, (numpy array, ???), + adjusted_height_river_map, (numpy array, ???), + river_land_mask (numpy array, ???), + biome_masks (numpy array, ???) + ], trees (list[numpy array (for each biome name)], this has all the biomes and the trees positions in them.) + """ + # setting params + if map_seed == None: self.map_seed = randint(0, 999999) + else: self.map_seed = map_seed + np.random.seed(self.map_seed) + self.size = size # Voronoi diagram print('Creating Voronoi diagram...') - points = np.random.randint(0, self.size, (514, 2)) + points = np.random.randint(0, size, (514, 2)) vor = self.voronoi(points) vor_map = self.voronoi_map(vor) - if self.useall: + if useall: fig = plt.figure(dpi=150, figsize=(4, 4)) plt.scatter(*points.T, s=1) @@ -371,7 +400,7 @@ def one(self): vor = self.voronoi(points) vor_map = self.voronoi_map(vor) - if self.useall: + if useall: fig = plt.figure(dpi=150, figsize=(4, 4)) plt.scatter(*points.T, s=1) @@ -382,17 +411,17 @@ def one(self): print('Bluring the boundaries (with noise)...') boundary_displacement = 8 boundary_noise = np.dstack([self.noise_map(32, 200, octaves=8), self.noise_map(32, 250, octaves=8)]) - boundary_noise = np.indices((self.size, self.size)).T + boundary_displacement*boundary_noise - boundary_noise = boundary_noise.clip(0, self.size-1).astype(np.uint32) + boundary_noise = np.indices((size, size)).T + boundary_displacement*boundary_noise + boundary_noise = boundary_noise.clip(0, size-1).astype(np.uint32) blurred_vor_map = np.zeros_like(vor_map) - for x in range(self.size): - for y in range(self.size): + for x in range(size): + for y in range(size): j, i = boundary_noise[x, y] blurred_vor_map[x, y] = vor_map[i, j] - if self.useall: + if useall: fig, axes = plt.subplots(1, 2) fig.set_dpi(150) fig.set_size_inches(8, 4) @@ -408,7 +437,7 @@ def one(self): temperature_map = self.noise_map(2, 10) precipitation_map = self.noise_map(2, 20) - if self.useall: + if useall: fig, axes = plt.subplots(1, 2) fig.set_dpi(150) fig.set_size_inches(8, 4) @@ -423,7 +452,7 @@ def one(self): # Histogram Equalization print('Histogram equalization...') - if self.useall: + if useall: fig, axes = plt.subplots(1, 2) fig.set_dpi(150) fig.set_size_inches(8, 4) @@ -441,7 +470,7 @@ def one(self): hist2d = np.interp(hist2d, (hist2d.min(), hist2d.max()), (0, 1)) hist2d = expit(hist2d/0.1) - if self.useall: + if useall: axes[1].imshow(hist2d, cmap="plasma") axes[1].set_xticks([0, 128, 256, 385, 511]) @@ -452,7 +481,7 @@ def one(self): uniform_temperature_map = self.histeq(temperature_map, alpha=0.33) uniform_precipitation_map = self.histeq(precipitation_map, alpha=0.33) - if self.useall: + if useall: fig, axes = plt.subplots(1, 2) fig.set_dpi(150) fig.set_size_inches(8, 4) @@ -470,7 +499,7 @@ def one(self): hist2d = np.interp(hist2d, (hist2d.min(), hist2d.max()), (0, 1)) hist2d = expit(hist2d/0.1) - if self.useall: + if useall: axes[1].imshow(hist2d, cmap="plasma") axes[1].set_xticks([0, 128, 256, 385, 511]) @@ -490,7 +519,7 @@ def one(self): temperature_map = self.fill_cells(vor_map, temperature_cells) precipitation_map = self.fill_cells(vor_map, precipitation_cells) - if self.useall: + if useall: fig, ax = plt.subplots(1 ,2) fig.set_dpi(150) fig.set_size_inches(8, 4) @@ -531,13 +560,11 @@ def one(self): biomes = np.flip(biomes, axis=0).T - if self.useall: + if useall: fig = plt.figure(dpi=150, figsize=(4, 4)) plt.imshow(biomes) plt.title("Temperature–Precipitation graph") - return temperature_cells, precipitation_cells, biomes, vor_map - - def two(self, temperature_cells, precipitation_cells, biomes, vor_map): + # Biome map print('Making biome map...') @@ -551,7 +578,7 @@ def two(self, temperature_cells, precipitation_cells, biomes, vor_map): biome_map = self.fill_cells(vor_map, biome_cells).astype(np.uint32) biome_colour_map = self.colour_cells(biome_map, biome_colours) - if self.useall: + if useall: fig = plt.figure(figsize=(5, 5), dpi=150) plt.imshow(biome_colour_map) @@ -561,22 +588,21 @@ def two(self, temperature_cells, precipitation_cells, biomes, vor_map): height_map = self.noise_map(4, 0, octaves=6, persistence=0.5, lacunarity=2) land_mask = height_map > 0 - if self.useall: + if useall: fig = plt.figure(dpi=150, figsize=(5, 5)) plt.imshow(land_mask, cmap='gray') + sea_colour = np.array([12, 14, 255]) land_mask_colour = np.repeat(land_mask[:, :, np.newaxis], 3, axis=-1) masked_biome_colour_map = land_mask_colour*biome_colour_map + (1-land_mask_colour)*sea_colour - if self.useall: + if useall: fig = plt.figure(dpi=150, figsize=(5, 5)) plt.imshow(masked_biome_colour_map) - return masked_biome_colour_map, biome_map, land_mask, biome_colour_map, height_map - - def three(self, masked_biome_colour_map, biome_map, land_mask, height_map): + biome_height_map, normal_map = self.apply_height_map(masked_biome_colour_map, height_map, height_map, land_mask) - if self.useall: + if useall: fig, ax = plt.subplots(1 ,2) fig.set_dpi(150) fig.set_size_inches(10, 5) @@ -593,7 +619,7 @@ def three(self, masked_biome_colour_map, biome_map, land_mask, height_map): height_map = self.noise_map(4, 0, octaves=6, persistence=0.5, lacunarity=2) smooth_height_map = self.noise_map(4, 0, octaves=1, persistence=0.5, lacunarity=2) - if self.useall: + if useall: fig, ax = plt.subplots(1 ,2) fig.set_dpi(150) fig.set_size_inches(10, 5) @@ -659,7 +685,7 @@ def three(self, masked_biome_colour_map, biome_map, land_mask, height_map): print('Generating Height Map Filters: Biome masks...') biome_count = len(biome_names) - biome_masks = np.zeros((biome_count, self.size, self.size)) + biome_masks = np.zeros((biome_count, size, size)) for i in range(biome_count): biome_masks[i, biome_map==i] = 1 @@ -672,7 +698,7 @@ def three(self, masked_biome_colour_map, biome_map, land_mask, height_map): biome_masks = biome_masks*blurred_land_mask - if self.useall: + if useall: plt.figure(dpi=150, figsize=(5, 5)) plt.imshow(biome_masks[6], cmap="gray") @@ -687,7 +713,7 @@ def three(self, masked_biome_colour_map, biome_map, land_mask, height_map): biome_height_map = self.apply_height_map(masked_biome_colour_map, height_map, height_map, land_mask) new_biome_height_map = self.apply_height_map(masked_biome_colour_map, adjusted_height_map, adjusted_height_map, land_mask) - if self.useall: + if useall: fig, ax = plt.subplots(1 ,2) fig.set_dpi(150) fig.set_size_inches(10, 5) @@ -697,9 +723,7 @@ def three(self, masked_biome_colour_map, biome_map, land_mask, height_map): ax[1].imshow(new_biome_height_map[0]) ax[1].set_title("After") - return adjusted_height_map, biome_masks - - def four(self, biome_map, vor_map, adjusted_height_map, land_mask, biome_colour_map): + ## Rivers ## Boundaries print('Generating Height Map Filters: Rivers... (may take a while...)') @@ -723,102 +747,9 @@ def four(self, biome_map, vor_map, adjusted_height_map, land_mask, biome_colour_ land_mask_colour = np.repeat(river_land_mask[:, :, np.newaxis], 3, axis=-1) rivers_biome_colour_map = land_mask_colour*biome_colour_map + (1-land_mask_colour)*sea_colour - if self.useall: + if useall: plt.figure(dpi=150, figsize=(5, 5)) plt.imshow(rivers_biome_colour_map) - - # TODO: make the rivers separate from the oceans, after this glue them together - return rivers_biome_colour_map, river_land_mask, adjusted_height_river_map - - def five(self, river_land_mask, adjusted_height_river_map, biome_masks): - ## Trees and Vegetation - trees = self.create_trees(river_land_mask, adjusted_height_river_map, biome_masks, tree_densities) - # Example - if self.useall: - low_density_trees = self.generate_trees(1000, self.size) - medium_density_trees = self.generate_trees(5000, self.size) - high_density_trees = self.generate_trees(25000, self.size) - - plt.figure(dpi=150, figsize=(10, 3)) - plt.subplot(131) - plt.scatter(*low_density_trees.T, s=1) - plt.title("Low Density Trees") - plt.xlim(0, 256) - plt.ylim(0, 256) - - plt.subplot(132) - plt.scatter(*medium_density_trees.T, s=1) - plt.title("Medium Density Trees") - plt.xlim(0, 256) - plt.ylim(0, 256) - - plt.subplot(133) - plt.scatter(*high_density_trees.T, s=1) - plt.title("High Density Trees") - plt.xlim(0, 256) - plt.ylim(0, 256) - plt.figure(dpi=150, figsize=(5, 5)) - - for k in range(len(biome_names)): - plt.scatter(*trees[k].T, s=0.15, c="red") - return trees - - def __init__(self, size, map_seed=762345, n=256, **kwargs): - """ - Generates a map! :) - - Parameters - ---------- - size : int - The size of the map to generate! - PLEASE NOTE: I am not fully sure what this specifically does. From testing I have found - out a possibility that it is just the resolution of the map and not actually zoomed in. - map_seed : int, optional - The seed of the map, by default 762345 - n : int, optional - I don't know what this is, may/may not be linked to the size above, by default 256 - - Kwargs - ------ - useall : bool, optional - Whether or not to use matplotlib to save all steps of the process or just the finished result, by default False (just show finished result) - showAtEnd : bool, optional - Whether or not to show using matplotlib the finished result (and possibly the rest of the steps, see `useall`), by default False - generateTrees : bool, optional - Whether or not to generate trees. If no then will output blanks where the trees output should be below, defaults to True - - Returns - ------- - tuple(list[numpy arrays/lists], numpy array) - [ - out (rounded and scaled from 1-10, list), - colour_map (numpy array, out before rounding and scaling, also contains colours), - rivers_biome_colour_map, (numpy array, ???), - adjusted_height_river_map, (numpy array, ???), - river_land_mask (numpy array, ???), - biome_masks (numpy array, ???) - ], trees (list[numpy array (for each biome name)], this has all the biomes and the trees positions in them.) - """ - # setting params - if map_seed == None: self.map_seed = randint(0, 999999) - else: self.map_seed = map_seed - np.random.seed(self.map_seed) - parseKWs(kwargs, ['useall', 'showAtEnd', 'generateTrees']) - self.useall = kwargs.get('useall', False) - self.size = size - - temperature_cells, precipitation_cells, biomes, vor_map, = self.one() - - masked_biome_colour_map, biome_map, land_mask, biome_colour_map, height_map = self.two(temperature_cells, precipitation_cells, biomes, vor_map) - - adjusted_height_map, biome_masks = self.three(masked_biome_colour_map, biome_map, land_mask, height_map) - - rivers_biome_colour_map, river_land_mask, adjusted_height_river_map = self.four(biome_map, vor_map, adjusted_height_map, land_mask, biome_colour_map) - - if kwargs.get('generateTrees', True): - trees = self.five(river_land_mask, adjusted_height_river_map, biome_masks) - else: - trees = [] # colour_map = apply_height_map(rivers_biome_colour_map, adjusted_height_river_map, adjusted_height_river_map, river_land_mask) # plt.imshow(colour_map[0]) @@ -826,9 +757,45 @@ def __init__(self, size, map_seed=762345, n=256, **kwargs): # im = Image.fromarray(colour_map[0].clip(0, 255).astype(np.uint8)) # im.save("figures/10.png") + ## Trees and Vegetation + if generateTrees: + trees = self.create_trees(river_land_mask, adjusted_height_river_map, biome_masks, tree_densities) + # Example + if useall: + low_density_trees = self.generate_trees(1000, size) + medium_density_trees = self.generate_trees(5000, size) + high_density_trees = self.generate_trees(25000, size) + + plt.figure(dpi=150, figsize=(10, 3)) + plt.subplot(131) + plt.scatter(*low_density_trees.T, s=1) + plt.title("Low Density Trees") + plt.xlim(0, 256) + plt.ylim(0, 256) + + plt.subplot(132) + plt.scatter(*medium_density_trees.T, s=1) + plt.title("Medium Density Trees") + plt.xlim(0, 256) + plt.ylim(0, 256) + + plt.subplot(133) + plt.scatter(*high_density_trees.T, s=1) + plt.title("High Density Trees") + plt.xlim(0, 256) + plt.ylim(0, 256) + plt.figure(dpi=150, figsize=(5, 5)) + + for k in range(len(biome_names)): + plt.scatter(*trees[k].T, s=0.15, c="red") + else: + trees = [] + colour_map = self.apply_height_map(rivers_biome_colour_map, adjusted_height_river_map, adjusted_height_river_map, river_land_mask) - if kwargs.pop('showAtEnd', False): + print('Finishing up generation...') + + if showAtEnd: plt.imshow(colour_map[0]) plt.show() @@ -838,3 +805,7 @@ def __init__(self, size, map_seed=762345, n=256, **kwargs): height_map = norm_map * scaling_factor # Convert to heights out = [[round(j) for j in i] for i in height_map] self.outs = ([out, colour_map, rivers_biome_colour_map, adjusted_height_river_map, river_land_mask, biome_masks], trees) + self.map = self.outs[0][0] + self.trees = self.tolist(self.outs[1]) + self.structures = [] + # self.generate_structures() diff --git a/utils/world.py b/utils/world.py index 1743c0d..a9778a4 100644 --- a/utils/world.py +++ b/utils/world.py @@ -1,7 +1,7 @@ import json, re from os.path import exists, join from random import choice -from math import floor, sqrt +from math import floor, sqrt, ceil from copy import deepcopy from shutil import copytree @@ -21,7 +21,7 @@ def create_iid(): return f'{"".join([r() for _ in range(8)])}-{"".join([r() for _ in range(4)])}-11ee-{"".join([r() for _ in range(4)])}-{"".join([r() for _ in range(12)])}' class World: - def __init__(self, filename, name='', idea='', size=None, size2=50, quality=500, override=False, make_new=True): + def __init__(self, filename, name='', idea='', size=None, size2=50, quality=None, override=False, make_new=True): """ A World! @@ -34,12 +34,13 @@ def __init__(self, filename, name='', idea='', size=None, size2=50, quality=500, idea : str the idea of the world. size : int - The amount of layers to create. + The amount of levels to create (in a square). size2 : int, optional The size of the world "chunks", by default 50 (ldtk blocks) quality : int, optional - The quality of the terrain generation. Also puts a limit on how much output it has. Defaults to 500 + The quality of the terrain generation. Also puts a limit on how much output it has. Think of this as the amount of pixels the output generates, and the size is the size of the chunks. + If you leave this, it will make this number `size * size2` which is what you want 100% of the time. override : bool, optional Whether or not to override the currently saved level with the same name (if there is one), by default False make_new : bool, optional @@ -48,11 +49,6 @@ def __init__(self, filename, name='', idea='', size=None, size2=50, quality=500, path = (folder+filename).replace('/', '\\') if not path.endswith('\\'): path += '\\' self.path = path - if (not exists(path) or override) and not make_new: - if name == '' or idea == '' or size == None: - raise KeyError('You MUST have name, idea and size args OR turn make_new on OR turn override off because the file does not exist or overrride is on!') - self.name = name - self.idea = idea self.data = {} if exists(path) and not override: self.data = json.load(open(path+'world.ldtk', 'r')) @@ -60,8 +56,13 @@ def __init__(self, filename, name='', idea='', size=None, size2=50, quality=500, self.name = dat['name'] self.idea = dat['idea'] elif make_new: - m = Map(quality, None) - print('Generating file...') + if name == '' or idea == '' or size == None: + raise KeyError('You MUST have name, idea and size args OR turn make_new on OR turn override off because the file does not exist or overrride is on!') + self.name = name + self.idea = idea + if quality == None: quality = int((ceil(sqrt(size)) * size2)*2) # TODO: Make this more efficient by generating a rectangle, not just a square + m = MapGen(quality) + print('Generating map...') self.data = empty.copy() self.data['tutorialDesc'] = 'ERROR!!' # So that if you look at the file and this hasn't finished it's setup then... Oh no! MAYBE TODO: error codes (300 error) self.data['worldLayout'] = choice(['Gridvania', 'Free']) @@ -76,10 +77,15 @@ def __init__(self, filename, name='', idea='', size=None, size2=50, quality=500, level['uid'] = j level['worldX'] = (j%size3) * size2 * 16 level['worldY'] = floor(j/size3) * size2 * 16 + level["pxWid"] = 16 * size2 + level["pxHei"] = 16 * size2 layer = level['layerInstances'][[i['__identifier'] for i in level['layerInstances']].index('World')] l = m(size2, size2, (j%size3)*size2, floor(j/size3)*size2) layer['intGridCsv'] = [] for i in l: layer['intGridCsv'].extend(i) + for i in level['layerInstances']: + i["__cWid"] = size2 + i["__cHei"] = size2 level['layerInstances'][[i['__identifier'] for i in level['layerInstances']].index('World')] = layer """entities = level['layerInstances'][[i['__identifier'] for i in level['layerInstances']].index('Entities')] @@ -111,7 +117,7 @@ def __init__(self, filename, name='', idea='', size=None, size2=50, quality=500, layer2 = level['layerInstances'][[i['__identifier'] for i in level['layerInstances']].index('Structures')] layer2['intGridCsv'] = [] #l2 = find_plateaus(l) - l2 = m.get_structs(size2, size2, (j%size3)*size2, floor(j/size3)*size2) + l2 = [i[size2:size2+(j%size3)*size2] for i in m.trees[size2:size2+floor(j/size3)*size2]] for i in l2: layer2['intGridCsv'].extend(i) level['layerInstances'][[i['__identifier'] for i in level['layerInstances']].index('Structures')] = layer2