-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch2.js
110 lines (89 loc) · 1.74 KB
/
sketch2.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
//Global Variables
let board = [
['','',''],
['','',''],
['','','']
]
let w;
let h;
let player1 = 'O';
let player2 = 'X';
let currentPlayer = player1;
//Functions
//initialize
function setup() {
let cnv = createCanvas(400,400);
cnv.center();
w = width/3;
h = height/3;
}
//Tic-Tac-Toe board
function createBoard() {
background(220);
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);
}
//Human Turn
function mousePressed() {
let nextPlayer;
if(currentPlayer == player1) {
nextPlayer = player2;
}
else {
nextPlayer = player1;
}
let i = floor(mouseX / w);
let j = floor(mouseY / h);
// console.log(mouseX);
// console.log(mouseY);
// console.log(w);
// console.log(h);
// console.log(mouseX/w);
// console.log(mouseY/h);
//check valid move
if(board[i][j] == "") {
board[i][j] = currentPlayer;
currentPlayer = nextPlayer;
//console.log(currentPlayer);
//console.log(nextPlayer);
}
}
//Drawing
function draw() {
createBoard();
//drawing X and O
for(let i=0; i<3; i++) {
for(let j=0; j<3; j++ ) {
let x = w*i + w/2;
let y = h*j + h/2;
let spot = board[i][j];
textSize(32);
let r = w/4;
//drawing X
if(spot == player2)
{
line(x-r,y-r, x+r,y+r);
line(x+r,y-r, x-r,y+r);
}
else if(spot == player1)
{
noFill();
ellipse(x , y, r*2);
}
}
}
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 !`)
}
}