I am a beginner and I want to make a Tic Tac Toe game.
I want to make a function to find the winner of the game and return "x" if x win, "o" if o win, "draw" if no one win and "error" if there are two winner.
function winner(x){
//x is an array that includes 3 child arrays, every child represents a row of tic tac toe matrix
// example x =[["x","o","x"],["o","x","o"],["o","o","x"]]
// It should return "x" because "x" player is the winner
}
I tried many ways but I still can't do it. Can you help me?
I am assuming that the values can also be "" apart from "x" or "o" (in case of early end to the game). Also, in case where there is no winner and the game still has some empty values, then I think it is best to return "incomplete".
function winner(x) {
console.log(`${x[0].join(' ')}\n${x[1].join(' ')}\n${x[2].join(' ')}`);
winners = new Set();
// columns check
for (let i = 0; i < 3; i++) {
if (x[0][i] !== "" && (new Set([x[0][i], x[1][i], x[2][i]])).size === 1) {
winners.add(x[0][i]);
}
}
// rows check
for (let i = 0; i < 3; i++) {
if (x[i][0] !== "" && (new Set(x[i])).size === 1) {
winners.add(x[i][0]);
}
}
// diagonals check
if (x[1][1] !== "" && ((new Set([x[0][0], x[1][1], x[2][2]])).size === 1 || (new Set([x[0][2], x[1][1], x[2][0]])).size === 1)) {
winners.add(x[1][1]);
}
if (winners.size === 2) {
return "error";
}
if (winners.size === 0) {
// completion check
if (x.every(y => y.every(z => z))){
return "draw";
}
return "incomplete";
}
return winners.values().next().value;
}
Explanation
You see a lot of Set objects created and manipulated in the code. Set in Javascript is an easy way to ensure that there are no duplicates. They are also used in the code to check if everything passed to it is the same.
Lastly, getting the value in the Set is done in the last line.