Skip to content

Instantly share code, notes, and snippets.

@jasonrdsouza
Created May 8, 2014 01:32
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 jasonrdsouza/cbb3a26c85c3b24333b1 to your computer and use it in GitHub Desktop.
Save jasonrdsouza/cbb3a26c85c3b24333b1 to your computer and use it in GitHub Desktop.
NxN TicTacToe win tracker
/*
NxN Tic Tac Toe win tracker
Assumptions
- User inputted moves are legal
- player X and player O don't both enter the same row/col as their move
- player X doesn't enter the same row/col twice
*/
package main
import (
"fmt"
"flag"
"errors"
)
type Board struct {
size int
rows []int
cols []int
diagz []int
}
func NewPlayerBoard(size int) (*Board) {
// each array element corresponds to the amount of X's or O's in that row, column, or diagonal
b := Board{size: size, rows: make([]int, size), cols: make([]int, size), diagz: make([]int, 2)}
return &b
}
// DoMove applies the requested move to the board, and returns true if the player has won
// input row and col are 0 indexed
// Illegal moves result in an error
func (b *Board) DoMove(row, col int) (bool, error) {
if row >= b.size || col >= b.size {
return false, errors.New("Invalid Move")
}
// handle row and column winners
if b.rows[row]++; b.rows[row] == b.size {
return true, nil
}
if b.cols[col]++; b.cols[col] == b.size {
return true, nil
}
// handle diagonal winners
if row == col {
b.diagz[0]++
}
if (row + col) == b.size - 1 {
b.diagz[1]++
}
if b.diagz[0] == b.size || b.diagz[1] == b.size {
return true, nil
}
return false, nil
}
func getAndPerformMove(b *Board) (bool, error) {
var row int
var col int
_, err := fmt.Scanln(&row, &col)
if err != nil {
return false, err
}
return b.DoMove(row, col)
}
func main() {
var board_size int
flag.IntVar(&board_size, "size", 3, "Size of the game board")
flag.Parse()
fmt.Println("Board size is:", board_size)
fmt.Println("Moves are 0 indexed")
fmt.Println("Please enter moves as: '0 3', where 0 is the row, and 3 is the column")
playerX_board := NewPlayerBoard(board_size)
playerO_board := NewPlayerBoard(board_size)
turn_count := 0
for {
if turn_count++; turn_count % 2 == 0 { // O's turn
fmt.Println("O's Turn:")
winner, err := getAndPerformMove(playerO_board)
if err != nil {
fmt.Println("Error:", err)
return
} else if winner {
fmt.Println("O Won!")
return
}
} else { // X's turn
fmt.Println("X's Turn:")
winner, err := getAndPerformMove(playerX_board)
if err != nil {
fmt.Println("Error:", err)
return
} else if winner {
fmt.Println("X Won!")
return
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment