1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

js: codegen & vlib fixes, replace the Game of Life CLI example (#12272)

This commit is contained in:
playX
2021-10-22 22:03:19 +03:00
committed by GitHub
parent 8a4756819a
commit 864d6eae6b
6 changed files with 107 additions and 23 deletions

View File

@ -1,25 +1,85 @@
module main
import term
import rand
import time
import automaton
fn print_automaton(a &automaton.Automaton) {
for y := 1; y < a.field.maxy; y++ {
mut s := ' '
for x := 1; x < a.field.maxx; x++ {
cell := a.field.get(x, y)
s += if cell == 1 { '@' } else { '.' }
}
println(s)
const (
cell = ''
nothing = ' '
switches = {
cell: nothing
nothing: cell
}
println('')
transformers = [nothing, cell]
)
struct Game {
mut:
grid [][]string
}
fn (g Game) get_surrounding_alive_count(x int, y int) int {
mut count := 0
for i := x - 1; i <= x + 1; i++ {
for j := y - 1; j <= y + 1; j++ {
if (i != x || j != y) && i >= 0 && j >= 0 && i < g.grid.len && j < g.grid[x].len {
if g.grid[i][j] == cell {
count++
}
}
}
}
return count
}
fn (mut g Game) evolve() {
mut temp_grid := [][]string{}
for x in 0 .. g.grid.len {
temp_grid << []string{}
for y in 0 .. g.grid[x].len {
count := g.get_surrounding_alive_count(x, y)
if count == 3 || ((g.grid[x][y] == cell) && count == 2) {
temp_grid[x] << cell
} else {
temp_grid[x] << nothing
}
}
}
g.grid = temp_grid
}
fn (mut g Game) display() {
for y in 0 .. g.grid[0].len {
mut line := ''
for x in 0 .. g.grid.len {
line += g.grid[x][y]
}
println(line)
}
}
fn new_game() Game {
w, h := term.get_terminal_size()
mut grid := [][]string{}
for x in 0 .. w {
grid << []string{}
for _ in 0 .. h {
is_live := rand.f64() > 0.82
icon := transformers[int(is_live)]
grid[x] << icon
}
}
return Game{grid}
}
fn main() {
mut a := automaton.gun()
mut g := new_game()
g.display()
for {
a.update()
print_automaton(a)
g.evolve()
term.erase_clear()
g.display()
time.sleep(100 * time.millisecond)
}
}