xxxxxxxxxx
132
let cells = [];
let rowCount = 5;
let players = ['X','O'];
let currentPlayer = 0;
let GameFinsihed = false;
let winnerComb = false;
let combinations = [];
function setup() {
createCanvas(100 *rowCount, 100 *rowCount);
// create cells
let w = 100;
for (let row = 0; row <rowCount; row++){
for (let col = 0; col <rowCount; col++){
let x = row*w;
let y =col*w;
cells.push(new Cell(x,y,w));
}
}
buildWinnderCombinations();
}
function draw() {
background(0);
for (let cell of cells){
cell.draw();
}
frameRate(10);
if (!GameFinsihed){
play();
}
else if(winnerComb){
drawWinner(winnerComb);
}
}
function play(){
let symbole = players[currentPlayer];
let cell = getRandomEmptyCell();
if (cell){
cell.val = symbole;
winnerComb = getWinner();
if (winnerComb){
GameFinsihed= true;
console.log(winnerComb);
}else{
currentPlayer = (currentPlayer == 0)? 1 : 0;
}
}
}
function getRandomEmptyCell(){
let list = [];
for (let cell of cells){
if (cell.val =='') list.push(cell)
}
if (list.length > 0){
return random(list);
}else{
return false;
}
}
function buildWinnderCombinations(){
combinations=[];
for (let i=0; i<rowCount; i++){
let h = [] // horizontal combinations
let v = [] // vertical combinations
for (let j=0; j<rowCount; j++){
h.push(i+ j*rowCount);
v.push(i*rowCount + j)
}
combinations.push(h);
combinations.push(v);
}
// diagonals
let d = [];
for (let i=0; i<rowCount; i++){
for (let j=0; j<rowCount; j++){
if (i == j)
d.push(i*rowCount + j)
}
}
combinations.push(d);
d = [];
for (let i=0; i<rowCount; i++){
for (let j=0; j<rowCount; j++){
if (i+j == rowCount-1)
d.push(i*rowCount + j)
}
}
combinations.push(d);
}
function getWinner(){
for (let cmb of combinations){
let isWinner = true;
for (let i=0; i<cmb.length -1; i++){
let pos =cmb[i];
let nextPos= cmb[i+1]
// not empty and different from next
if (cells[pos].val == '' || cells[pos].val != cells[nextPos].val)
isWinner = false;
}
if (isWinner) return cmb;
}
return false;
}
function drawWinner(cmb){
let pos1 = cmb[0];
let pos2 = cmb[cmb.length -1];
let startX = cells[pos1].x + (cells[pos1].w/2) + (cells[pos1].w*0.1)
let startY = cells[pos1].y + (cells[pos1].w/2) + (cells[pos1].w*0.1)
let endX = cells[pos2].x + (cells[pos2].w/2) + (cells[pos1].w*0.1)
let endY = cells[pos2].y + (cells[pos2].w/2) + (cells[pos1].w*0.1)
push();
stroke(255,0,0);
strokeWeight(5);
line(startX,startY, endX, endY);
pop();
}