1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
|
// Package randomart generates OpenSSH style randomart images.
package randomart
import (
"bytes"
)
// Dimensions of the generated image.
const (
XDim = 17
YDim = 9
)
const (
start = -1
end = -2
)
// Board is a generated randomart board.
type Board struct {
tiles [YDim][XDim]int8
title string
subtitle string
}
// Generate creates a Board to represent the given data by applying the drunken
// bishop algorithm.
func Generate(data []byte, title string) Board {
return GenerateSubtitled(data, title, "")
}
func GenerateSubtitled(data []byte, title, subtitle string) Board {
board := Board{title: title, subtitle: subtitle}
var x, y int
x = XDim / 2
y = YDim / 2
board.tiles[y][x] = start
for _, b := range data {
for s := uint(0); s < 8; s += 2 {
d := (b >> s) & 3
switch d {
case 0, 1:
// Up
if y > 0 {
y--
}
case 2, 3:
// Down
if y < YDim-1 {
y++
}
}
switch d {
case 0, 2:
// Left
if x > 0 {
x--
}
case 1, 3:
// Right
if x < XDim-1 {
x++
}
}
if board.tiles[y][x] >= 0 {
board.tiles[y][x]++
}
}
}
if board.tiles[YDim/2][XDim/2] == 0 {
board.tiles[YDim/2][XDim/2] = start
}
board.tiles[y][x] = end
return board
}
// Returns the string representation of the Board, using the OpenSSH ASCII art
// character set.
func (board Board) String() string {
var chars = []string{
" ", ".", "o", "+", "=",
"*", "B", "O", "X", "@",
"%", "&", "#", "/", "^",
}
var buf bytes.Buffer
if len(board.title) > 15 {
board.title = board.title[:15]
}
writeTitle(&buf, board.title)
for _, row := range board.tiles {
buf.WriteString("|")
for _, c := range row {
var s string
if c == start {
s = "S"
} else if c == end {
s = "E"
} else if int(c) < len(chars) {
s = chars[c]
} else {
s = chars[len(chars)-1]
}
buf.WriteString(s)
}
buf.WriteString("|\n")
}
writeTitle(&buf, board.subtitle)
return buf.String()
}
func writeTitle(buf *bytes.Buffer, title string) {
if title != "" {
extraChars := len(title) + 2 - XDim
if extraChars > 0 {
title = title[:XDim-extraChars]
}
title = "[" + title + "]"
}
leftLen := (XDim - len(title)) / 2
rightLen := XDim - len(title) - leftLen
buf.WriteString("+")
for i := 0; i < leftLen; i++ {
buf.WriteString("-")
}
buf.WriteString(title)
for i := 0; i < rightLen; i++ {
buf.WriteString("-")
}
buf.WriteString("+\n")
}
|