Skip to content

Instantly share code, notes, and snippets.

@sertdfyguhi
Created October 12, 2021 09:11
Show Gist options
  • Save sertdfyguhi/3e8aeec31bed54ea6ca899ae000408e9 to your computer and use it in GitHub Desktop.
Save sertdfyguhi/3e8aeec31bed54ea6ca899ae000408e9 to your computer and use it in GitHub Desktop.
Tic tac toe in go
package main
import (
"bufio"
"fmt"
"log"
"os"
)
const boardTemplate = `
| |
%s | %s | %s
| |
---+---+---
| |
%s | %s | %s
| |
---+---+---
| |
%s | %s | %s
| |
`
func main() {
reader := bufio.NewReader(os.Stdin)
turn := 1
board := [3][3]int{
{0, 0, 0},
{0, 0, 0},
{0, 0, 0},
}
for contains(board[0], 0) || contains(board[1], 0) || contains(board[2], 0) {
board, turn = prompt(board, turn, *reader)
}
printBoard(board)
tie()
}
func contains(s [3]int, e int) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func prompt(board [3][3]int, turn int, reader bufio.Reader) ([3][3]int, int) {
printBoard(board)
fmt.Printf("player %d's turn: ", turn)
r, _, err := reader.ReadRune()
if err != nil {
log.Fatal(err)
}
space := int(r-'0') - 1
if space > 3*3-1 || space < 0 {
fmt.Println("That is not a valid space.")
return board, turn
}
pos := [2]int{space / 3, space % 3}
if board[pos[0]][pos[1]] != 0 {
fmt.Println("That space is already taken.")
return board, turn
}
board[pos[0]][pos[1]] = turn
wins := checkWin(board, turn)
if wins {
printBoard(board)
win(turn)
}
if turn == 1 {
turn = 2
} else {
turn = 1
}
return board, turn
}
func printBoard(board [3][3]int) {
mapping := []string{" ", "X", "O"}
fmt.Printf(
boardTemplate[1:],
mapping[board[0][0]],
mapping[board[0][1]],
mapping[board[0][2]],
mapping[board[1][0]],
mapping[board[1][1]],
mapping[board[1][2]],
mapping[board[2][0]],
mapping[board[2][1]],
mapping[board[2][2]],
)
}
func checkWin(board [3][3]int, turn int) bool {
// horizontal
for i := 0; i < len(board); i++ {
if board[i] == [3]int{turn, turn, turn} {
return true
}
}
// vertically
vertical := [3][3]int{
{board[0][0], board[1][0], board[2][0]},
{board[0][1], board[1][1], board[2][1]},
{board[0][2], board[1][2], board[2][2]},
}
for i := 0; i < len(vertical); i++ {
if vertical[i] == [3]int{turn, turn, turn} {
return true
}
}
// diagonally
diagonal := [2][3]int{
{board[0][0], board[1][1], board[2][2]},
{board[0][2], board[1][1], board[2][0]},
}
for i := 0; i < len(diagonal); i++ {
if diagonal[i] == [3]int{turn, turn, turn} {
return true
}
}
return false
}
func win(turn int) {
fmt.Printf("player %d wins!\n", turn)
os.Exit(0)
}
func tie() {
fmt.Println("tie!")
os.Exit(0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment