| 1 | fn clear() { |
| 2 | JS.console.clear() |
| 3 | } |
| 4 | |
| 5 | const w = 30 |
| 6 | const h = 30 |
| 7 | |
| 8 | fn get(game [][]bool, x int, y int) bool { |
| 9 | if y < 0 || x < 0 { |
| 10 | return false |
| 11 | } |
| 12 | if y >= h || x >= w { |
| 13 | return false |
| 14 | } |
| 15 | |
| 16 | return game[y][x] |
| 17 | } |
| 18 | |
| 19 | fn neighbours(game [][]bool, x int, y int) int { |
| 20 | mut count := 0 |
| 21 | if get(game, x - 1, y - 1) { |
| 22 | count++ |
| 23 | } |
| 24 | if get(game, x, y - 1) { |
| 25 | count++ |
| 26 | } |
| 27 | if get(game, x + 1, y - 1) { |
| 28 | count++ |
| 29 | } |
| 30 | if get(game, x - 1, y) { |
| 31 | count++ |
| 32 | } |
| 33 | if get(game, x + 1, y) { |
| 34 | count++ |
| 35 | } |
| 36 | if get(game, x - 1, y + 1) { |
| 37 | count++ |
| 38 | } |
| 39 | if get(game, x, y + 1) { |
| 40 | count++ |
| 41 | } |
| 42 | if get(game, x + 1, y + 1) { |
| 43 | count++ |
| 44 | } |
| 45 | return count |
| 46 | } |
| 47 | |
| 48 | fn step(game [][]bool) [][]bool { |
| 49 | mut new_game := [][]bool{} |
| 50 | for y, row in game { |
| 51 | mut new_row := []bool{} |
| 52 | new_game[y] = new_row |
| 53 | for x, cell in row { |
| 54 | count := neighbours(game, x, y) |
| 55 | new_row[x] = (cell && count in [2, 3]) || count == 3 |
| 56 | } |
| 57 | } |
| 58 | return new_game |
| 59 | } |
| 60 | |
| 61 | fn row_str(row []bool) string { |
| 62 | mut str := '' |
| 63 | for cell in row { |
| 64 | if cell { |
| 65 | str += '◼ ' |
| 66 | } else { |
| 67 | str += '◻ ' |
| 68 | } |
| 69 | } |
| 70 | return str |
| 71 | } |
| 72 | |
| 73 | fn show(game [][]bool) { |
| 74 | clear() |
| 75 | for row in game { |
| 76 | println(row_str(row)) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | // TODO: Remove `fn main` once vet supports scripts |
| 81 | fn main() { |
| 82 | mut game := [][]bool{len: h, init: []bool{len: w}} |
| 83 | |
| 84 | game[11][15] = true |
| 85 | game[11][16] = true |
| 86 | game[12][16] = true |
| 87 | game[10][21] = true |
| 88 | game[12][20] = true |
| 89 | game[12][21] = true |
| 90 | game[12][22] = true |
| 91 | |
| 92 | JS.setInterval(fn () { |
| 93 | show(game) |
| 94 | game = step(game) |
| 95 | }, 500) |
| 96 | } |
| 97 | |