i created a Tic Tac Toe game on javascript and HTML. in the game the user can choose on how many columes and rows he wants to play. i was abble to check win in a row and a colum but i don’t have any idea for a diagonal. I need to make it as simple as posible, and i will be very thenkfull if someone can help.
here is the javascript code:
var rows;
var cols;
var Array;
var tor = 0;
function XO() {
rows = +prompt("Enter rows : ");
cols = +prompt("Enter cols : ");
intBoard = new Array(rows);
var r, c;
for (r = 0; r < intBoard.length; r++) {
intBoard[r] = new Array(cols);
for (c = 0; c < cols; c++) {
intBoard[r][c] = 0;
}
}
var idNum = 0;
var strToShow = "<table border='1'>";
for (var r = 0; r < rows; r++) {
strToShow = strToShow + "<tr>";
for (var c = 0; c < cols; c++) {
strToShow = strToShow + "<td id='" + idNum.toString() +
" ' onclick='TdClicked(this)' width='80px' height='80px' >";
//strToShow = strToShow + idNum.toString();
strToShow = strToShow + "<img src='background.jpg' width='80px' height='80px' />";
strToShow = strToShow + "</td>";
idNum++;
}
strToShow = strToShow + "</tr>";
}
strToShow = strToShow + "</table>";
document.write(strToShow);
}
var showfirst = 0;
function TdClicked(tdClickedThis) {
var idClicked = tdClickedThis.id;
var rowClicked = Math.floor(idClicked / cols);
var colClicked = idClicked % cols;
if (showfirst == 0) {
document.getElementById(idClicked).innerHTML = "<img width='80px' height='80px' src='wolf.jpg'/>";
showfirst++;
intBoard[rowClicked][colClicked] = 1;
for (c = 0; c < cols; c++) { // check win in column
if (intBoard[rowClicked][c] != 1)
c = cols + 111; //break;
}
if (c == cols)
alert("PLAYER X WIN!!")
for (r = 0; r < rows; r++) { // check win in row
if (intBoard[r][colClicked] != 1)
r = rows + 111; //break;
}
if (r == rows)
alert("PLAYER X WIN!!")
}
else {
document.getElementById(idClicked).innerHTML = "<img width='80px' height='80px' src='fox.png'/>";
showfirst--;
intBoard[rowClicked][colClicked] = 2;
for (c = 0; c < cols; c++) { //check win in column
if (intBoard[rowClicked][c] != 2)
c = cols + 111; //break;
}
if (c == cols)
alert("PLAYER O WIN!!")
for (r = 0; r < rows; r++) { // check win in row
if (intBoard[r][colClicked] != 2)
r = rows + 111; //break;
}
if (r == rows)
alert("PLAYER O WIN!!")
}
}