-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
225 lines (188 loc) · 4.32 KB
/
main.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
package main
import (
"bufio"
"fmt"
"net"
"strconv"
)
const xSymbol = "\x1b[34mX\x1b[0m"
const oSymbol = "\x1b[36mO\x1b[0m"
const noWinner = "none"
var winCombinations = [][]int{
{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, // verticals
{0, 3, 6}, {1, 4, 7}, {2, 5, 8}, // horizontals
{0, 4, 8}, {2, 4, 6}, // diagonals
}
type Player struct {
Index int
Connection net.Conn
Symbol string
Score int
}
type Game struct {
Board map[int]string
Players []Player
CurrentPlayer Player
Watchers []net.Conn
}
func (g *Game) String() string {
if !g.isFullPlaces() {
return "waiting for an oponent to join \n"
}
var (
board string
score string
)
for i := 0; i < 9; i += 3 {
board += fmt.Sprintf("%v | %v | %v\n", g.Board[i], g.Board[i+1], g.Board[i+2])
}
for _, p := range g.Players {
score += fmt.Sprintf("%v:%v ", p.Symbol, p.Score)
}
return fmt.Sprintf("%v \nscore: %v\n", board, score)
}
func (g *Game) isFullBoard() bool {
for _, v := range g.Board {
if v != xSymbol && v != oSymbol {
return false
}
}
return true
}
func (g *Game) isFullPlaces() bool {
return len(g.Players) == 2
}
func (g *Game) shouldResetBoard() bool {
return g.getWinnerSymbol() != noWinner || g.isFullBoard()
}
func (g *Game) canPlayTurn(p Player) bool {
if p.Connection == g.CurrentPlayer.Connection && g.isFullPlaces() {
return true
}
return false
}
func (g *Game) resetBoard() {
for i := range 9 {
g.Board[i] = fmt.Sprintf("%d", i)
}
}
func (g *Game) switchCurrentPlayer() {
if g.CurrentPlayer.Index == 0 {
g.CurrentPlayer = g.Players[1]
} else {
g.CurrentPlayer = g.Players[0]
}
}
func (g *Game) isFreePos(pos int) bool {
if g.Board[pos] == xSymbol || g.Board[pos] == oSymbol || pos > 8 || pos < 0 {
return false
}
return true
}
func (g *Game) playTurn(p Player, pos int) {
g.Board[pos] = p.Symbol
}
func (g *Game) getWinnerSymbol() string {
for _, c := range winCombinations {
if g.Board[c[0]] == g.Board[c[1]] && g.Board[c[1]] == g.Board[c[2]] {
return g.Board[c[0]]
}
}
return noWinner
}
func (g *Game) getPlayerWithSymbol(s string) *Player {
if g.Players[0].Symbol == s {
return &g.Players[0]
}
return &g.Players[1]
}
func (p *Player) incrementScore() {
p.Score += 1
}
func (g *Game) dispatchNextTurn() {
if !g.isFullPlaces() {
return
}
for _, p := range g.Players {
if p.Connection != g.CurrentPlayer.Connection {
p.Connection.Write([]byte("oponent's turn! \n"))
continue
}
p.Connection.Write([]byte("your turn: \n"))
}
}
func (g *Game) dispatchGame() {
for _, p := range g.Players {
p.Connection.Write([]byte(g.String()))
}
}
func handleGameConnection(g *Game, p Player) {
scanner := bufio.NewScanner(p.Connection)
defer handlePlayerQuit(g, p)
for {
if ok := scanner.Scan(); !ok {
break
}
pos, _ := strconv.Atoi(scanner.Text())
handlePlayerPosition(pos, g, p)
}
}
func handlePlayerQuit(g *Game, pl Player) {
for i, p := range g.Players {
if p.Connection == pl.Connection {
g.Players = append(g.Players[:i], g.Players[i+1:]...)
break
}
}
pl.Connection.Close()
}
func handlePlayerPosition(pos int, g *Game, p Player) {
if g.canPlayTurn(p) && g.isFreePos(pos) {
g.playTurn(p, pos)
g.switchCurrentPlayer()
}
if ws := g.getWinnerSymbol(); ws != noWinner {
winner := g.getPlayerWithSymbol(ws)
winner.incrementScore()
}
if g.shouldResetBoard() {
g.resetBoard()
}
g.dispatchGame()
g.dispatchNextTurn()
}
func rejectConnection(conn net.Conn) {
fmt.Printf("rejecting client connected from %v\n", conn.RemoteAddr().String())
conn.Write([]byte("Game is full, try again later!" + "\n"))
conn.Close()
}
func main() {
listener, _ := net.Listen("tcp", "localhost:8080")
fmt.Println("Listening on localhost:8080.")
var game = Game{
Board: make(map[int]string, 9),
}
game.resetBoard()
defer listener.Close()
for {
conn, _ := listener.Accept()
if game.isFullPlaces() {
rejectConnection(conn)
continue
}
fmt.Printf("client connected from %v\n", conn.RemoteAddr().String())
player := Player{
Index: len(game.Players),
Connection: conn,
Symbol: []string{xSymbol, oSymbol}[len(game.Players)],
Score: 0,
}
game.Players = append(game.Players, player)
game.CurrentPlayer = player
if game.isFullPlaces() {
game.dispatchGame()
game.dispatchNextTurn()
}
go handleGameConnection(&game, player)
}
}