Last active
December 4, 2019 07:27
-
-
Save tomowarkar/3bb50298393b66148e43e00238e52083 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"math/rand" | |
"time" | |
"github.com/nsf/termbox-go" | |
) | |
const coldef = termbox.ColorDefault | |
// Maze ... | |
type Maze struct { | |
width int | |
height int | |
field [][]int | |
} | |
// InitMaze ... | |
func (m *Maze) InitMaze(h, w int) { | |
m.width = w | |
m.height = h | |
m.field = make([][]int, h) | |
for i := 0; i < h; i++ { | |
m.field[i] = make([]int, w) | |
} | |
} | |
// RandMaze ... | |
func (m *Maze) RandMaze() { | |
rand.Seed(time.Now().UnixNano()) | |
for j := 0; j < m.height; j++ { | |
for i := 0; i < m.width; i++ { | |
m.field[j][i] = rand.Intn(3) | |
} | |
} | |
} | |
// DrawField ... | |
func (m Maze) DrawField() { | |
termbox.Clear(coldef, coldef) | |
for j := 0; j < m.height; j++ { | |
for i := 0; i < m.width; i++ { | |
if m.field[j][i] == 0 { | |
termbox.SetCell(i*2, j, '⚪', coldef, coldef) | |
} else if m.field[j][i] == 1 { | |
termbox.SetCell(i*2, j, '🔵', coldef, coldef) | |
} else { | |
termbox.SetCell(i*2, j, '🔴', coldef, coldef) | |
} | |
} | |
} | |
termbox.Flush() | |
} | |
//key event | |
func keyEventLoop(kch chan termbox.Key) { | |
for { | |
switch ev := termbox.PollEvent(); ev.Type { | |
case termbox.EventKey: | |
kch <- ev.Key | |
default: | |
} | |
} | |
} | |
//time event | |
func timeEventLoop(tch chan bool, span int) { | |
for { | |
tch <- true | |
time.Sleep(time.Duration(span) * time.Millisecond) | |
} | |
} | |
func mainLoop(mz Maze, tch chan bool, kch chan termbox.Key) { | |
for { | |
select { | |
case key := <-kch: //key event | |
switch key { | |
case termbox.KeyEsc, termbox.KeyCtrlC: //end event | |
return | |
} | |
case <-tch: //time event | |
mz.RandMaze() | |
mz.DrawField() | |
break | |
default: | |
} | |
} | |
} | |
func main() { | |
err := termbox.Init() | |
if err != nil { | |
panic(err) | |
} | |
defer termbox.Close() | |
var maze Maze | |
maze.InitMaze(10, 10) | |
kch := make(chan termbox.Key) | |
tch := make(chan bool) | |
go keyEventLoop(kch) | |
go timeEventLoop(tch, 500) | |
mainLoop(maze, tch, kch) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment