Skip to content

Instantly share code, notes, and snippets.

@luizdepra
Created September 6, 2012 14:17
Show Gist options
  • Save luizdepra/3656743 to your computer and use it in GitHub Desktop.
Save luizdepra/3656743 to your computer and use it in GitHub Desktop.
Map Generator
# -*- coding: utf-8 -*-
# -- MAPGEN.PY --
import sys
import math
import random
class Map:
# consts
_FOUR_DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def __init__(self, width, height):
self._width = width
self._height = height
self._data = [['#' for x in xrange(width)] for y in xrange(height)]
self._visited = []
for y in xrange(self._height):
for x in xrange(self._width):
self._visited.append((x, y))
def flood(self, x, y, cx, cy, max_distance):
self._data[y][x] = '.'
self._visited.remove((x, y))
for t in self._FOUR_DIRECTIONS:
nx, ny = x + t[0], y + t[1]
if self._visited.count((nx, ny)) == 0:
continue
distance = abs(nx - cx) + abs(ny - cy)
if distance > max_distance:
continue
probability = 1 - (distance / max_distance)
if random.random() <= probability:
self.flood(nx, ny, cx, cy, max_distance)
def spawnWater(self, seeds, max_distance):
for i in xrange(seeds):
k = random.randint(0, len(self._visited) - 1)
t = self._visited[k]
x, y = t[0], t[1]
self.flood(x, y, x, y, max_distance * 1.0)
def printMap(self):
for y in xrange(self._height):
for x in xrange(self._width):
sys.stdout.write(self._data[y][x])
sys.stdout.write('\n')
# Max Distance need to be float
map = Map(32,32)
map.spawnWater(8, 6)
map.printMap()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment