Debian Codegraph @

demos/boxes/boxes.go

raw symbols SCIP
1 // Copyright 2025 The TCell Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // boxes just displays random colored boxes on your terminal screen.
16 // Press escape or control-q to exit the program.
17 package main
18
19 import (
20 "fmt"
21 "math/rand"
22 "os"
23 "time"
24
25 "github.com/gdamore/tcell/v3"
26 "github.com/gdamore/tcell/v3/color"
27 )
28
29 func makeBox(s tcell.Screen) {
30 w, h := s.Size()
31
32 if w == 0 || h == 0 {
33 return
34 }
35
36 glyphs := []string{"@", "#", "&", "*", "=", "%", "Z", "A"}
37
38 lx := rand.Int() % w
39 ly := rand.Int() % h
40 lw := rand.Int() % (w - lx)
41 lh := rand.Int() % (h - ly)
42 st := tcell.StyleDefault
43 gl := " "
44 if s.Colors() > 256 {
45 rgb := tcell.NewHexColor(int32(rand.Int() & 0xffffff))
46 st = st.Background(rgb)
47 } else if s.Colors() > 1 {
48 st = st.Background(color.Color(rand.Int()%s.Colors()) | color.IsValid)
49 } else {
50 st = st.Reverse(rand.Int()%2 == 0)
51 gl = glyphs[rand.Int()%len(glyphs)]
52 }
53
54 for row := range lh {
55 for col := range lw {
56 s.PutStrStyled(lx+col, ly+row, gl, st)
57 }
58 }
59 s.Show()
60 }
61
62 var (
63 count = 0
64 interval = time.Millisecond * 5
65 drawTime time.Duration
66 )
67
68 func main() {
69
70 tcell.SetEncodingFallback(tcell.EncodingFallbackASCII)
71 s, e := tcell.NewScreen()
72 if e != nil {
73 fmt.Fprintf(os.Stderr, "%v\n", e)
74 os.Exit(1)
75 }
76 if e = s.Init(); e != nil {
77 fmt.Fprintf(os.Stderr, "%v\n", e)
78 os.Exit(1)
79 }
80
81 s.SetStyle(tcell.StyleDefault.
82 Foreground(color.Black).
83 Background(color.White))
84 s.Clear()
85
86 loop:
87 for {
88 select {
89 case ev := <-s.EventQ():
90 switch ev := ev.(type) {
91 case *tcell.EventKey:
92 switch ev.Key() {
93 case tcell.KeyEscape, tcell.KeyCtrlQ:
94 break loop
95 case tcell.KeyCtrlL:
96 s.Sync()
97 }
98 case *tcell.EventResize:
99 s.Sync()
100 }
101 case <-time.After(interval):
102 }
103 start := time.Now()
104 makeBox(s)
105 count++
106 drawTime += time.Since(start)
107 }
108
109 s.Fini()
110 fmt.Printf("Finished %d boxes in %s (drawing time only)\n", count, drawTime)
111 if count > 0 {
112 fmt.Printf("Average is %0.3f ms / box\n", (float64(drawTime)/float64(count))/1000000.0)
113 }
114 }