How do I check diagonal win in TIC Tac Toe? - javascript

I created a Tic Tac Toe game in 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.
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!!")
}
}

Related

How to make a diamond in javascript with nested loops?

I have made this code, but only works for the right half of the diamond, how do I make the full diamond? I need to use nested loops
function myDiamond(){
let row, star;
let toPrint = "";
let rowCount = +prompt("Enter a number to make a diamond");
for (row = 1; row <= rowCount; row++){
for (star = 1; star <= row; star++){
if (star == 1 || star == row){
toPrint +="*";
} else {
toPrint += " ";
}
}
toPrint += "<br>";
}
document.getElementById("figure").innerHTML = toPrint;
for (row = rowCount; row >= 1; row--){
for (star = 1; star <= row; star++){
if (star == 1 || star == row){
toPrint +="*";
} else {
toPrint += " ";
}
toPrint += "<br>";
}
document.getElementById("figure").innerHTML = toPrint;
}
}
Is this what you're trying to do:
function createDimondShape(size) {
var stuff = "";
for (var i = 1; i <= size; i++) {
for (var s = size - 1; s >= i; s--) {
stuff += (" ");
}
for (var j = 1; j <= i; j++) {
stuff += ("* ")
}
stuff += "\n";
}
if (i == size + 1) {
for (var i = 1; i <= size - 1; i++) {
for (var s = 1; s <= i; s++) {
stuff += (" ");
}
for (j = i; j <= size - 1; j++) {
stuff += ("* ");
}
stuff += "\n";
}
}
document.getElementById("figure").innerHTML = stuff;
}
createDimondShape(5);
<pre id="figure"></pre>
Couple of trials here:
function createDimondShape(a, size) {
var stuff = "";
for (var i = 1; i <= size; i++) {
for (var s = size - 1; s >= i; s--) {
stuff += (" ");
}
for (var j = 1; j <= i; j++) {
stuff += ("* ")
}
stuff += "\n";
}
if (i == size + 1) {
for (var i = 1; i <= size - 1; i++) {
for (var s = 1; s <= i; s++) {
stuff += (" ");
}
for (j = i; j <= size - 1; j++) {
stuff += ("* ");
}
stuff += "\n";
}
}
document.getElementById("figure" + a).innerHTML += stuff;
}
createDimondShape(1, 3);
createDimondShape(2, 7);
.f {
display: flex;
flex-direction: row;
}
.f pre {
width: 45%;
}
<div class="f">
<pre id="figure1"></pre>
<pre id="figure2"></pre>
</div>
Preview
With prompt, as asked in the comments:
function createDimondShape(size) {
var stuff = "";
for (var i = 1; i <= size; i++) {
for (var s = size - 1; s >= i; s--) {
stuff += (" ");
}
for (var j = 1; j <= i; j++) {
stuff += ("* ")
}
stuff += "\n";
}
if (i == size + 1) {
for (var i = 1; i <= size - 1; i++) {
for (var s = 1; s <= i; s++) {
stuff += (" ");
}
for (j = i; j <= size - 1; j++) {
stuff += ("* ");
}
stuff += "\n";
}
}
document.getElementById("figure").innerHTML = stuff;
}
createDimondShape(+prompt("Enter a number..."));
<pre id="figure"></pre>
you can do that
document.querySelectorAll('input[type=range]').forEach(r=>r.oninput=_=>r.closest('label').dataset.val=r.value)
btDiamond.onclick=_=>
{
const szD = szDiam.valueAsNumber
oneDiamond.textContent = ''
for(let sp=szD;sp--;)
oneDiamond.textContent += ' '.repeat(sp) + '/'.repeat(szD-sp) + '\\'.repeat(szD-sp) + '\n'
for(let sp=0;sp<szD;sp++)
oneDiamond.textContent += ' '.repeat(sp) + '\\'.repeat(szD-sp) + '/'.repeat(szD-sp) + '\n'
}
label, pre {
margin : 0.5em 1.2em;
}
label input {
vertical-align : middle;
width : 300px;
}
label::after {
display: inline-block;
content : attr(data-val);
width : 2em;
}
<h4>shine bright like a diamond</h4>
<label data-val="6">
size :
<input type="range" id="szDiam" min="1" max="20" value="6">
</label>
<button id="btDiamond"> draw !</button>
<hr>
<pre id="oneDiamond"> your diamond will go here </pre>

How i can force the unique Cell to stay and not disappear when I click any cells in my table?

The main goal to let player A pick vertical and player B to pick horizontal.
Please run the snippet code to understand my question better!, thanks a lot
I have unique cell with Symbol S and color red, however if i click any cell, it disappears and normal numbers replace it. How i can force the unique Cell to stay and not disappear when I click any cells in my table?
var isCol = 0;
var board = [];
for (r = 0; r < 7; r++) {
var line = [];
for (c = 0; c < 7; c++) {
line.push(RandomGenerator(50, 500));
}
board.push(line);
}
function prs(c, r) {
showTable(c, r);
isCol = (isCol + 1) % 2;
}
function toColor(col, row, chosen_col, chosen_row) {
var ret = false;
switch (isCol) {
case 0:
if (row == chosen_row) {
ret = true;
}
break;
case 1:
if (col == chosen_col) {
ret = true;
}
break;
}
return ret;
}
function showTable(chosen_col, chosen_row) {
var str = "";
str += "<table border=1>";
for (row = 0; row < 7; row++) {
str += "<tr>";
for (col = 0; col < 7; col++) {
str += "<td onclick='prs(" + col + "," + row + ")'";
if (toColor(col, row, chosen_col, chosen_row)) {
str += " class='grn' ";
}
str += ">";
str += board[row][col];
str += "</td>";
}
str += "</tr>";
}
str += "</table>";
document.getElementById("ff").innerHTML = str;
}
function RandomGenerator(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
showTable(-1);
var getUnique = function(){
var tdElements = document.querySelectorAll('#ff td');
tdElements[
RandomGenerator(0, tdElements.length)
].classList.add('uniqueCell');
// update the text of the cell using the class
document.querySelector('.uniqueCell').textContent = 'S';
};
getUnique();
td{
border:2px solid black;
width:10px;
height:10px;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
.uniqueCell {
background-color: tomato;
text-align: center;
}
<div id="ff"></div>
added
document.querySelectorAll("#ff td")[uniqueCell].innerHTML='S';
document.querySelectorAll("#ff td")[uniqueCell].className ='uniqueCell';
uniqueCell is the random td number
var isCol = 0;
var board = [];
for (r = 0; r < 7; r++) {
var line = [];
for (c = 0; c < 7; c++) {
line.push(RandomGenerator(50, 500));
}
board.push(line);
}
function prs(c, r) {
showTable(c, r);
isCol = (isCol + 1) % 2;
document.querySelectorAll("#ff td")[uniqueCell].innerHTML='S';
document.querySelectorAll("#ff td")[uniqueCell].className ='uniqueCell';
}
function toColor(col, row, chosen_col, chosen_row) {
var ret = false;
switch (isCol) {
case 0:
if (row == chosen_row) {
ret = true;
}
break;
case 1:
if (col == chosen_col) {
ret = true;
}
break;
}
return ret;
}
function showTable(chosen_col, chosen_row) {
var str = "";
str += "<table border=1>";
for (row = 0; row < 7; row++) {
str += "<tr>";
for (col = 0; col < 7; col++) {
str += "<td onclick='prs(" + col + "," + row + ")'";
if (toColor(col, row, chosen_col, chosen_row)) {
str += " class='grn' ";
}
str += ">";
str += board[row][col];
str += "</td>";
}
str += "</tr>";
}
str += "</table>";
document.getElementById("ff").innerHTML = str;
}
function RandomGenerator(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
showTable(-1);
var getUnique = function(){
var tdElements = document.querySelectorAll('#ff td');
uniqueCell=RandomGenerator(0, tdElements.length);
tdElements[
uniqueCell
].classList.add('uniqueCell');
// update the text of the cell using the class
document.querySelector('.uniqueCell').textContent = 'S';
};
var uniqueCell;
getUnique();
td{
border:2px solid black;
width:10px;
height:10px;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
.uniqueCell {
background-color: tomato;
text-align: center;
}
<div id="ff"></div>
Function showTable(...) generates table every time and replaces with innerHtml with new one. getUnique marks cell only at beginnning.
The possible solution, to store var randomCell = RandomGenerator(...) before showTable(-1), and set class uniqueCell in showTable(...)

Check background colour of the grid of buttons in my code

What I'm trying to do, is get it so when all of the buttons have been turned to black, it displays the h2 text in the 'lightsoff' div. So if any of the buttons aren't black, the text will be hidden.
I'd like to be able to do it by writing a new function that carries out the checking of the background colour.
function toggle(i, j) {
b = document.getElementById("but_" + i + j)
t = b.innerHTML
if (t == "X") {
b.innerHTML = "O";
b.setAttribute("style", "color:red; background-color:yellow")
}
if (t == "O") {
b.innerHTML = "X";
b.setAttribute("style", "color:white; background-color:black")
}
}
function press(i, j) {
toggle(i, j);
if (i > 0) {
toggle(i - 1, j);
}
if (i < 4) {
toggle(i + 1, j);
}
if (j > 0) {
toggle(i, j - 1);
}
if (j < 4) {
toggle(i, j + 1);
}
}
function generateGrid() {
var d = document.getElementById("button-grid");
var table = document.createElement("table");
d.appendChild(table);
for (var i = 0; i < 5; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 5; j++) {
var cell = document.createElement("td");
cell.innerHTML = "<button type=button id=but_" + i + j +
" onclick=\"press(" + i + ',' + j + ")\"" +
" style=\"color:red; background-color:yellow\"" +
">O</button>";
row.appendChild(cell);
}
table.appendChild(row);
}
toggle(2, 2)
}
window.onload = function() {
generateGrid();
};
<center>
<h1>Lights Off Puzzle</h1>
<h3>Click on the buttons until they all turn black!</h3>
<div id="button-grid"></div>
<div id="lightsoff">
<h2>All the lights are out, you win!</h2>
</div>
</center>
Use classes and count
function toggle(i, j) {
b = document.getElementById("but_" + i + j)
t = b.innerHTML
if (t == "X") {
b.innerHTML = "O";
b.className="on"
}
if (t == "O") {
b.innerHTML = "X";
b.className="off"
}
var off = document.querySelectorAll(".off").length === document.querySelectorAll("#button-grid table tr td").length; // are all off
document.getElementById("lightsoff").style.display= off ? "block":"none"; // ternary shorthand for if (something) x=a; else x=b;
}
function press(i, j) {
toggle(i, j);
if (i > 0) {
toggle(i - 1, j);
}
if (i < 4) {
toggle(i + 1, j);
}
if (j > 0) {
toggle(i, j - 1);
}
if (j < 4) {
toggle(i, j + 1);
}
}
function generateGrid() {
var d = document.getElementById("button-grid");
var table = document.createElement("table");
d.appendChild(table);
for (var i = 0; i < 5; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 5; j++) {
var cell = document.createElement("td");
cell.innerHTML = "<button type=button id=but_" + i + j +
" onclick=\"press(" + i + ',' + j + ")\"" +
" class='red'" +
">O</button>";
row.appendChild(cell);
}
table.appendChild(row);
}
toggle(2, 2)
}
window.onload = function() {
generateGrid();
};
.on {color:red; background-color:yellow}
.off {color:white; background-color:black}
#lightsoff { display: none }
<center>
<h1>Lights Off Puzzle</h1>
<h3>Click on the buttons until they all turn black!</h3>
<div id="button-grid"></div>
<div id="lightsoff">
<h2>All the lights are out, you win!</h2>
</div>
</center>
Toggle a class using classList for the state and then look at the number of elements with that class by using querySelectorAll().
function toggle(i, j) {
b = document.getElementById("but_" + i + j)
b.classList.toggle("on")
b.textContent = b.classList.contains("on") ? "O" : "X"
}
function press(i, j) {
toggle(i, j);
if (i > 0) {
toggle(i - 1, j);
}
if (i < 4) {
toggle(i + 1, j);
}
if (j > 0) {
toggle(i, j - 1);
}
if (j < 4) {
toggle(i, j + 1);
}
console.log("Number of on buttons is: ", document.querySelectorAll("button.on").length)
}
function generateGrid() {
var d = document.getElementById("button-grid");
var table = document.createElement("table");
d.appendChild(table);
for (var i = 0; i < 5; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 5; j++) {
var cell = document.createElement("td");
cell.innerHTML = "<button type=button id=but_" + i + j +
" onclick=\"press(" + i + ',' + j + ")\"" +
" class='on' " +
">O</button>";
row.appendChild(cell);
}
table.appendChild(row);
}
toggle(2, 2)
}
window.onload = function() {
generateGrid();
};
td button{
color: #FFF;
background-color: #000;
}
td button.on {
color: red;
background-color: #FFC;
}
<center>
<h1>Lights Off Puzzle</h1>
<h3>Click on the buttons until they all turn black!</h3>
<div id="button-grid"></div>
<div id="lightsoff">
<h2>All the lights are out, you win!</h2>
</div>
</center>
If you really want to do it without using classes than you need to loop over all the cells and see if any of them are the color. Checking color codes can be a pain because not all browsers return the same thing. I would just check the text.
function check()
var btns = document.querySelectorAll("button")
for (var i=0; i<btns.length; i++) {
if (btns[i].textContent === "O") return false
}
return true
}

Display an alert box with line-breaks in for loop dynamically in javascript

here I want one row then line break then another row and so on.... in only one alert message...
function GetCellValues()
{
var rows = document.getElementsByTagName('tr');
var str = '';
for (var c = 1 ; c < rows.length ; c++)
{
var row = rows[c];
var inputs = row.getElementsByTagName('input');
for (var k = 0 ; k < inputs.length ; k++)
{
str += inputs[k].value + ', ';
}
}
alert(str);
}
Use a newline character: \n
function GetCellValues()
{
var rows = document.getElementsByTagName('tr');
var str = '';
for (var c = 1 ; c < rows.length ; c++)
{
var row = rows[c];
var inputs = row.getElementsByTagName('input');
for (var k = 0 ; k < inputs.length ; k++)
{
str += inputs[k].value + '\n';
}
}
alert(str);
}
try this as you want line breaks for each row.we have add line breaks in outer for loop
function GetCellValues()
{
var rows = document.getElementsByTagName('tr');
var str = '';
for (var c = 1 ; c < rows.length ; c++)
{
var row = rows[c];
var inputs = row.getElementsByTagName('input');
for (var k = 0 ; k < inputs.length ; k++)
{
str += inputs[k].value + ',';
}
str += inputs[k].value + '\n';
}
alert(str);
}
Just use '\n' in place of ', '

How to create a dynamic table in a dynamic cell?

I created a dynamic table that contains 20 rows and 2 columns. this is my code:
function createTblBtnClick() {
var tbl = document.createElement("table");
tbl.setAttribute("id", "myTable");
tbl.setAttribute("dir", "rtl");
tbl.cellPadding = 0;
tbl.cellSpacing = 0;
for (i = 0; i < rowNum; i++) {
var row = tbl.insertRow(-1);
for (j = 0; j < colNum; j++) {
var cell = row.insertCell(-1);
cell.setAttribute("id", "cell" + i.toString() + "-" + j.toString());
}
}
document.getElementById("MyTablePanel").innerHTML = "";
document.getElementById("MyTablePanel").appendChild(tbl);
for (i = 0; i < rowNum; i++) {
for (j = 0; j < colNum; j++) {
var srt = "<a href='javascript:select(" + i.toString() + "," + j.toString() + ")' ><div id='div-" + i.toString() + "-" + j.toString() + "'> </div></a>";
document.getElementById("cell" + i.toString() + "-" + j.toString()).innerHTML = srt;
}
}
}
Now I want to add another table in any of my cells. In fact I want to divide each of my cells to 2. How can I do it?
I test below code but it creates 4 column in a row :
function createTblBtnClick() {
var tbl = document.createElement("table");
var tb2 = document.createElement("table");
tbl.setAttribute("id", "myTable");
tbl.setAttribute("dir", "rtl");
tbl.cellPadding = 0;
tbl.cellSpacing = 0;
tb2.setAttribute("id", "myTable1");
//tbl.setAttribute("dir", "rtl");
tb2.cellPadding = 0;
tb2.cellSpacing = 0;
var inner_tb = 0;
for (i = 0; i < rowNum; i++) {
var row = tbl.insertRow(-1);
for (j = 0; j < colNum; j++) {
var cell = row.insertCell(-1);
cell.setAttribute("id", "cell" + i.toString() + "-" + j.toString());
}
}
document.getElementById("MyTablePanel").innerHTML = "";
document.getElementById("MyTablePanel").appendChild(tbl);
////////////////////////////////////////////////////////
var row1 = tb2.insertRow(-1);
for (inner_tb = 0; inner_tb < 2; inner_tb++) {
var cell1 = row.insertCell(-1);
cell.setAttribute("id", "in_cell " + inner_tb.toString());
}
document.getElementById("cell" + i.toString() + "-" + j.toString()).innerHTML = "";
document.getElementById("cell" + i.toString() + "-" + j.toString()).appendChild(tb2);
///////////////////////////////////////////////////////////////
for (i = 0; i < rowNum; i++) {
for (j = 0; j < colNum; j++) {
var srt = "<a href='javascript:select(" + i.toString() + "," + j.toString() + ")' ><div id='div-" + i.toString() + "-" + j.toString() + "'> </div></a>";
document.getElementById("cell" + i.toString() + "-" + j.toString()).innerHTML = srt;
}
}
}
Do exactly the same logic, but append the table to a cell reference.
var innerTbl = document.createElement("table");
//Populate the table...
//With the table populated, append it in the cell of the outertable.
cell.appendChild(innerTbl);
I think this might be what you're trying to do:
http://jsfiddle.net/mPwpq/1/
function createTblBtnClick() {
var rowNum = 20;
var colNum = 2;
var tbl = document.createElement("table");
tbl.setAttribute("id", "myTable");
tbl.setAttribute("dir", "rtl");
tbl.cellPadding = 0;
tbl.cellSpacing = 0;
for (i = 0; i < rowNum; i++) {
var row = tbl.insertRow(-1);
for (j = 0; j < colNum; j++) {
var cell = row.insertCell(-1);
cell.setAttribute("id", "cell" + i.toString() + "-" + j.toString());
// Add inner table with two columns
var innerTbl = document.createElement("table");
innerTbl.innerHTML = '<tr><td>A</td><td>B</td></tr>';
cell.appendChild(innerTbl);
}
}
document.getElementById("MyTablePanel").innerHTML = "";
document.getElementById("MyTablePanel").appendChild(tbl);
}
just a suggestion. Rather than using javascript for doing creating table, why not create the table in the HTML. Get that table in a var using Document.getElementByID. create new string variable like "thisRow" and add the HTML code in the string of the variable like
thisRow += "rowcellinner table"
and then use .append(thisRow);
you can assign the value to thisRow variable in each counter of the loop and append it to table. I find this easier to do.

Categories