1

标题说什么。我有一个骰子程序,它打印一个骰子 IE

 ------
|      |
|      |
|     1|
 ------

我希望能够打印多个骰子,所以它看起来像这样:

 ------     ------
|      |   |      |
|      |   |      |
|     1|   |     3|
 ------     ------

我试过fmt.Print了,但仍然将它们打印在彼此下方。我也在考虑创建一个函数,打印每个对象的顶行,但我不知道如何做到这一点。有任何想法吗?

4

2 回答 2

2

这负责打印。这些数字在 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()
    }
}
于 2016-03-25T14:19:35.023 回答
1
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

于 2016-03-25T14:11:14.747 回答