Skip to content

Instantly share code, notes, and snippets.

@zaltoprofen
Created October 14, 2016 09:50
Show Gist options
  • Save zaltoprofen/627d437c15a1044ad250b66ac5c1baa9 to your computer and use it in GitHub Desktop.
Save zaltoprofen/627d437c15a1044ad250b66ac5c1baa9 to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"flag"
"log"
"math/rand"
"os"
"time"
termbox "github.com/nsf/termbox-go"
)
var (
numBeers = flag.Int("num-beers", 100, "a number of beers")
timeRaining = flag.Int64("time", 10, "a time raining beers [second]")
)
func main() {
flag.Parse()
os.Exit(_main())
}
func printError(err error) {
log.Println("error:", err)
}
var invalidArguments = errors.New("invalid arguments")
func _main() int {
if *numBeers <= 0 || *timeRaining <= 0 {
printError(invalidArguments)
flag.PrintDefaults()
return 1
}
err := termbox.Init()
if err != nil {
printError(err)
return 1
}
defer termbox.Close()
go mainLoop()
<-time.After(time.Duration(*timeRaining) * time.Second)
return 0
}
type point struct {
x, y int
vy int
}
func cheers(beers []point) {
w, h := termbox.Size()
for i := range beers {
beers[i].x = rand.Intn(w)
beers[i].y = rand.Intn(h)
beers[i].vy = rand.Intn(3) + 1
}
}
func printBeers(beers []point) {
for _, b := range beers {
termbox.SetCell(b.x, b.y, rune('🍺'), termbox.ColorDefault, termbox.ColorDefault)
}
}
func moveBeers(beers []point) {
w, h := termbox.Size()
for i := range beers {
b := &beers[i]
b.y += b.vy
if b.y >= h {
b.x = rand.Intn(w)
b.y = 0
b.vy = rand.Intn(3) + 1
}
}
}
func mainLoop() {
beers := make([]point, *numBeers)
cheers(beers)
for {
c := time.After(50 * time.Millisecond)
termbox.SetCursor(-1, -1)
termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
printBeers(beers)
moveBeers(beers)
termbox.Flush()
<-c
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment