This repository was archived by the owner on Jan 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
104 lines (94 loc) · 1.95 KB
/
main.go
File metadata and controls
104 lines (94 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"fmt"
"github.com/nsf/termbox-go"
)
var winningconditions = [][]int{
[]int{0, 1, 2},
[]int{0, 3, 6},
[]int{0, 4, 8},
[]int{1, 4, 7},
[]int{2, 4, 6},
[]int{2, 5, 8},
[]int{3, 4, 6},
[]int{6, 7, 8},
}
// ok ok ill clean it up later
func main() {
err := termbox.Init()
if err != nil {
panic(err)
}
quit := make(chan struct{})
place := make(chan int)
playing := false
board := []string{"_", "_", "_", "_", "_", "_", "_", "_", "_"}
player := "X"
clear()
fmt.Println("TicTacGo - Press Space to start!")
go func() {
for {
ev := termbox.PollEvent()
switch ev.Type {
case termbox.EventKey:
switch ev.Key {
case termbox.KeyEsc:
close(quit)
return
case termbox.KeySpace:
if playing == false {
playing = true
clear()
displayboard(board)
}
}
if ch := ev.Ch; ch > 48 && ch < 58 {
place <- int(ch - 49)
}
}
}
}()
loop:
for {
select {
case <-quit:
break loop
case p := <-place:
if playing == true {
if player == "X" { player = "O" } else { player = "X" }
if state := play(board, p, player); state == "w" {
fmt.Printf("\n%s won! Press Space to restart.", player)
playing = false
board = []string{"_", "_", "_", "_", "_", "_", "_", "_", "_"}
}
}
}
}
termbox.Close()
fmt.Printf("\x1b[2J")
fmt.Println("Goodbye!")
}
func play(board []string, place int, player string) string {
board[place] = player
displayboard(board)
for i := 0; i < 8; i++ {
condition := winningconditions[i];
a := board[condition[0]];
b := board[condition[1]];
c := board[condition[2]];
if a == "_" || b == "_" || c == "_" { continue }
if a == b && b == c { return "w" }
}
return "p"
}
func displayboard(board []string) {
clear()
for i := 0; i < 9; i++ {
if i != 0 && i % 3 == 0 { fmt.Printf("\n") }
fmt.Printf("%s ", board[i])
}
}
func clear() {
fmt.Printf("\x1b[2J")
termbox.SetCursor(0, 0)
}