Maze generation: Difference between revisions
Content added Content deleted
m (Delphi small fixes of my code) |
(Updated to work with Nim 1.4: added missing parameter type, import "random" instead of "math", changed "random" to "rand", changed ".. <" to "..<".) |
||
Line 5,101: | Line 5,101: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
{{trans|D}} |
{{trans|D}} |
||
<lang nim>import |
<lang nim>import random, sequtils, strutils |
||
randomize() |
randomize() |
||
template newSeqWith(len: int, init: expr): expr = |
|||
var result {.gensym.} = newSeq[type(init)](len) |
|||
for i in 0 .. <len: |
|||
result[i] = init |
|||
result |
|||
iterator randomCover[T](xs: openarray[T]): T = |
iterator randomCover[T](xs: openarray[T]): T = |
||
var js = toSeq 0..xs.high |
var js = toSeq 0..xs.high |
||
for i in countdown(js.high, 0): |
for i in countdown(js.high, 0): |
||
let j = random(i |
let j = random(i) |
||
swap(js[i], js[j]) |
swap(js[i], js[j]) |
||
for j in js: |
for j in js: |
||
Line 5,127: | Line 5,121: | ||
ver = newSeqWith(h, newSeqWith(w, "| ") & "|") |
ver = newSeqWith(h, newSeqWith(w, "| ") & "|") |
||
proc walk(x, y) = |
proc walk(x, y: int) = |
||
vis[y][x] = true |
vis[y][x] = true |
||
for p in [[x-1,y], [x,y+1], [x+1,y], [x,y-1]].randomCover: |
for p in [[x-1,y], [x,y+1], [x+1,y], [x,y-1]].randomCover: |
||
if p[0] notin 0 .. |
if p[0] notin 0 ..< w or p[1] notin 0 ..< h or vis[p[1]][p[0]]: continue |
||
if p[0] == x: hor[max(y, p[1])][x] = "+ " |
if p[0] == x: hor[max(y, p[1])][x] = "+ " |
||
if p[1] == y: ver[y][max(x, p[0])] = " " |
if p[1] == y: ver[y][max(x, p[0])] = " " |
||
walk p[0], p[1] |
walk p[0], p[1] |
||
walk |
walk rand(0..<w), rand(0..<h) |
||
for a,b in zip(hor, ver & @[""]).items: |
for a,b in zip(hor, ver & @[""]).items: |
||
echo join(a & "+\n" & b)</lang> |
echo join(a & "+\n" & b)</lang> |
||
{{out}} |
|||
Example output: |
Example output: |
||
<pre>+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ |
<pre>+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ |