-
Notifications
You must be signed in to change notification settings - Fork 0
/
sketch.js
118 lines (102 loc) · 2.15 KB
/
sketch.js
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
let board = [
['', '', ''],
['', '', ''],
['', '', '']
];
let w;
let h;
let ai = 'X';
let human = 'O';
let currentPlayer = human;
function setup() {
createCanvas(400, 400);
w = width / 3;
h = height / 3;
//bestMove();
}
function equals3(a, b, c) {
return a == b && b == c && a != '';
}
function checkWinner() {
let winner = null;
// horizontal
for (let i = 0; i < 3; i++) {
if (equals3(board[i][0], board[i][1], board[i][2])) {
winner = board[i][0];
}
}
// Vertical
for (let i = 0; i < 3; i++) {
if (equals3(board[0][i], board[1][i], board[2][i])) {
winner = board[0][i];
}
}
// Diagonal
if (equals3(board[0][0], board[1][1], board[2][2])) {
winner = board[0][0];
}
if (equals3(board[2][0], board[1][1], board[0][2])) {
winner = board[2][0];
}
let openSpots = 0;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (board[i][j] == '') {
openSpots++;
}
}
}
if (winner == null && openSpots == 0) {
return 'tie';
} else {
return winner;
}
}
function mousePressed() {
if (currentPlayer == human) {
// Human make turn
let i = floor(mouseX / w);
let j = floor(mouseY / h);
// If valid turn
if (board[i][j] == '') {
board[i][j] = human;
currentPlayer = ai;
bestMove();
}
}
}
function draw() {
background(255);
strokeWeight(4);
line(w, 0, w, height);
line(w * 2, 0, w * 2, height);
line(0, h, width, h);
line(0, h * 2, width, h * 2);
for (let j = 0; j < 3; j++) {
for (let i = 0; i < 3; i++) {
let x = w * i + w / 2;
let y = h * j + h / 2;
let spot = board[i][j];
textSize(32);
let r = w / 4;
if (spot == human) {
noFill();
ellipse(x, y, r * 2);
} else if (spot == ai) {
line(x - r, y - r, x + r, y + r);
line(x + r, y - r, x - r, y + r);
}
}
}
let result = checkWinner();
if (result != null) {
noLoop();
let resultP = createP('');
resultP.style('font-size', '32pt');
if (result == 'tie') {
resultP.html('Tie!');
} else {
resultP.html(`${result} wins!`);
}
}
}