Last active
January 3, 2023 13:07
-
-
Save QuakePhil/a95bd49008cab17b0b91037ccac4a4d2 to your computer and use it in GitHub Desktop.
Spi-Ral-Toe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "os" | |
var input [3]byte // 2nd index for enter key, 3rd for windoze | |
var spiral = []byte{1, 2, 3, 8, 9, 4, 7, 6, 5} | |
var unspiral = []byte{1, 2, 3, 6, 9, 8, 7, 4, 5} | |
var play func(byte, []rune) | |
func main() { | |
play = func(move byte, board []rune) { | |
update := func(next byte, board []rune, r rune) (done bool) { | |
check := func(m []int) (winner bool) { | |
for i := 0; i < 16; i += 2 { | |
s := m[i] | |
w := m[i+1] | |
o := board[s] | |
if o == board[w+s] && o == board[s+(w*2)] { | |
winner = o > 0 | |
} | |
} | |
return | |
} | |
if board[next-1] > '9' { | |
return false | |
} | |
board[next-1] = r | |
println(string(r), "played", next) | |
println(string(board)[:3]) | |
println(string(board)[3:6]) | |
println(string(board)[6:]) | |
// re: https://stackoverflow.com/questions/2245801/code-golf-tic-tac-toe/2565507 | |
if check([]int{0, 1, 3, 1, 6, 1, 0, 3, 1, 3, 2, 3, 0, 4, 2, 2}) { | |
println("X won") | |
return true | |
} | |
for _, r = range board { | |
if r <= '9' { | |
return false | |
} | |
} | |
println("tie") | |
return true | |
} | |
// credit to Martin Gardner: https://codegolf.stackexchange.com/questions/152064/play-tic-tac-toe-and-never-lose | |
if update(unspiral[move+move%2*2-2], board, 'X') { | |
return | |
} | |
os.Stdin.Read(input[:]) | |
if input[0] > 48 && input[0] < 58 { | |
update(input[0]-48, board, 'O') | |
play(spiral[input[0]-49], board) | |
} | |
} | |
println("X always goes in the middle") | |
play(10, []rune{'1', '2', '3', '4', '5', '6', '7', '8', '9'}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment