World Cup

四年一度的世界杯最近正在俄罗斯如火如荼的进行,昨天看了西班牙🇪🇸对葡萄牙🇵🇹的比赛,C罗真的是太帅了,帽子戏法,不过作为一个伪球迷-真程序员,准备写一点和世界杯有关的东西,想想用机器学习预测比赛结果好像并没有什么卵用,于是就写一个最简单的搬砖程序来提醒自己比赛时间吧。最终效果如下所示,典型的 MVC

1
2
3
4
5
6
7
8
9
10
11
12
13
14

Costa Rica 0 - 0 Serbia
------------------------------------------------------------------------
⚽ Will be played 4 hours from now


Germany 0 - 0 Mexico
------------------------------------------------------------------------
⚽ Will be played 7 hours from now


Brazil 0 - 0 Switzerland
------------------------------------------------------------------------
⚽ Will be played 10 hours from now

Model

比赛相关的数据可以从 http://worldcup.sfg.io/ 获取,我们使用结构体定义数据模型,注意结构体中的数据字段必须为大写,否则无法正确 Unmarshal,如果想要使结构体中的字段与 json 中的字段不同,可以额外增加 tag 来说明。

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
type match struct {
Time string `json:"time,omitempty"`
DateTime string `json:"datetime,omitempty"`
HomeTeam team `json:"home_team,ommitempty"`
AwayTeam team `json:"away_team,omitempty"`
Winner string `json:"winner,omitempty"`
}

type team struct {
Country string `json:"country,omitempty"`
Code string `json:"code,omitempty"`
Goals int `json:"goals,omitempty"`
}

func fetch(endpoint) ([]match, error) {
url := fmt.Sprintf("http://worldcup.sfg.io/%s", endpoint)
res, err := http.Get(url)
if err != nil {
return nil, err
}
defer res.Body.Close()
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var matches []match
err = json.Unmarshal(b, &matches)
if err != nil {
return nil, err
}
return matches, nil
}

View

因为我们的 layout 相对比较复杂,所以 View 部分代码也最多,但难度不大,就是繁琐,主要注意几点,彩色字体输出,不同情况下进度条的展示效果和各个字段所在的位置。

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
type status int

const (
PAST status = iota
NOW
FUTURE
)

const ScreenWidth = 72

const (
START = "\x1b[32m"
END = "\x1b[0m"
)

func colorize(s string) string {
return START + s + END
}

func multiply(c rune, n int) string {
var cs []rune
for i := 0; i < n; i++ {
cs = append(cs, c)
}
return string(cs)
}

func prettify(m match) string {

t, _ := time.Parse(time.RFC3339, m.DateTime)
diff := int(time.Now().Sub(t).Seconds())

var status status
switch {
case diff > 60*90:
status = PAST
case diff < 0:
status = FUTURE
default:
status = NOW
}

percentage := 0
matchStatus := ""
on := false

switch status {
case PAST:
percentage = 100
var result string
if m.Winner == "Draw" {
result = "Draw"
} else {
result = fmt.Sprintf("%s won", m.Winner)
}
matchStatus = fmt.Sprintf("Played %s. %s", humanize.Time(t), result)
on = true
case NOW:
percentage = int(diff / 60 / 90 * 100)
matchStatus = fmt.Sprintf("Being played now: %s minutes gone", humanize.Time(t))
on = true
case FUTURE:
percentage = 0
matchStatus = fmt.Sprintf("Will be played %s", humanize.Time(t))
}

home := m.HomeTeam
away := m.AwayTeam

s, e := "", ""
if on {
s = start
e = end
}

return fmt.Sprintf(" %s%-32s %d - %d %32s%s\n %s\n \u26BD %s\n",
s,home.Country,home.Goals,away.Goals,away.Country,e,
progressBar(percentage),
matchStatus,
)
}

func progressBar(percentage int) string {
var bar string

switch percentage {
case 0:
bar = multiply('-', ScreenWidth)
case 100:
bar = colorize(multiply('-', ScreenWidth))
default:
completed := int(float64(ScreenWidth) / 100.0 * float64(percentage))
bar = colorize(multiply('-', completed-1)+"o") + multiply('-', ScreenWidth-completed)
}

return bar
}

Controller

Controller 部分就是将 Model 部分和 view 部分代码整合在一起。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func main() {
matches, err := fetch("matches/today")
if err != nil {
log.Fatal(err)
}
for i, match := range matches {
if i == 0 {
fmt.Println()
}
fmt.Println(prettify(match))
if i != len(matches)-1 {
fmt.Println()
}
}
}
Pieces of Valuable Programming Knowledges