-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGameBoard.go
124 lines (116 loc) · 2.54 KB
/
GameBoard.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
package main
import (
"strings"
)
type GameBoard struct {
tokenOne byte
tokenTwo byte
game [6][7]byte
}
func initialize(g *GameBoard){
g.game = [6][7]byte{{' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' '}}
}
func toString(g *GameBoard) string {
var sb strings.Builder
var row, column int
sb.WriteString("+---------------+\n")
for row = 0; row < 6; row++ {
sb.WriteString("| ")
for column = 0; column < 7; column++ {
sb.WriteString(string(g.game[row][column]))
sb.WriteString(" ")
}
sb.WriteString("|\n")
}
sb.WriteString("+---------------+\n")
sb.WriteString(" 0 1 2 3 4 5 6")
return sb.String()
}
//Inserts token into specified column.
//Returns true on success and false otherwise
func insertToken (g *GameBoard, token byte, column int) bool {
var success bool = false
var row int = len(g.game) - 1
for row >= 0 {
if g.game[row][column] == ' ' {
success = true
g.game[row][column] = token
break
}
row--
}
return success
}
//Returns true if a winstate is found (four in a row)
func checkWinner (g *GameBoard, token byte) bool{
var row int = len(g.game) - 1
var goalStr string = string([]byte{token, token, token, token})
//check horizontal goal
for row >= 0 {
str := string(g.game[row][:])
if strings.Contains(str, goalStr){
return true
}
row--
}
var column int = len(g.game[0]) - 1
var sb strings.Builder
//check vertical goal
for column >= 0 {
row = len(g.game) - 1
for row >= 0 {
sb.WriteString(string(g.game[row][column]))
row--
}
str := sb.String()
sb.Reset()
if strings.Contains(str, goalStr){
return true
}
column--
}
column = 0
//check horizontal goal (\)
for column < len(g.game[0]) - 3 {
row = 0;
for row < len(g.game) - 3{
var i int = 0
for row + i < len(g.game) && column + i < len(g.game[0]){
sb.WriteString(string(g.game[row + i][column + i]))
i++
}
row++
str := sb.String()
sb.Reset()
if strings.Contains(str, goalStr){
return true
}
}
column++
}
column = len(g.game[0]) - 1
//check horizontal goal (/)
for column > 2 {
row = 0;
for row < len(g.game) - 3 {
var i int = 0
for row + i < len(g.game) && column - i >= 0{
sb.WriteString(string(g.game[row + i][column - i]))
i++
}
row++
str := sb.String()
sb.Reset()
if strings.Contains(str, goalStr){
return true
}
}
column--
}
return false
}