Skip to content

Instantly share code, notes, and snippets.

@aarti
Created September 19, 2016 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarti/0a9c131cc8dbb47db858a25b1aba44e8 to your computer and use it in GitHub Desktop.
Save aarti/0a9c131cc8dbb47db858a25b1aba44e8 to your computer and use it in GitHub Desktop.
connect 4 in Go
package main
import (
"fmt"
"math/rand"
"os"
"regexp"
"strconv"
"strings"
)
const (
X = "X"
Y = "Y"
)
var Xwin = regexp.MustCompile(`XXXX`)
var Ywin = regexp.MustCompile(`YYYY`)
type C4 struct {
board [6][7]string //The most commonly used Connect Four board size is 7 columns × 6 rows
}
func (c4 *C4) pp() { // pretty print board
for _, r := range c4.board {
for _, c := range r {
fmt.Print(c)
}
fmt.Println()
}
}
func (c4 *C4) play(player string) {
x, y := rand.Intn(6), rand.Intn(7)
for c4.board[x][y] != "X" && c4.board[x][y] != "Y" {
x, y = rand.Intn(6), rand.Intn(7)
c4.board[x][y] = player
}
}
func (c4 *C4) horizontalWin() bool {
for i, r := range c4.board {
rowState := strings.Join(r[0:6], "")
if Xwin.MatchString(rowState) {
fmt.Println("X Won at row:", i+1)
return true
}
if Ywin.MatchString(rowState) {
fmt.Println("Y Won at row:", i+1)
return true
}
}
return false
}
func main() {
c4 := new(C4)
seedVal := 23
if len(os.Args) > 1 {
seedVal, _ = strconv.Atoi(os.Args[1])
}
rand.Seed(int64(seedVal)) // pass seed as first arg
fmt.Println("Initialize Board")
for i := 0; i < 6; i++ {
for j := 0; j < 7; j++ {
c4.board[i][j] = "-"
}
}
c4.pp()
moves := 0
for !c4.horizontalWin() {
moves += 1
c4.play("Y")
c4.play("X")
if moves == 10 { // -- how does the board look after 10 moves
fmt.Println("Moves:", moves)
c4.pp()
}
}
fmt.Println("Won after Moves:", moves)
c4.pp()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment