tictactoe.gno
1.59 Kb · 80 lines
1package tictactoe
2
3import "strconv"
4
5var (
6 board [9]string
7 turn = "X"
8 winner string
9 moves int
10)
11
12func init() {
13 for i := 0; i < 9; i++ {
14 board[i] = "."
15 }
16}
17
18// Mark places the current player's token at pos (0=top-left ... 8=bottom-right, row-major).
19func Mark(pos int) string {
20 if winner != "" {
21 return "game over: " + winner
22 }
23 if pos < 0 || pos > 8 {
24 return "invalid position: use 0-8"
25 }
26 if board[pos] != "." {
27 return "cell already taken"
28 }
29 board[pos] = turn
30 moves++
31 if checkWin() {
32 winner = turn
33 return turn + " wins!"
34 }
35 if moves == 9 {
36 winner = "draw"
37 return "draw!"
38 }
39 if turn == "X" {
40 turn = "O"
41 } else {
42 turn = "X"
43 }
44 return "ok"
45}
46
47func checkWin() bool {
48 lines := [8][3]int{
49 {0, 1, 2}, {3, 4, 5}, {6, 7, 8},
50 {0, 3, 6}, {1, 4, 7}, {2, 5, 8},
51 {0, 4, 8}, {2, 4, 6},
52 }
53 for _, l := range lines {
54 if board[l[0]] != "." && board[l[0]] == board[l[1]] && board[l[1]] == board[l[2]] {
55 return true
56 }
57 }
58 return false
59}
60
61func Render(_ string) string {
62 out := "# Tic-Tac-Toe\n\n"
63 out += "```\n"
64 out += " " + board[0] + " | " + board[1] + " | " + board[2] + "\n"
65 out += "---+---+---\n"
66 out += " " + board[3] + " | " + board[4] + " | " + board[5] + "\n"
67 out += "---+---+---\n"
68 out += " " + board[6] + " | " + board[7] + " | " + board[8] + "\n"
69 out += "```\n\n"
70 if winner == "draw" {
71 out += "**Draw!**\n"
72 } else if winner != "" {
73 out += "**" + winner + " wins!**\n"
74 } else {
75 out += "Next turn: **" + turn + "**\n\n"
76 out += "Positions: 0=top-left, 4=center, 8=bottom-right (row-major)\n"
77 }
78 out += "\nMoves played: " + strconv.Itoa(moves) + "\n"
79 return out
80}