Skip to content

Instantly share code, notes, and snippets.

@prabirshrestha
Last active September 14, 2015 04:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prabirshrestha/2d206d9575340ca34fc1 to your computer and use it in GitHub Desktop.
Save prabirshrestha/2d206d9575340ca34fc1 to your computer and use it in GitHub Desktop.
termbox-go with (partial) react style rendering.
package main
import (
"time"
"github.com/nsf/termbox-go"
)
type appState struct {
endEventLoop bool
ch rune
fg termbox.Attribute
}
func main() {
eventQueue, state, err := create()
if err != nil {
panic(err)
}
defer close()
start(eventQueue, state)
}
func create() (chan termbox.Event, *appState, error) {
err := termbox.Init()
if err != nil {
return nil, nil, err
}
return make(chan termbox.Event), getInitialState(), nil
}
func getInitialState() *appState {
return &appState{
endEventLoop: false,
ch: 'a',
fg: termbox.ColorRed,
}
}
func close() {
termbox.Close()
}
func start(eventQueue chan termbox.Event, state *appState) {
go func() {
for {
eventQueue <- termbox.PollEvent()
}
}()
render(state)
for !state.endEventLoop {
if shouldUpdate := update(eventQueue, state); shouldUpdate {
render(state)
}
}
}
func update(eventQueue chan termbox.Event, state *appState) (shouldUpdate bool) {
shouldUpdate = true
colorChangeTick := time.NewTicker(2 * time.Second)
select {
case event := <-eventQueue:
switch event.Type {
case termbox.EventKey:
switch event.Key {
case termbox.KeyCtrlC, termbox.KeyEsc:
state.endEventLoop = true
default:
state.ch = event.Ch
}
case termbox.EventError:
panic(event.Err)
}
case <-colorChangeTick.C:
if state.fg == termbox.ColorRed {
state.fg = termbox.ColorBlue
} else {
state.fg = termbox.ColorRed
}
}
return
}
func render(state *appState) {
termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
if state.endEventLoop {
termbox.Flush()
return
}
w, h := termbox.Size()
termbox.SetCell(w/2, h/2, state.ch, state.fg, termbox.ColorDefault)
termbox.Flush()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment