-
Notifications
You must be signed in to change notification settings - Fork 0
/
ghess.go
348 lines (325 loc) · 9.08 KB
/
ghess.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Package ghess is a Go Chess Engine.
//
// Fenimore Love 2016
// GPLv3
//
package ghess
import (
"bufio"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"time"
)
// Board is a chessboard type.
// TODO: Make Upper Case? M-c for upper case
type Board struct {
board [120]byte // piece position
// Game Variables
castle [4]byte // castle possibility KQkq or ----
empassant int // square vulnerable to empassant
Score string
toMove string // Next move is w or b
moves int // the count of moves
Check bool
Checkmate bool // start Capitalizing
Draw bool
// Game Positions
fen string // Game position
pgn string // Game history
headers string // Pgn format
History [8]int // For Draws, last six coordinates
}
// NewBoard returns pointer to new Board in the starting position.
func NewBoard() Board {
arr := [120]byte{}
b := make([]byte, 120)
// starting position
b = []byte(` RNBKQBNR PPPPPPPP ........ ........ ........ ........ pppppppp rnbkqbnr `)
copy(arr[:], b)
// pieceMap
// TODO: Put this somewhere it makes sense
return Board{
board: arr,
castle: [4]byte{'K', 'Q', 'k', 'q'},
toMove: "w",
Score: "*",
moves: 1,
}
}
// String() returns a string printable board.
// The board will rotate according to whose turn
// it is.
func (b *Board) String() string {
var printBoard string
if b.toMove == "w" {
printBoard = b.StringWhite()
} else {
printBoard = b.StringBlack()
}
return printBoard
}
// StringWhite returns a string printable board
// from white's perspective.
func (b *Board) StringWhite() string {
var nums [8]byte // somehow print these?
nums[0], nums[1], nums[2], nums[3], nums[4], nums[5], nums[6], nums[7] = '1', '2', '3', '4', '5', '6', '7', '8'
r := make(map[int]bool) // black squares
r[17], r[15], r[13], r[11], r[28], r[26], r[24], r[22], r[37], r[35], r[33], r[31], r[48], r[46], r[44], r[42], r[57], r[55], r[53], r[51], r[68], r[66], r[64], r[62], r[77], r[75], r[73], r[71], r[88], r[86], r[84], r[82] = false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false
game := b.board
p := UnicodeMap // slower but makes code more readable, and printing isn't slow anyway
var printBoard string
j := 7
for i := 89; i > 10; i-- {
if i%10 == 0 {
printBoard += string(nums[j]) + ": " + "\n"
j--
continue
} else if (i+1)%10 == 0 {
continue
}
if game[i] == '.' {
_, ok := r[i]
if ok { // white square
printBoard += "|" + " " + "|"
} else { // black square
printBoard += "|" + "\u2591" + "|"
}
} else {
printBoard += "|" + p[string(game[i])] + "|"
}
}
printBoard += string(nums[j]) + ": " + "\n"
printBoard += ":a::b::c::d::e::f::g::h:\n"
return printBoard
}
// StringBlack rotates for Black perspective.
func (b *Board) StringBlack() string {
var nums [8]byte // somehow print these?
nums[0], nums[1], nums[2], nums[3], nums[4], nums[5], nums[6], nums[7] = '1', '2', '3', '4', '5', '6', '7', '8'
r := make(map[int]bool) // black squares
r[17], r[15], r[13], r[11], r[28], r[26], r[24], r[22], r[37], r[35], r[33], r[31], r[48], r[46], r[44], r[42], r[57], r[55], r[53], r[51], r[68], r[66], r[64], r[62], r[77], r[75], r[73], r[71], r[88], r[86], r[84], r[82] = false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false
game := b.board
p := UnicodeMap
var printBoard string
j := 0
for i := 11; i < 90; i++ {
if i%10 == 0 {
printBoard += string(nums[j]) + ": " + "\n"
j++
continue
} else if (i+1)%10 == 0 {
continue
}
if game[i] == '.' {
_, ok := r[i]
if ok { // white square
printBoard += "|" + " " + "|"
} else { // black square
printBoard += "|" + "\u2591" + "|"
}
} else {
printBoard += "|" + p[string(game[i])] + "|"
}
}
printBoard += string(nums[j]) + ": " + "\n"
printBoard += ":h::g::f::e::d::c::b::a:\n"
return printBoard
}
// PgnString returns headers and pgn history.
func (b *Board) PgnString() string {
return b.headers + b.pgn
}
// Position returns string FEN position.
// It also sets the Board.fen attribute
// to the most currect position. (b.fen
// remains empty unil b.Position() is called)
func (b *Board) Position() string {
pos := ""
emp := "-"
zeroTicker := 0
for i := 88; i > 10; i-- {
if i%10 == 0 || (i+1)%10 == 0 {
continue
}
// Cycle backwards and tally empty squares
if b.board[i] == '.' {
zeroTicker++
} else if zeroTicker > 0 && b.board[i] != '.' {
pos += strconv.Itoa(zeroTicker)
pos += string(b.board[i])
zeroTicker = 0
} else {
pos += string(b.board[i])
}
if (i-1)%10 == 0 && i > 10 { // hit edge
if zeroTicker > 0 {
pos += strconv.Itoa(zeroTicker)
}
zeroTicker = 0
if i > 11 {
pos += "/"
}
}
}
if b.empassant != 0 {
if b.toMove == "w" {
emp = PieceMap[b.empassant+10]
} else {
emp = PieceMap[b.empassant-10]
}
}
b.fen = pos + " " + b.toMove + " " + string(b.castle[:4]) + " " + emp + " 0 " + strconv.Itoa(b.moves)
return b.fen
}
// Stats returns program data of current game
// in map[string]string.
// Todo, replace with exported struct attirbutes.
func (b *Board) Stats() map[string]string {
_ = b.Position()
m := make(map[string]string)
m["turn"] = b.toMove
m["move"] = strconv.Itoa(b.moves)
m["castling"] = string(b.castle[:])
m["position"] = b.fen
m["history"] = b.pgn
m["check"] = strconv.FormatBool(b.Check)
m["headers"] = b.headers
m["score"] = b.Score
m["checkmate"] = strconv.FormatBool(b.Checkmate)
//m["lastthree"] =
return m
}
// SetHeaders sets pgnHeaders for a pgn export.
func (b *Board) SetHeaders(w, bl string) {
w = strings.TrimRight(w, "\r\n")
bl = strings.TrimRight(bl, "\r\n")
y, m, d := time.Now().Date()
ye, mo, da := strconv.Itoa(y), strconv.Itoa(int(m)),
strconv.Itoa(d)
white := "[White \"" + w + "\"]"
black := "[Black \"" + bl + "\"]"
date := "[Date \"" + ye + "." + mo + "." + da + "\"]"
result := `[Result "*"]`
b.headers = white + "\n" + black + "\n" + date + "\n" + result + "\n"
}
// Play game in terminal
func main() {
board := NewBoard()
PlayGame(board)
}
// PlayGame takes user input and commands.
// See ui/clichess.go for more robust client.
func PlayGame(board Board) {
var turn string
welcome := `
********
go-chess
/~ |_ _ _ _
\_|||(/__\_\
`
reader := bufio.NewReader(os.Stdin)
fmt.Println(welcome)
fmt.Print(board.String())
Loop:
for {
if board.toMove == "w" {
turn = "White"
} else {
turn = "Black"
}
fmt.Print(turn, " to move: ")
input, _ := reader.ReadString('\n')
isCmd, _ := regexp.MatchString(`/`, input)
if isCmd {
input = strings.TrimRight(input, "\r\n")
switch {
case input == "/quit":
break Loop //os.Exit(1)
case input == "/new":
board = NewBoard()
fmt.Print(board.String())
case input == "/print":
fmt.Print(board.String())
default:
fmt.Println("Mysterious input")
}
continue
}
e := board.ParseMove(input)
if board.toMove == "w" {
turn = "White"
} else {
turn = "Black"
}
fmt.Println("\n-------------------")
// TODO use formats.
if e != nil {
fmt.Printf(" [Error: %v]\n", e)
}
fmt.Print(board.String())
if board.Checkmate {
fmt.Println("****CheckMate!****")
} else if board.Check {
fmt.Println("****Check!****")
}
}
fmt.Println("\nGood Game.")
}
// Coordinates prints the int values used
// for Board.Move()
func (b *Board) Coordinates() {
// TODO Rotate Board
game := b.board
var printBoard string
for i := 89; i > 10; i-- {
if i%10 == 0 {
printBoard += "\n"
continue
} else if (i+1)%10 == 0 {
printBoard += string(game[i]) + ": "
continue
}
printBoard += "|" + strconv.Itoa(i) + "|"
}
printBoard += "\n"
printBoard += " :a ::b ::c ::d ::e ::f ::g ::h :\n"
fmt.Println(printBoard)
}
// isUpper is a wrapper to check if byte in
// Board.board is upper case.
// If Uppercase, it is either white player
// [TODO] or it is empty square.
func (b Board) isUpper(x int) bool {
return b.board[x] <= 'Z' //[]byte{0x5a}[0]
}
func (b *Board) cycleHistory(o, d int) {
//fmt.Println(b.history)
b.History[7] = b.History[5]
b.History[6] = b.History[4]
b.History[5] = b.History[3]
b.History[4] = b.History[2]
b.History[3] = b.History[1]
b.History[2] = b.History[0]
b.History[1] = d
b.History[0] = o
// fmt.Println(b.History)
}
// CopyBoard takes in a Board pointer and returns
// a copy of it's state, this is for modifying and then
// keeping the originals state intact. One must be careful because
// the values of Board are []byte slices, and these are themselves
// pointers.
// FIXME: This isn't really useful anymore now that the slices are arrays.
func CopyBoard(b *Board) *Board {
c := *b // dereference the pointer
//boardCopy := make([]byte, 120) // []bytes are slices
//castleCopy := make([]byte, 4)
//copy(boardCopy, b.board)
//copy(castleCopy, b.castle)
//c.board = boardCopy
//c.castle = castleCopy
return &c
}