Saturday, June 20, 2020

Using the 'tcell' graphics-in-a-terminal Library in a GoLang Program

package main
/*
 This code draws a single character (or 'rune', or 'glyph') at a single
 location on a terminal window in Debian GNU/Linux.
*/

import (
 "fmt"
 "os"
 "time"
 "github.com/gdamore/tcell"
)

func main() {
 // Create a "canvas" (a window, frame) on which to draw
 s, e := tcell.NewScreen()

 // Check for some error situations; exit if need be
 if e != nil {
  fmt.Fprintf(os.Stderr, "%v\n", e)
  os.Exit(1)
 }
 if e = s.Init(); e != nil {
  fmt.Fprintf(os.Stderr, "%v\n", e)
  os.Exit(1)
 }

 // Set foreground and background colors of "canvas"
 s.SetStyle(tcell.StyleDefault.
  Foreground(tcell.ColorWhite).
  Background(tcell.ColorBlack))

 // Clear the "canvas"
 s.Clear()

 // Set foreground and background colors of box
 fg := tcell.ColorYellow
 bg := tcell.ColorBlue

 // Set the coordinates for where we'll draw our character ('glyph', 'rune')
 x := 10
 y := 20

 st := tcell.StyleDefault
 st = st.Background(bg)
 st = st.Foreground(fg)

 glyph := rune('W')

 s.SetCell(x, y, st, glyph)

 // Display the prepared "canvas"
 s.Show()

 // Pause X seconds before resetting "graphics" screen to normal
 // Number of time units times length of time units
 duration := time.Duration(3) * time.Second
 time.Sleep(duration)

 //Reset screen to normal
 s.Fini()
}

No comments: