xxxxxxxxxx
115
let w;
let h;
let board = [
['','',''],
['','',''],
['','','']
];
let player1 = 'X';
let player2 = 'O';
let currentPlayer;
function setup() {
createCanvas(400,400);
background(255);
w = width/3;
h = height/3;
let toss = random(1);
if(toss == 0){
currentPlayer = player1;
}else{
currentPlayer = player2;
}
}
function playerChanger(currentPlayer){
if(currentPlayer == player1){
return player2;
}else if(currentPlayer == player2){
return player1;
}
}
function equals3(a, b, c){
return a==b && b==c && a!='';
}
function Winner(){
//Rows check
//Columns check
for(let i=0; i<3; i++){
if(equals3(board[i][0],board[i][1],board[i][2])) {
print("The winner is ",board[i][0]);
return true;
}
else if(equals3(board[0][i],board[1][i],board[2][i])){
print("The winner is ",board[0][i]);
return true;
}
}
//Diagonal check
if(equals3(board[0][0],board[1][1],board[2][2])){
print("The winner is ",board[0][0]);
return true;
}else if(equals3(board[2][0],board[1][1],board[0][2])){
print("The winner is ",board[2][0]);
return true;
}
//checks for free space
for(let i=0; i<3; i++){
for(let j=0; j<3; j++){
if(board[j][i] == ''){
return false;
}
}
}
//Else the game tied
print("The game is Tied!!")
return true;
}
function mousePressed(){
let i = floor(mouseX/w);
let j = floor(mouseY/h);
if(board[i][j] ==''){
board[i][j] = currentPlayer;
currentPlayer = playerChanger(currentPlayer);
}
}
function draw() {
strokeWeight(3);
fill(0);
line(w*1,0,w*1,height);
line(w*2,0,w*2,height);
line(0,h*1,width,h*1);
line(0,h*2,width,h*2);
let offset = w/4;
for(let i=0; i<3; i++){
for(let j=0; j<3; j++){
let x = w*j;
let y = h*i;
if(board[j][i] == player1){
line(x+offset, y+offset, x+w-offset, y+h-offset);
line(x+offset, y+h-offset, x+w-offset, y+offset);
}else if(board[j][i] == player2){
ellipseMode(CORNER);
noFill();
ellipse(x+offset,y+offset,w/2);
}
}
}
if(Winner()){
noLoop();
}
}