Skip to content

Instantly share code, notes, and snippets.

@Mekire
Last active March 28, 2016 06:56
Show Gist options
  • Save Mekire/77fdccead0d517ba6df2 to your computer and use it in GitHub Desktop.
Save Mekire/77fdccead0d517ba6df2 to your computer and use it in GitHub Desktop.
import sys
import random
import pygame as pg
MAP_SIZE = 20, 10
TILE_SIZE = 50, 50
CHANCE_OF_SAME = 0.75
TEXTURES = ["water", "dirt", "grass", "coal"]
TEXTURE_DICT = {"water" : pg.Color("skyblue"),
"dirt" : pg.Color("sandybrown"),
"grass" : pg.Color("lightgreen"),
"coal" : pg.Color("grey")}
NEIGHBORS = [(-1,1), (0,1), (1,1), (-1,0), (1,0), (-1,-1), (0,-1), (1,-1)]
class Node(object):
def __init__(self, coords, previous=None):
self.coords = coords
self.texture = self.get_texture(previous)
def get_texture(self, previous):
if previous is not None:
if random.random() < CHANCE_OF_SAME:
texture = previous.texture
else:
without_previous = TEXTURES[:]
without_previous.remove(previous.texture)
texture = random.choice(without_previous)
else:
texture = random.choice(TEXTURES)
return texture
def make_map(size, start_node=(0,0)):
nodes = []
stack = [start_node]
closed = set((start_node,))
previous = None
while stack:
current = Node(stack.pop(), previous)
neighbors = NEIGHBORS[:]
random.shuffle(neighbors)
for step_x,step_y in neighbors:
x, y = current.coords[0]+step_x, current.coords[1]+step_y
if (x,y) not in closed and 0 <= x < size[0] and 0 <= y < size[1]:
stack.append((x,y))
closed.add((x,y))
nodes.append(current)
previous = current
return nodes
def draw_tile(surface, tile):
x, y = tile.coords
color = TEXTURE_DICT[tile.texture]
rect = ((x*TILE_SIZE[0], y*TILE_SIZE[1]), TILE_SIZE)
surface.fill(color, rect)
def main():
pg.init()
screen_size = MAP_SIZE[0]*TILE_SIZE[0], MAP_SIZE[1]*TILE_SIZE[1],
screen = pg.display.set_mode(screen_size)
clock = pg.time.Clock()
tiles = make_map(MAP_SIZE, (10,5))
for tile in tiles:
pg.event.pump()
draw_tile(screen, tile)
clock.tick(60)
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