2 回答
TA贡献1860条经验 获得超8个赞
这负责打印。数字在 1 到 6(含)之间随机分配。作为命令行参数的骰子数。所以在我的例子中 ./roll 6 打印 6 个骰子,随机数最多为 6。
package main
import (
"fmt"
"math/rand"
"os"
"strconv"
"time"
)
func main() {
numDice := 1
if len(os.Args) > 1 {
i, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Println(err)
}
numDice = i
}
seed := rand.NewSource(time.Now().UnixNano())
randomNumber := rand.New(seed)
die := []string{
" ------ ",
"| | ",
"| | ",
"| | ",
" ------ ",
}
for i := 0; i < 5; i++ {
for j, n := 0, numDice; j < n; j++ {
if i == 3 {
fmt.Printf("| %d | ", randomNumber.Intn(5)+1)
} else {
fmt.Print(die[i])
}
}
fmt.Println()
}
}
TA贡献1785条经验 获得超8个赞
package main
import (
"bytes"
"fmt"
"strings"
)
func getDie(n int) []string {
return []string{
" ------",
"| |",
"| |",
fmt.Sprintf("|%6d|", n),
" ------",
}
}
func joinLines(between int, items ...[]string) []string {
if len(items) == 0 {
return nil
}
if len(items) == 1 {
return items[0]
}
lineCount := 0
maxSizes := make([]int, len(items))
for i, item := range items {
for j, line := range item {
if maxSizes[i] < len(line) {
maxSizes[i] = len(line)
}
if j+1 > lineCount {
lineCount = j + 1
}
}
}
lines := make([]string, lineCount)
for i := 0; i < lineCount; i++ {
var buff bytes.Buffer
for j, item := range items {
diff := 0
if j+1 < len(items) {
diff += maxSizes[j] + between
}
if i < len(item) {
line := item[i]
buff.WriteString(line)
diff -= len(line)
}
if diff > 0 {
buff.WriteString(strings.Repeat(" ", diff))
}
}
lines[i] = buff.String()
}
return lines
}
func main() {
a, b, c, d := getDie(2), getDie(3), []string{"", "", "="}, getDie(5)
all := joinLines(3, a, b, c, d)
for _, line := range all {
fmt.Println(line)
}
}
https://play.golang.org/p/NNrTUDdfyn
- 2 回答
- 0 关注
- 199 浏览
添加回答
举报