main.go
This file
Path
examples/space/main.go
134 lines · 2.6 KiB · Go
Last changed by
Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
History of this fileTake it
1package main23import (4 "fmt"5 "image/color"6 "math/rand"7 "os"8 "strings"9 "time"1011 tea "charm.land/bubbletea/v2"12 "charm.land/lipgloss/v2"13)1415// An example to show the FPS count of a moving space-like background.16//17// This was ported from the talented Orhun Parmaksız (@orhun)'s space example18// from his blog post "Why stdout is faster than stderr?".1920type model struct {21 colors [][]color.Color22 lastWidth int23 lastHeight int24 frameCount int25 width int26 height int27}2829func (m model) Init() tea.Cmd {30 return tea.Batch(31 tickCmd(),32 )33}3435func tickCmd() tea.Cmd {36 return tea.Tick(time.Second/60, func(time.Time) tea.Msg {37 return tickMsg{}38 })39}4041type tickMsg struct{}4243func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {44 switch msg := msg.(type) {45 case tea.KeyPressMsg:46 switch msg.String() {47 case "q", "ctrl+c":48 return m, tea.Quit49 }5051 case tea.WindowSizeMsg:52 m.width = msg.Width53 m.height = msg.Height54 if m.width != m.lastWidth || m.height != m.lastHeight {55 m.setupColors()56 m.lastWidth = m.width57 m.lastHeight = m.height58 }5960 case tickMsg:61 m.frameCount++62 return m, tickCmd()63 }6465 return m, nil66}6768func (m *model) setupColors() {69 height := m.height * 2 // double height for half blocks70 m.colors = make([][]color.Color, height)7172 for y := range height {73 m.colors[y] = make([]color.Color, m.width)74 randomnessFactor := float64(height-y) / float64(height)7576 for x := range m.width {77 baseValue := randomnessFactor * (float64(height-y) / float64(height))78 randomOffset := (rand.Float64() * 0.2) - 0.179 value := clamp(baseValue+randomOffset, 0, 1)8081 // Convert value to grayscale color (0-255)82 gray := uint8(value * 255)83 m.colors[y][x] = lipgloss.Color(fmt.Sprintf("#%02x%02x%02x", gray, gray, gray))84 }85 }86}8788func clamp(value, min, max float64) float64 {89 if value < min {90 return min91 }92 if value > max {93 return max94 }95 return value96}9798func (m model) View() tea.View {99 // Title100 title := lipgloss.NewStyle().Bold(true).Render("Space")101102 // Color display103 var s strings.Builder104 height := m.height - 1 // leave one line for title105 for y := range height {106 for x := range m.width {107 xi := (x + m.frameCount) % m.width108 fg := m.colors[y*2][xi]109 bg := m.colors[y*2+1][xi]110 st := lipgloss.NewStyle().Foreground(fg).Background(bg)111 s.WriteString(st.Render("▀"))112 }113 if y < height-1 {114 s.WriteString("\n")115 }116 }117118 v := tea.NewView(strings.Join([]string{119 title,120 s.String(),121 }, "\n"))122 v.AltScreen = true123 return v124}125126func main() {127 p := tea.NewProgram(model{}, tea.WithFPS(120))128129 _, err := p.Run()130 if err != nil {131 fmt.Printf("Error running program: %v", err)132 os.Exit(1)133 }134}