/
game.go
105 lines (86 loc) · 2.04 KB
/
game.go
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
// Copyright (c) 2016 SEkiSoft
// See License.txt
package model
import (
"encoding/json"
"io"
"net/http"
"strconv"
)
const (
MAX_NUMLINES = 19
MIN_NUMLINES = 5
WHITE = 1
BLACK = 2
)
type Game struct {
ID string `json:"id"`
IDBlack string `json:"id_black"`
IDWhite string `json:"id_white"`
Board string `json:"board"`
NumLines uint `json:"numlines"`
Turn uint `json:"turn"`
CreateAt int64 `json:"create_at"`
UpdateAt int64 `json:"update_at"`
DeleteAt int64 `json:"delete_at"`
Finished bool `json:"finished"`
}
func (g *Game) ToJson() string {
json, err := json.Marshal(g)
if err != nil {
return ""
}
return string(json)
}
func GameFromJson(data io.Reader) *Game {
decoder := json.NewDecoder(data)
var g Game
err := decoder.Decode(&g)
if err == nil {
return &g
}
return nil
}
func GamesToJson(g []*Game) string {
json, err := json.Marshal(g)
if err == nil {
return string(json)
}
return "[]"
}
func (g *Game) IsValid() *AppError {
if g.NumLines < MIN_NUMLINES || g.NumLines > MAX_NUMLINES {
return NewAppError("Game.IsValid", "Too many/few lines", http.StatusUnprocessableEntity)
} else if len(g.Board) != int(g.NumLines*g.NumLines) {
return NewAppError("Game.IsValid", "Board does not match line number", http.StatusUnprocessableEntity)
}
return nil
}
func (g *Game) PreSave() {
if g.ID == "" {
g.ID = NewID()
g.IDBlack = NewID()
g.IDWhite = NewID()
}
g.CreateAt = GetMillis()
g.UpdateAt = g.CreateAt
g.Finished = false
}
func (g *Game) PreUpdate() {
g.UpdateAt = GetMillis()
}
func (g *Game) GetStats() *GameStats {
var gs GameStats
// TODO GetGameStats
return &gs
}
func (g *Game) HasPlayer(playerID string) bool {
return g.IDBlack == playerID || g.IDWhite == playerID
}
func (g *Game) GetBoardPiece(x, y uint) (int, *AppError) {
if x < g.NumLines && y < g.NumLines {
piece, _ := strconv.ParseInt(string(g.Board[y*g.NumLines+x]), 10, 0)
return int(piece), nil
}
return -1, NewAppError("Game.GetBoardPiece", "row/col out of range", http.StatusUnprocessableEntity)
}