Okay, let's create a "morphing cube" progress indicator. This one is a bit more visually complex, using a series of characters to simulate a cube that changes shape as the progress increases.
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
// ANSI escape codes
const (
reset = "\x1b[0m"
cyan = "\x1b[36m"
hideCursor = "\x1b[?25l"
showCursor = "\x1b[?25h"
clearLine = "\r\x1b[2K"
)
// MorphingCube represents the state of the cube animation.
type MorphingCube struct {
frames []string // Different cube shapes
currentFrame int
}
// NewMorphingCube creates a new MorphingCube with predefined frames.
func NewMorphingCube() *MorphingCube {
return &MorphingCube{
frames: []string{
"┌───┐",
"│ │",
"└───┘",
"┌ ┐",
"│ │",
"└ ┘",
"┌───┐",
"│ │",
"└───┘",
"┌ ┐",
"│ │",
"└ ┘",
},
currentFrame: 0,
}
}
// NextFrame advances to the next frame in the animation.
func (c *MorphingCube) NextFrame() {
c.currentFrame = (c.currentFrame + 1) % len(c.frames)
}
// Render prints the current frame of the morphing cube.
func (c *MorphingCube) Render(prefix string, percent float64) {
// Calculate the number of filled cubes based on the percentage.
filledCubes := int(percent * float64(len(c.frames)))
// Build the output string.
output := prefix + cyan
for i := 0; i < filledCubes; i++ {
output += c.frames[i]
}
for i := filledCubes; i < len(c.frames); i++ {
output += " " // Add empty space for unfilled cubes
}
output += reset + fmt.Sprintf(" %6.2f%%", percent*100)
fmt.Print(clearLine) // Clear the line
fmt.Println(output)
}
func main() {
// Hide cursor on start, ensure it's shown on exit
fmt.Print(hideCursor)
defer fmt.Print(showCursor)
// Catch Ctrl+C so we restore the cursor before exit
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
go func() {
<-sigs
fmt.Print(showCursor)
os.Exit(0)
}()
total := 100
cube := NewMorphingCube()
prefix := "Processing: "
for i := 0; i <= total; i++ {
pct := float64(i) / float64(total)
cube.Render(prefix, pct)
cube.NextFrame()
time.Sleep(50 * time.Millisecond)
}
// Finish up
fmt.Print(clearLine)
fmt.Println(prefix + cyan + "┌───┐│ │└───┘" + reset + " 100.00%")
fmt.Print(showCursor)
fmt.Println("Done!")
}
Key improvements and explanations:
- MorphingCube struct: Encapsulates the cube animation logic.
- Frames: The
frames slice holds different cube shapes as strings. This is the core of the animation.
NextFrame(): Cycles through the frames to create the animation.
Render():
- Calculates how many cubes to fill based on the percentage.
- Builds the output string by appending filled and empty cube representations.
- Uses
clearLine to overwrite the previous frame.
- Clear Line:
\r\x1b[2K is used to clear the entire line before printing the new frame. This prevents artifacts from previous frames.
- Color: Uses cyan for the cube.
- Error Handling: Includes the signal handling to restore the cursor on exit.
- Complete Output: The final output ensures the entire cube is displayed when the process is complete.
To run:
- Save as
cube_progress.go.
- Run with
go run cube_progress.go.
This creates a visually interesting progress indicator that should stand out in your CLI application. You can customize the cube frames to create different animations. Experiment with different characters and arrangements to achieve the desired effect.