牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

Golangのコマンドラインツールパッケージ urfave/cli を使って御神籤を作ってみるメモ

(glang1.6)

Install

$ go get github.com/urfave/cli

code

package main

import (
    "fmt"
    "math/rand"
    "os"
    "time"

    "github.com/urfave/cli"
)

func suffle(arr []string) {
    rand.Seed(time.Now().UnixNano())
    n := len(arr)
    for i := n - 1; i > 0; i-- {
        j := rand.Intn(i + 1)
        arr[i], arr[j] = arr[j], arr[i]
    }
}

func main() {
    app := cli.NewApp()
    app.Name = "omikuji"
    app.Usage = "Get today's fortune!"
    app.Version = "0.1"

    app.Flags = []cli.Flag{
        cli.StringFlag{
            Name:  "level",
            Value: "normal",
            Usage: "Fortune level, it is hard, easy and normal",
        },
    }

    app.Action = func(c *cli.Context) error {
        fortunes := []string{
            "Dai-kichi",
            "Kichi",
            "Chu-kichi",
            "Shou-kichi",
            "Sue-kichi",
            "Kyou",
            "Shou-kyou",
            "Dai-kyou",
        }

        if c.String("level") == "hard" {
            fortunes = []string{
                "Dai-kichi",
                "Dai-kyou",
            }
        } else if c.String("level") == "easy" {
            fortunes = []string{
                "Dai-kichi",
                "Kichi",
                "Chu-kichi",
                "Shou-kichi",
                "Sue-kichi",
            }
        }

        suffle(fortunes)
        fmt.Println(fortunes[0])

        return nil
    }

    app.Run(os.Args)
}

Build

$ go build omikuji.go

Run

$ ./omikuji
Sue-kichi
$ ./omikuji --level=easy
Kichi
$ ./omikuji --level=hard
Dai-kyou
$ ./omikuji --version
omikuji version 0.1
$ ./omikuji --help
NAME:
   omikuji - Get today's fortune!

USAGE:
   omikuji [global options] command [command options] [arguments...]

VERSION:
   0.1

COMMANDS:
GLOBAL OPTIONS:
   --level value  Fortune level, it is hard, easy and normal (default: "normal")
   --help, -h     show help
   --version, -v  print the version

参考