Created
March 28, 2016 10:40
-
-
Save Mekire/1b66c63085e4bbe534fd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| import random | |
| import bisect | |
| import pygame as pg | |
| MAP_SIZE = (30, 15) | |
| TILE_SIZE = (32, 32) | |
| TEXTURES = ["w", "d", "g", "c"] | |
| TEXTURE_DICT = { | |
| "w" : pg.Color("skyblue"), | |
| "d" : pg.Color("sandybrown"), | |
| "g" : pg.Color("lightgreen"), | |
| "c" : pg.Color("slategray") | |
| } | |
| ADJACENT_CHANCE = { | |
| ("w","w") : (("w",0.8), ("d",0.0), ("g", 0.2), ("c",0.0)), | |
| ("w","d") : (("w",0.0), ("d",0.0), ("g", 1), ("c",0.0)), | |
| ("w","g") : (("w",0.5), ("d",0.0), ("g", 0.5), ("c",0.0)), | |
| ("w","c") : (("w",0.0), ("d",1), ("g", 0.0), ("c",0.0)), | |
| ("d","d") : (("w",0.0), ("d",0.6), ("g", 0.35), ("c",0.05)), | |
| ("d","g") : (("w",0.0), ("d",0.45), ("g", 0.525), ("c",0.025)), | |
| ("d","c") : (("w",0.0), ("d",1), ("g", 0.0), ("c",0.0)), | |
| ("g","g") : (("w",0.15), ("d",0.15), ("g", 0.70), ("c",0.0)), | |
| ("g","c") : (("w",0.0), ("d",1), ("g", 0.0), ("c",0.0)), | |
| ("c","c") : (("w",0.0), ("d",1), ("g", 0.0), ("c",0.0)) | |
| } | |
| def make_map(size): | |
| nodes = {} | |
| for j in range(size[1]): | |
| for i in range(size[0]): | |
| up = nodes.get((i,j-1), random.choice(TEXTURES)) | |
| prev = nodes.get((i-1,j), random.choice(TEXTURES)) | |
| choice = CHANCE_DICT.get((up,prev)) or CHANCE_DICT.get((prev,up)) | |
| nodes[i,j] = choice() | |
| return nodes | |
| def draw_tile(surface, coords, texture): | |
| x, y = coords | |
| color = TEXTURE_DICT[texture] | |
| rect = ((x*TILE_SIZE[0], y*TILE_SIZE[1]), TILE_SIZE) | |
| surface.fill(color, rect) | |
| def weighted_chooser(items): | |
| """ | |
| Returns a function that makes a weighted random choice from items. | |
| Stolen from SO. | |
| """ | |
| added_weights = [] | |
| last_sum = 0 | |
| for item, weight in items: | |
| last_sum += weight | |
| added_weights.append(last_sum) | |
| def choice(): | |
| roll = random.random() * last_sum | |
| return items[bisect.bisect(added_weights, roll)][0] | |
| return choice | |
| def main(): | |
| global CHANCE_DICT | |
| CHANCE_DICT = {k:weighted_chooser(v) for k,v in ADJACENT_CHANCE.items()} | |
| pg.init() | |
| screen_size = MAP_SIZE[0]*TILE_SIZE[0], MAP_SIZE[1]*TILE_SIZE[1], | |
| screen = pg.display.set_mode(screen_size) | |
| tiles = make_map(MAP_SIZE) | |
| for coords,texture in tiles.items(): | |
| draw_tile(screen, coords, texture) | |
| pg.display.update() | |
| while pg.event.wait().type != pg.QUIT: | |
| pass | |
| pg.quit() | |
| sys.exit() | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment