How to check Conway's Game Of Life Code - Glider Gun - javascript

I have written code of Conway's Game Of Life with JS and I'm pretty sure something is wrong. I'm trying to imitate Gosper glider gun, but even when starting with the right pattern, i can't built any gliders.
I wrote an interface with buttons to toggle, stop and clear the game, and also a button that initializes the game to the pattern of the glider gun
I couldn't fit the table in full into the question here - need to add extra rows for it to work
var main = document.getElementById("main");
document.getElementById("toggle").setAttribute("onclick", "toggleTable()");
document.getElementById("stop").setAttribute("onclick", "stopTable()");
document.getElementById("setGun").setAttribute("onclick", "setGun()");
document.getElementById("clear1").setAttribute("onclick", "clear1()");
for (var i = 0; i < main.rows.length; i++) {
var currow = main.rows[i];
for (var f = 0; f < currow.cells.length; f++)
currow.cells[f].setAttribute("onclick", "changeColor(this)");
}
function changeColor(item) {
item.classList.toggle("clicked");
}
function clear1() {
for (var i = 0; i < main.rows.length; i++) {
var currow = main.rows[i];
for (var f = 0; f < currow.cells.length; f++)
main.rows[i].cells[f].classList.remove("clicked");
}
}
function setGun() {
changeColor(main.rows[3].cells[36]);
changeColor(main.rows[3].cells[37]);
changeColor(main.rows[4].cells[36]);
changeColor(main.rows[4].cells[37]);
changeColor(main.rows[1].cells[26]);
changeColor(main.rows[2].cells[26]);
changeColor(main.rows[2].cells[24]);
changeColor(main.rows[3].cells[23]);
changeColor(main.rows[3].cells[22]);
changeColor(main.rows[4].cells[23]);
changeColor(main.rows[4].cells[22]);
changeColor(main.rows[5].cells[23]);
changeColor(main.rows[5].cells[22]);
changeColor(main.rows[6].cells[24]);
changeColor(main.rows[6].cells[26]);
changeColor(main.rows[7].cells[26]);
changeColor(main.rows[5].cells[2]);
changeColor(main.rows[5].cells[3]);
changeColor(main.rows[6].cells[2]);
changeColor(main.rows[6].cells[3]);
changeColor(main.rows[3].cells[15]);
changeColor(main.rows[3].cells[14]);
changeColor(main.rows[4].cells[13]);
changeColor(main.rows[5].cells[12]);
changeColor(main.rows[6].cells[12]);
changeColor(main.rows[7].cells[12]);
changeColor(main.rows[8].cells[13]);
changeColor(main.rows[9].cells[14]);
changeColor(main.rows[9].cells[15]);
changeColor(main.rows[6].cells[16]);
changeColor(main.rows[4].cells[17]);
changeColor(main.rows[8].cells[17]);
changeColor(main.rows[5].cells[18]);
changeColor(main.rows[6].cells[18]);
changeColor(main.rows[7].cells[18]);
changeColor(main.rows[6].cells[19]);
}
function calcNeigh(row, cell) {
var countNeigh = 0;
if ((row - 1 != -1 && row - 1 < main.rows.length && cell - 1 != -1 && cell - 1 < main.rows[row].cells.length) && main.rows[row - 1].cells[cell - 1].classList.contains("clicked"))
countNeigh++
if ((row - 1 != -1 && row - 1 < main.rows.length) && main.rows[row - 1].cells[cell].classList.contains("clicked"))
countNeigh++
if ((row - 1 != -1 && row - 1 < main.rows.length && cell + 1 < main.rows[row].cells.length) && main.rows[row - 1].cells[cell + 1].classList.contains("clicked"))
countNeigh++
if ((cell - 1 != -1) && main.rows[row].cells[cell - 1].classList.contains("clicked"))
countNeigh++
if ((cell + 1 != -1 && cell + 1 < main.rows[row].cells.length) && main.rows[row].cells[cell + 1].classList.contains("clicked"))
countNeigh++
if ((row + 1 < main.rows.length && cell - 1 != -1) && main.rows[row + 1].cells[cell - 1].classList.contains("clicked"))
countNeigh++
if ((row + 1 < main.rows.length) && main.rows[row + 1].cells[cell].classList.contains("clicked"))
countNeigh++
if ((row + 1 < main.rows.length && cell + 1 < main.rows[row].cells.length) && main.rows[row + 1].cells[cell + 1].classList.contains("clicked"))
countNeigh++
return countNeigh;
}
function isAlive(i, f) {
if (main.rows[i].cells[f].classList.contains("clicked"))
return true;
else return false;
}
function liveOrDie(neigh, i, f) {
if (isAlive(i, f)) {
if (neigh > 3 || neigh < 2)
main.rows[i].cells[f].classList.remove("clicked");
}
else if (neigh == 3)
main.rows[i].cells[f].classList.add("clicked");
}
var run;
function toggleTable() {
run = setInterval(function () {
for (var i = 0; i < main.rows.length; i++) {
var currow = main.rows[i];
for (var f = 0; f < currow.cells.length; f++) {
liveOrDie(calcNeigh(i, f), i, f);
}
}
}, 200);
}
function stopTable() {
clearInterval(run);
}
#main td {
width: 20px;
height: 20px;
border: 1px solid silver;
}
#main {
text-align: center;
margin: auto;
}
.clicked {
background-color: black;
}
#toggle {
width: 200px;
height: 50px;
background-color: navy;
}
#stop {
width: 200px;
height: 50px;
background-color: green;
}
#setGun {
width: 200px;
height: 50px;
background-color: orchid;
}
#clear1 {
width: 200px;
height: 50px;
background-color: white;
border: 1px solid black;
}
<table id="main">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<div id="toggle">toggle</div>
<div id="stop">stop</div>
<div id="setGun">setGun</div>
<div id="clear1">clear</div>

The problem is that your code updates the cells, while their previous state is still needed to calculate the next state of some neighboring cells, so the calculation for those cells will be wrong.
You need to make sure that all calculations (neigh) are done on a snapshot of the "generation" and not on a mutating state.
Other remarks on your code:
Don't use the DOM to maintain the state of the game. Instead maintain the state in an array data structure, and only write to the DOM (not read from it).
Don't set "onclick" attributes. Instead use addEventListener
Don't use the pattern if <boolean expression> return true; else return false (like you did in isAlive). Instead, just return the boolean expression.
Avoid code repetition, like in setGun, where you can make the logic more data-driven: put the involved values in an array, and then loop over that array to initialise the game
Here is what I would make of your code:
const main = document.getElementById("main");
// Create a memory data structure for the real state of the game
const rowCount = 15, colCount = 50;
let grid = Array.from({length: rowCount}, row => Array(colCount).fill(false));
// Build table dynamically to save repetition in static HTML
main.innerHTML = ("<tr>" + "<td><\/td>".repeat(colCount) + "</tr>").repeat(rowCount);
document.getElementById("toggle").addEventListener("click", startAnimation);
document.getElementById("stop").addEventListener("click", stopAnimation);
document.getElementById("setGun").addEventListener("click", setGun);
document.getElementById("clear").addEventListener("click", clear);
main.addEventListener("click", e => changeColor(e.target.cellIndex, e.target.parentNode.rowIndex));
// Define constant for some configuration:
const GUN = `
--------------------------X
------------------------X-X
--------------XX------XX------------XX
-------------X---X----XX------------XX
--XX--------X-----X---XX
--XX--------X---X-XX----X-X
------------X-----X-------X
-------------X---X
--------------XX`;
// This function alone is responsible for any output
function display() {
grid.forEach((row, y) =>
row.forEach((cell, x) =>
main.rows[y].cells[x].classList.toggle("clicked", cell)
)
);
}
function changeColor(x, y) {
grid[y][x] = !grid[y][x];
display();
}
function clear() {
stopAnimation();
grid.forEach(row => row.fill(false));
display();
}
function setFromString(s) {
clear();
s.match(/\S+/g).forEach((line, y) => {
grid[y].forEach((_, x, row) => row[x] = line[x] == "X")
});
display();
}
function setGun() {
setFromString(GUN);
}
function calcNeigh(x, y) {
return [[x-1,y-1], [x,y-1], [x+1,y-1], [x-1,y], [x+1,y], [x-1,y+1], [x,y+1], [x+1,y+1]]
.reduce((sum, [x, y]) => sum + isAlive(x, y), 0);
}
function isAlive(x, y) {
return !!grid[y]?.[x];
}
function liveOrDie(neigh, x, y) {
return neigh == 2 ? isAlive(x, y) : neigh == 3;
}
function nextGeneration() {
// grid is updated with a new 2D array, so there is no interference!
grid = grid.map((row, y) =>
row.map((cell, x) => liveOrDie(calcNeigh(x, y), x, y))
);
display();
}
let run;
function startAnimation() {
stopAnimation(); // Make sure to first stop the current timer
run = setInterval(nextGeneration, 200);
}
function stopAnimation() {
clearInterval(run);
}
table { border-collapse: collapse }
#main td {
width: 8px;
height: 8px;
border: 1px solid silver;
}
#main {
text-align: center;
margin: auto;
}
.clicked { background-color: black; }
button {
width: 100px;
height: 30px;
}
#toggle { background-color: cyan; }
#stop { background-color: green; }
#setGun { background-color: orchid; }
#clear { background-color: white; }
<table id="main"></table>
<button id="toggle">Start</button>
<button id="stop">Stop</button>
<button id="setGun">Set Gun</button>
<button id="clear">Clear</button>

Related

I cant assign a value to an javascript object key

im trying to make a tetris game , and ive made some progress, but im stuck with an object key assignement problem,
what im trying to do now is detect collisions of the shapes and what i thought of is to keep track of each shape's position
,by storing the coordinates in an object called alreadyOccupiedPos
and this objects stores the shapes as keys
,for example the key name of the first shape to appear will be '1' and the key name of the second shape to appear is '2' ect...
and each shape has a value as an array of arrays, the array includes the squares that make up the shape and each square
is represented as a sub-array, and the sub-array has two elements, the current row and the current column where
the square is within the board. I started by giving the alreadyOccupiedPos object a default key for the first shape.
And i have two key variables , the first one is numberOfSquares which represents the number of squares that the shape consists of,
and it gets reseted each time a new shape gets created or moved and then the i have shapeNumber which is a default parameter in the function that i can use to to refer
to the shape number in the alreadyOccupiedPos object .Now to the problem im facing , in the second loop where the shape drawing happens , and along with drawing the shape,
im trying to insert the location of each square in the alreadyOccupiedPos object by pushing an array that includes the current row and the current column where the
square is into the array that includes the squares of the shape, and this is what i tried to do alreadyOccupiedPos[shapeNumber][numberOfSquares] = [j + step, i + randomHorizantalPos];
and the problem is it just doesnt get assigned.
this is the codepen :
https://codepen.io/marwanoss/pen/gOmxPoP?editors=0010
this is the js code:
let tableBody = document.querySelector('table').children[0];
let tableRows = Array.from(tableBody.children)
//shapes
let L_shape = [
[1, 0, 0],
[1, 0, 0],
[1, 1, 1]
];
let S_shape = [
[0, 1, 1],
[0, 1, 0],
[1, 1, 0]
];
let Z_shape = [
[1, 1, 0],
[0, 1, 0],
[0, 1, 1]
];
let J_shape = [
[0, 0, 1],
[0, 0, 1],
[1, 1, 1]
];
let square_shape = [
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]
];
let I_shape = [
[0, 1, 0],
[0, 1, 0],
[0, 1, 0]
];
let T_shape = [
[1, 1, 1],
[0, 1, 0],
[0, 1, 0]
]
let shapes = [L_shape, S_shape, Z_shape, J_shape, square_shape, I_shape, T_shape]
, colors = ['red', 'black', 'green', 'yellow', 'cyan', 'rgb(44, 10, 10)']
, randomlyChosenColor = colors[Math.floor(Math.random() * colors.length)]
, randomlyChosenShape = shapes[Math.floor(Math.random() * shapes.length)]
, randomHorizantalPos = Math.floor(Math.random() * 13)
, numberOfSquares = 0
, clearLimit = tableRows.length
, alreadyOccupiedPos = { 1: [] };
function recur(step = 0, shapeNumber = 1) {
//this condition checks whether a shape has reached the bottom of the board or not, if so a new shape gets generated and the position get reseted to the top of the board.
if (step === 17) {
clearLimit = step;
randomHorizantalPos = Math.floor(Math.random() * 13);
randomlyChosenShape = shapes[Math.floor(Math.random() * shapes.length)];
randomlyChosenColor = colors[Math.floor(Math.random() * colors.length)];
alreadyOccupiedPos[shapeNumber + 1] = [];
numberOfSquares = 0;
recur(0, shapeNumber)
} else {
//this for loop clears the board
for (let i = 0; i < tableRows.slice(0, clearLimit - 1).length; i++) {
for (let j = randomHorizantalPos; j < randomHorizantalPos + 3; j++) {
tableRows[i].children[j].style.backgroundColor = 'white'
}
}
//after the board gets cleared by the previous loop this loop creates the shape by giving the squares a background color to create the illusion of the shape moving by adding a step in each recursive call
for (let i = 0; i < tableRows.length; i++) {
for (let j = 0; j < randomlyChosenShape.length; j++) {
if (randomlyChosenShape[j][i] === 1) {
tableRows[j + step].children[i + randomHorizantalPos].style.backgroundColor = randomlyChosenColor;
alreadyOccupiedPos[shapeNumber][numberOfSquares] = [j + step, i + randomHorizantalPos];
numberOfSquares++;
}
}
}
setTimeout(() => {
numberOfSquares = 0;
recur(step + 1, shapeNumber)
}, 1000);
}
}
recur()
and this is the html (thats alot of html lol, i could've created the html using a loop in js i just forgot xD) :
<body>
<table>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<script src="tetris.js"></script>
</body>
and this is the css:
body{
display: flex;
padding: 0;
margin: 0;
box-sizing: border-box;
background-color: black;
}
html{
font-size: 10px;
}
table{
background-color: white;
height: 60rem;
width: 50rem;
margin: 5% auto;
}
table td{
background-color: white;
border: black .1px solid;
}
alreadyOccupiedPos[shapeNumber][numberOfSquares] has already been assigned. Maybe you need to change the line
recur(0, shapeNumber)
to
recur(0, shapeNumber + 1);
to assign the value to the newly created array.

highlighting the new drawn number

I would like to specify my page and add that only the latest generated number is highlighted. The current page highlights each number and I would like it to highlight only the latest number in the table and then go out, i.e. when the number 12 is drawn, the cell with the number 12 will be highlighted, and if the number is drawn 55 then 12 goes out and 55 lights up
jQuery(function ($) {
var bingo = {
selectedNumbers: [],
generateRandom: function () {
var min = 1; //Liczba początkowa
var max = 89; //Liczba końcowa
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return random;
},
generateNextRandom: function () {
if (bingo.selectedNumbers.length > 88) {
alert("Koniec");
return 0;
}
var random = bingo.generateRandom();
while ($.inArray(random, bingo.selectedNumbers) > -1) {
random = bingo.generateRandom();
}
bingo.selectedNumbers.push(random);
return random;
},
};
$("td").each(function () {
var concatClass = this.cellIndex + "" + this.parentNode.rowIndex;
var numberString = parseInt(concatClass, 10).toString();
$(this)
.addClass("cell" + numberString)
.text(numberString);
$(".cell" + numberString).attr("CellValue", numberString);
});
$("#btnGenerate").click(function () {
var random = bingo.generateNextRandom().toString();
$(".bigNumberDisplay span").text(random);
$("td.cell" + random).addClass("selected");
$("td").each(function () {
if ($(this).attr("CellValue") === random) {
$(this).css("background-color", "yellow");
}
});
});
window.onbeforeunload = function (e) {
e = e || window.event;
var returnString = "Are you sure?";
if (e) {
e.returnValue = returnString;
}
return returnString;
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="pl">
<head>
<title> Bingo</title>
<link href="style.css" rel="stylesheet" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.js"></script>
<script src="./index.js"></script>
</head>
<body>
<div class="container">
<div class="bigNumberDisplay">
<span>0</span>
</div>
<div>
<input id="btnGenerate" type="button" value="Wylosuj numer stolika" />
</div>
<br />
<div class="numbersTable">
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
<br />
</div>
</body>
</html>
div {
text-align: center;
}
.bigNumberDisplay {
font-size: 6em;
}
.numbersTable {
font-size: 1.6em;
}
table {
margin-left: auto;
margin-right: auto;
}
table,
tr,
td {
border-collapse: collapse;
border: solid 1px #999;
}
td {
min-width: 100px;
color: #fff;
}
td.selected {
color: #000000;
}
a basic design in which each number highlights
You can do it like this: Instead of setting the inline style background-color: yellow, add a class to the newly appended cell. When the generate button is clicked, remove this class from all cells and add it only to the newly appended cell.
jQuery(function($) {
var bingo = {
selectedNumbers: [],
generateRandom: function() {
var min = 1; //Liczba początkowa
var max = 89; //Liczba końcowa
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return random;
},
generateNextRandom: function() {
if (bingo.selectedNumbers.length > 88) {
alert("Koniec");
return 0;
}
var random = bingo.generateRandom();
while ($.inArray(random, bingo.selectedNumbers) > -1) {
random = bingo.generateRandom();
}
bingo.selectedNumbers.push(random);
return random;
},
};
$("td").each(function() {
var concatClass = this.cellIndex + "" + this.parentNode.rowIndex;
var numberString = parseInt(concatClass, 10).toString();
$(this)
.addClass("cell" + numberString)
.text(numberString);
$(".cell" + numberString).attr("CellValue", numberString);
});
$("#btnGenerate").click(function() {
var random = bingo.generateNextRandom().toString();
$(".bigNumberDisplay span").text(random);
$("td.cell" + random).addClass("selected");
$("td.active").removeClass("active");
$("td").each(function() {
if ($(this).attr("CellValue") === random) {
$(this).addClass("active");
}
});
});
window.onbeforeunload = function(e) {
e = e || window.event;
var returnString = "Are you sure?";
if (e) {
e.returnValue = returnString;
}
return returnString;
};
});
.active {
background-color:yellow;
}
div {
text-align: center;
}
.bigNumberDisplay {
font-size: 6em;
}
.numbersTable {
font-size: 1.6em;
}
table {
margin-left: auto;
margin-right: auto;
}
table,
tr,
td {
border-collapse: collapse;
border: solid 1px #999;
}
td {
min-width: 100px;
color: #fff;
}
td.selected {
color: #000000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="pl">
<head>
<title> Bingo</title>
<link href="style.css" rel="stylesheet" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.js"></script>
<script src="./index.js"></script>
</head>
<body>
<div class="container">
<div class="bigNumberDisplay">
<span>0</span>
</div>
<div>
<input id="btnGenerate" type="button" value="Wylosuj numer stolika" />
</div>
<br />
<div class="numbersTable">
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
<br />
</div>
</body>
</html>
I would use a CSS class to make the highlighted number yellow:
.highlight {
background-color: yellow;
}
I would add that class to the cell that you want to highlight. It looks like you are looping through all td elements and finding the one with the right CellValue attribute. You can select that element using CSS selectors instead.
So try replacing this code:
$("td").each(function () {
if ($(this).attr("CellValue") === random) {
$(this).css("background-color", "yellow");
}
});
With:
$('.highlight').removeClass('highlight');
$('td[CellValue="' + random + '"]').addClass('highlight');
This would also remove the highlight class from the cell you first selected.
This is using CSS attribute selectors to target the correct cell. You can read more about CSS attribute selectors here: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
The accepted answer is great. I just thought it would be fun to make a concise version of this with rando.js and jquery.
var ROWS = 10;
var COLS = 9;
$(document).ready(function() {
var htmlToAdd = "";
for (var i = 0; i < ROWS; i++) {
htmlToAdd += "<tr>";
for (var j = 0; j < COLS; j++) htmlToAdd += "<td style=\"width:" + 100 / COLS + "%;\">" + (i + (COLS + 1) * j) + "</td>";
htmlToAdd += "</tr>";
}
$("table").html(htmlToAdd);
});
function showNext() {
$(".highlighted").removeClass("highlighted");
if (pick = rando($("td").not(".shown")).value || false) $("#result").text(pick.addClass("shown").addClass("highlighted").text());
}
body{ padding:50px; text-align:center; }
#result{ font-size:96px; }
table{ border-collapse:collapse; width:100%; }
td{ color:transparent; border:1px solid #999; text-align:center; font-size:25px; }
td.shown{ color:black; }
td.highlighted{ background:yellow; }
button{ margin:20px 0px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://randojs.com/1.0.0.js"></script>
<div id="result">0</div>
<button onclick="showNext();">Show next</button>
<table></table>

how can i put <td> on table cells?

First I made a table that have date titles in different format such as number of the gregorian date and name of the days of the Week and number of the persian date.
I want to color them when I select some cells and display them as a cell where text can be written inside such as below image:
![The desired table photo][1]
please help me to edit codes for create a table such as top image.
The table I made is as follows:
let jyear = moment().locale('fa').format('YYYY');
let jmonth = moment().locale('fa').format('M');
console.log("jyear", jyear);
console.log("jmonth", jmonth);
var d = new Date();
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
document.getElementById("EN-Year").innerHTML = d.getFullYear();
document.getElementById("EN-Month").innerHTML = months[d.getMonth()] + '-' + months[d.getMonth() + 1];
document.getElementById("shamsi_year").innerHTML = jyear;
document.getElementById("shamsi_month").innerHTML = moment().locale('fa').format('jMMMM');
document.getElementById("shamsi_month2").innerHTML = moment().locale('fa').format('jMMMM');
renderHeaderGrid(jyear, jmonth);
function renderHeaderGrid(jyear, jmonth) {
let jDate = moment.from(`${jyear}/${jmonth}/01`, 'fa', 'YYYY/MM/DD');
jDate = jDate.locale("fa");
let daysInMonth = jDate.daysInMonth();
let miladi_date = jDate.locale("en");
for (let i = 0; i < daysInMonth; i++) {
let miladiDayNameInWeek = miladi_date.format("dd"); //miladi day name of weeek
let miladiDayInMonth = miladi_date.format("DD"); //miladi day num
let shamsiDayInMonth = jDate.format("jDD"); //shamsi day num
let th_week_name = document.createElement("th");
let th_day_num = document.createElement("th");
let th_shamsi_day_num = document.createElement("th");
th_week_name.innerText = miladiDayNameInWeek;
th_day_num.innerText = miladiDayInMonth;
th_shamsi_day_num.innerText = shamsiDayInMonth;
document.getElementById("tr_days_name").append(th_week_name);
document.getElementById("tr_days_num").append(th_day_num);
document.getElementById("tr_days_shamsi_num").append(th_shamsi_day_num);
miladi_date.add(1, "d");
}
}
* {
direction: rtl;
}
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
position: relative;
}
.table {
width: 100%;
}
.month {
background-color: orange;
}
.place {
background-color: rgb(77, 207, 77);
}
.other,
.title {
background-color: rgb(141, 140, 140);
}
<table id="ttt" class="table" border="1" summary="This table gives some statistics about fruit
flies: average height and weight, and percentage
with red eyes (for both males and females).">
<caption>
<EM>A test table with merged cells</EM>
</caption>
<tr>
<th class="title" colspan="34"></th>
</tr>
<tr id="tr_days_name">
<th colspan="4">DAY</th>
</tr>
<tr id="tr_days_num" colspan="2">
<th id="EN-Year" colspan="2"></th>
<th id="EN-Month" class="month" colspan="2"></th>
</tr>
<tr rowspan="1" colspan="2" id="tr_days_shamsi_num">
<th id="shamsi_year" colspan="2"></th>
<th id="shamsi_month" class="month" colspan="2"></th>
</tr>
<tr id="firstplace">
<th id="shamsi_month2" colspan="2" rowspan="6"></th>
<th class="place" colspan="2"></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th class="place" colspan="2"></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th class="place" colspan="2"></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th class="place" colspan="2"></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th class="place" colspan="2"></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th class="other" colspan="2"></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<script src="https://unpkg.com/jalali-moment/dist/jalali-moment.browser.js"></script>
Hope this gives you an idea:
const cells = document.querySelectorAll(".cell");
cells.forEach((cell, i) => {
cell.addEventListener("click", () => {
cell.innerHTML = `<input type="text" id="cell-input_${i}">`
const cellInput = document.querySelector(`#cell-input_${i}`)
cellInput.focus()
cellInput.addEventListener("blur", () => {
cell.innerHTML = cellInput.value
});
});
});
.cell {
border: 1px solid black;
height: 20px;
min-width: 20px;
}
<table>
<tr>
<td class="cell"></td>
<td class="cell"></td>
<td class="cell"></td>
<td class="cell"></td>
<td class="cell"></td>
</tr>
</table>

How to get random numbers in a table cell in html using javascript

I want to generate number "1" in random cells from my table. There is a game like: you will select a table by pressing a button, after press play. When you will press play I want to put random the number "1" but not in all cells. (e.g: if table is 8x8, put 8 of "1" in the table, if table is 6x6, put 6 of "1" in the table and so on...) I create 3 tables in html and put them hidden with javascript.
Now I want some hints, some help from you guys. Thank you! Here is my code:
//Variables
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
var button3 = document.getElementById('button3');
var backBtn = document.getElementById('back-btn');
var playBtn = document.getElementById('play-btn');
var sixTable = document.getElementById('sixXsix');
var eightTable = document.getElementById('eightXeight');
var steenTable = document.getElementById('steen');
//Visibility starter
sixTable.style.display = 'none';
eightTable.style.display = 'none';
steenTable.style.display = 'none';
backBtn.style.display = 'none';
playBtn.style.display = 'none';
//Buttons function
button1.onclick = function() {
var six = document.getElementById('sixXsix');
var eight = document.getElementById('eightXeight');
var steen = document.getElementById('steen');
if (six.style.display === 'none') {
six.style.display = 'block';
eight.style.display = 'none';
steen.style.display = 'none';
button1.style.display = 'none';
button2.style.display = 'none';
button3.style.display = 'none';
backBtn.style.display = 'block';
playBtn.style.display = 'block';
}
}
button2.onclick = function() {
var six = document.getElementById('sixXsix');
var eight = document.getElementById('eightXeight');
var steen = document.getElementById('steen');
if (eight.style.display === 'none') {
six.style.display = 'none';
eight.style.display = 'block';
steen.style.display = 'none';
button1.style.display = 'none';
button2.style.display = 'none';
button3.style.display = 'none';
backBtn.style.display = 'block';
playBtn.style.display = 'block';
}
}
button3.onclick = function() {
var six = document.getElementById('sixXsix');
var eight = document.getElementById('eightXeight');
var steen = document.getElementById('steen');
if (steen.style.display === 'none') {
six.style.display = 'none';
eight.style.display = 'none';
steen.style.display = 'block';
button1.style.display = 'none';
button2.style.display = 'none';
button3.style.display = 'none';
backBtn.style.display = 'block';
playBtn.style.display = 'block';
}
}
backBtn.onclick = function() {
sixTable.style.display = 'none';
eightTable.style.display = 'none';
steenTable.style.display = 'none';
backBtn.style.display = 'none';
playBtn.style.display = 'none';
button1.style.display = 'block';
button2.style.display = 'block';
button3.style.display = 'block';
}
playBtn.onclick = function() {
}
<div id="buttons">
<button id="button1">6x6 Table</button>
<button id="button2">8x8 Table</button>
<button id="button3">16x16 Table</button>
<button id="back-btn">Back</button>
<button id="play-btn">Play</button>
</div>
<div id="table">
<div id="sixXsix">
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
<div id="eightXeight">
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
<div id="steen">
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
</div>
This below code uses jquery to generate random numbers between 1 and the number of cells and then places a 1 in the corresponding cell.
If any of it is not clear, let me know.
Hope this helps.
$('#playBtn').on('click', function() {
var cellsCount = $('#table1 td').length;
var rows = $('#table1 tr').length;
var usedCells = [];
if (rows != $("#table1 tr:first-child td").length) {
alert("The grid is not a square, I dont know how many cells to mark.");
return;
}
// empty all cells first
$("#table1 td").empty();
$("#table1 td").css("background-color", "white");
// generate random numbers between 1 and the number of cells available
// (no duplicates)
while (usedCells.length < rows) {
randCell = Math.floor(Math.random() * cellsCount);
if (usedCells.indexOf(randCell) == -1) {
usedCells.push(randCell);
}
}
// for each number generate, color the cell and add the "1"
$.each(usedCells, function(index, value) {
cell = "#table1 td:eq(" + value + ")";
$(cell).html("1");
$(cell).css("background-color", "red");
});
});
td {
border: 1px solid black;
height: 25px;
width: 25px;
text-align: center;
background-color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button id="playBtn">Play</button>
<br>
<table id="table1">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
This snippet uses a templating method (interpolate) to create a nXn table containing n random cells with value 1. See this git-repo for usage of interpolate.
(function () {
String.prototype.interpolate = function (tokens) {
return interpolate(this, tokens);
};
document.querySelector("#buttons")
.addEventListener('click', createTable);
document.querySelector("#button1").click();
function createTable(evt) {
const origin = evt.target;
if ( !/button/i.test(origin.nodeName)) { return; }
const size = origin.getAttribute('data-table')
.split('x')
.reduce(function (a, b, i) {
i == 1 ? a.rows = +b : a.cols = +b; return a;
}, {} );
size.totalCells = size.rows * size.cols;
const fillCells = getUniqueRandomValues(size.cols, size.totalCells);
let cellCount = 0;
const rowCells = () => '<td{hasValue}> </td>'
.interpolate( Array(size.rows).join(",").split(",")
.map( () => {
return {
hasValue: fillCells.indexOf(cellCount++) > -1
? " class=\"hasValue\""
: ""
};
}
)
);
const rows = '<tr>{cell}</tr>'.interpolate(
Array(size.rows).join(",").split(",")
.map( () => { return { cell: rowCells() }; } )
);
const header = ('<tr><td colspan="{colsize}" class="header">' +
'{rowsize} rows, {colsize} columns</td><tr>')
.interpolate({colsize: size.cols, rowsize: size.rows});
document.querySelector("#result").innerHTML =
'<table>{rows}</table>'
.interpolate( { rows: header + rows });
}
function getUniqueRandomValues(nValues, maxRandomValue) {
let existing = {};
maxRandomValue -= 1;
const randomUnique = () => {
const rndm = Math.floor(1 + Math.random() * maxRandomValue);
const exists = existing[rndm];
if ( !exists ) { existing[rndm] = 1; }
return exists ? randomUnique() : rndm;
};
return Array(nValues).join(",").split(",")
.map( () => randomUnique() ) ;
}
function interpolate(string2Interpolate, tokens) {
if (!(tokens instanceof Array) && tokens instanceof Object) {
tokens = [tokens];
} else if (!(tokens instanceof Object)) {
return string2Interpolate;
}
let replacer = function (token) {
return function (t, t1, t2) {
return token[t2] === ''
? String.fromCharCode(0)
: token[t2] || t;
};
}
let str = string2Interpolate;
return tokens.map(function (token) {
return str.replace(/(\{?)([a-z_0-9]+)(\})/gi, replacer(token));
}).join('').replace(RegExp(String.fromCharCode(0), "g"), '');
}
}());
body { font: 12px verdana, arial; }
table { margin-top: 1em; }
table td {
text-align: right;
border: 1px solid #c0c0c0;
padding: 2px;
min-width: 1.2em;
min-height: 1.2em;}
table td.header {
background-color: black;
color: white;
text-align: center;
}
td.hasValue {
background-color: green;
color: white;
}
td.hasValue:before {
content: "1";
}
<div id="buttons">
<button id="button1" data-table="6x6">
6x6 Table
</button>
<button id="button2" data-table="8x8">
8x8 Table
</button>
<button id="button3" data-table="16x16">
16x16 Table
</button>
</div>
<div id="result"></div>

Issue with centering and coloring a grid

I'm trying to make essentially a 16x16 etch-a-sketch. I've finally created a grid, however unless I put data in it it ends up looking screwed up. I can't center the grid, nor can I get the color to evenly cover the grid.
What am I doing wrong?
(JSFiddle)
$(document).ready(function() {
$(td).hover(function() {
(this).css("background-color", "black");
});
});
table {
position: relative;
background-color: gray;
}
h1 {
padding: 1%;
background-color: red;
font-family: Cursive;
color: yellow;
width: 90%;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="theme.css">
</head>
<body>
<h1 align="center"> My Etch-a-Sketch game</h1>
<table style="width:600px;">
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
<tr>
<div class="boxes" style="width: 60px; height: 60px; border: none;">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</div>
</tr>
</table>
</body>
</html>
You cannot put <div> directly into <tr>.
$(document).ready(function() {
$('td').hover(function() {
$(this).css("background-color", "black");
});
});
table {
position: relative;
background-color: gray;
}
h1 {
padding: 1%;
background-color: red;
font-family: Cursive;
color: yellow;
width:90%;
position: relative;
}
td {
width: 60px;
height: 60px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 align="center"> My Etch-a-Sketch game</h1>
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
Mainly just syntax errors and typos.
One main thing is that div elements cannot be children of tr elements, but they were unnecessary.
$(td) should be $('td')
(this) should be $(this)
$(document).ready(function() {
$('td').hover(function() {
$(this).css("background-color", "black");
});
});
body {
margin: 0;
}
table {
background-color: gray;
width: 100vmin;
height: 100vmin;
border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
</table>
But this is how I would do it.
$(document).ready(function() {
var t = $('<table/>'), r = $('<tr/>'), x = 16, y = 16;
for(var i = 1; i <= (x * y); ++i) {
if(i % y === 0 && t.append(r)) r = $('<tr/>');
r.append($('<td/>'));
}
$('body').append(t);
$('td').hover(function() {
$(this).css("background-color", "black");
});
});
body {
margin: 0;
}
table {
background-color: gray;
width: 100vmin;
height: 100vmin;
border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories

Resources