-
Notifications
You must be signed in to change notification settings - Fork 0
/
play.go
80 lines (69 loc) · 1.29 KB
/
play.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
package main
import (
"bufio"
"fmt"
"github.com/jakecoffman/graph/adversarial/tictactoe"
"log"
"os"
"strconv"
"strings"
)
type Input struct {
reader *bufio.Reader
}
func NewInput() *Input {
return &Input{
reader: bufio.NewReader(os.Stdin),
}
}
func (i *Input) Read() string {
str, err := i.reader.ReadString('\n')
check(err)
return strings.Split(str, "\n")[0]
}
func main() {
log.SetFlags(0)
input := NewInput()
fmt.Println("Do you want to go first? (Y|n)")
str := input.Read()
player := tictactoe.CellO
if str == "" || strings.HasPrefix(strings.ToUpper(str), "Y") {
player = tictactoe.CellX
}
state := tictactoe.NewState()
turn := tictactoe.CellX
for !state.IsGameOver() {
if player == turn {
fmt.Println(state)
fmt.Println("Enter index to move: ")
str = input.Read()
i, err := strconv.Atoi(str)
check(err)
if i > 8 || i < 0 {
continue
}
if state.Index(i) != tictactoe.CellBlank {
continue
}
state.Play(i, turn)
} else {
move := state.BestMove(turn)
state.Play(move, turn)
}
turn = -turn
}
fmt.Println(state)
score := state.Evaluate(turn)
if score == 0 {
fmt.Println("TIE!")
} else if score < 0 {
fmt.Println("LOSE")
} else {
fmt.Println("WIN")
}
}
func check(err error) {
if err != nil {
log.Fatalln(err)
}
}