Skip to content

Instantly share code, notes, and snippets.

@Matt3o12
Created April 16, 2015 17:01
Show Gist options
  • Save Matt3o12/e7d80b635d89bf867198 to your computer and use it in GitHub Desktop.
Save Matt3o12/e7d80b635d89bf867198 to your computer and use it in GitHub Desktop.
Termui - Wiki - ColorRenderers Example
type RandomRendererFactory struct {
Max int
Min int
}
func NewRandomRendererFactory(min, max int) RandomRendererFactory {
return RandomRendererFactory{Min: min, Max: max}
}
func (f RandomRendererFactory) TextRenderer(text string) TextRenderer {
return RandomRenderer{Text: text, Min: f.Min, Max: f.Max}
}
type RandomRenderer struct {
Text string
Min int
Max int
}
func (r RandomRenderer) NormalizedText() string {
return r.Text
}
func (r RandomRenderer) Render(lastColor, background Attribute) RenderedSequence {
return r.RenderSequence(0, -1, lastColor, background)
}
func (r RandomRenderer) nextSequence(text []rune) (Attribute, int) {
var nextGuess int
// if RandomRender has not been properly initialzied
// (i.e. without min/max), let's just assume: 1
if r.Max == 0 && r.Min == 0 {
nextGuess = 1
} else {
nextGuess = r.Min + rand.Intn(r.Max-r.Min)
}
if nextGuess > len(text) {
nextGuess = len(text)
}
color := Attribute(rand.Intn(9))
return color, nextGuess
}
func (r RandomRenderer) RenderSequence(start, end int, lastColor, background Attribute) RenderedSequence {
runes := []rune(r.Text)
if end < 0 {
end = len(runes)
}
runes = runes[start:end]
offset := 0
var colorSeq []ColorSubsequence
for offset < len(runes) {
color, length := r.nextSequence(runes[offset:])
seq := ColorSubsequence{Color: color, Start: offset, End: offset + length}
colorSeq = append(colorSeq, seq)
offset += length
}
seq := RenderedSequence{NormalizedText: string(runes)}
seq.LastColor = lastColor
seq.BackgroundColor = background
seq.Sequences = colorSeq
return seq
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment