table selection with CSS/html - javascript

i have a 5x5 grid and im using tables to do it and i am able to edit using css the first 5 the but cant do the rest.
Is there away i can change the colour of each individual cell. I need an empty square 11 black squares and 13 white squares.
I have been trying to use this but this only works up to to the td:nth-child(1)
.box tbody tr:first-child td:nth-child(1) {
width: 60px;
height: 60px;
margin: 1px;
text-align: center;
background-color: black;
font-weight: bold;
font-size: x-large;
var id_empty;
var num_moves;
var isCompleted = false;
var time=0;
var nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25];
window.addEventListener("load", startTimer, false);
function startTimer()
{
window.setInterval("updateTime()", 1000);
}
function updateTime()
{
++time;
document.getElementById("time").innerHTML ="Current Time: " +time +" (seconds)";
}
function startPuzzle() {
num_moves = 0;
isCompleted = false;
for(var i=0; i < 25; i++) {
var tmp = document.getElementById(i);
tmp.className = "cell ";
}
randomNumber = nums.sort(function () { return (Math.round(Math.random())-0.5);});
while(!Problem.prototype.is_solvable(randomNumber)) {
randomNumber = nums.sort(function () { return (Math.round(Math.random())-0.5);});
}
for(var i=0; i < 25; i++) {
var tmp = document.getElementById(i);
if(randomNumber[i] == 25) {
tmp.className = "cell empty";
tmp.innerHTML = "";
id_empty = i;
}
else
tmp.innerHTML = randomNumber[i];
}
}
function clickCell(x)
{
if(isCompleted)
return;
if(x.id != id_empty+'') {
var emptyI = Math.floor(id_empty/5);
var emptyJ = id_empty % 5;
var id_selected = Number(x.id);
var selectedI = Math.floor(id_selected/5);
var selectedJ = id_selected % 5;
if((Math.abs(emptyI - selectedI) == 1 && emptyJ == selectedJ) ||
(Math.abs(emptyJ - selectedJ) == 1 && emptyI == selectedI)) {
document.getElementById(id_empty).className = "cell";
document.getElementById(id_empty).innerHTML = x.innerHTML;
x.className = "cell empty";
x.innerHTML = '';
id_empty = id_selected;
num_moves++;
document.getElementById("moves").innerHTML = "Moves so far: " + num_moves;
if(isDone()){
isCompleted = true;
document.getElementById("moves").innerHTML = "Letter complete - Shuffle tiles" + num_moves;
}
}
}
}
<!-- is done fuction can be used for letter recognition and is for future work -->
function isDone() {
return document.getElementById('0').innerHTML == '1' &&
document.getElementById('1').innerHTML == '2' &&
document.getElementById('2').innerHTML == '3' &&
document.getElementById('3').innerHTML == '4' &&
document.getElementById('4').innerHTML == '5' &&
document.getElementById('5').innerHTML == '6' &&
document.getElementById('6').innerHTML == '7' &&
document.getElementById('7').innerHTML == '8' &&
document.getElementById('8').innerHTML == '9' &&
document.getElementById('9').innerHTML == '10' &&
document.getElementById('10').innerHTML == '11' &&
document.getElementById('11').innerHTML == '12' &&
document.getElementById('12').innerHTML == '13' &&
document.getElementById('13').innerHTML == '14' &&
document.getElementById('14').innerHTML == '15' &&
document.getElementById('15').innerHTML == '16' &&
document.getElementById('16').innerHTML == '17' &&
document.getElementById('17').innerHTML == '18' &&
document.getElementById('18').innerHTML == '19' &&
document.getElementById('19').innerHTML == '20' &&
document.getElementById('20').innerHTML == '21' &&
document.getElementById('21').innerHTML == '22' &&
document.getElementById('22').innerHTML == '23' &&
document.getElementById('23').innerHTML == '24' &&
document.getElementById('24').innerHTML == '25' ;
}
function lastClick() {
var curr_state = currentState();
var problem = new Problem(curr_state);
var sol = Solver.a_star_search(problem);
var result = "<ol>";
for(var i = 0; i < sol.length; i++) {
var n = moveNumb(sol[i],curr_state);
curr_state = problem.result(sol[i],curr_state);
result += "<li>move " + n + "</li>";
}
result += "</ol>";
document.getElementById("steps").innerHTML = result;
}
function currentState() {
var result = [];
for(var i = 0; i < 25; i++) {
var tmp = document.getElementById(String(i)).innerHTML;
if(tmp == '') {
result[i] = 25;
}
else {
result[i] = Number(tmp);
}
}
return result;
}
function moveNumb(action,state) {
var i = state.indexOf(25);
switch(action) {
case Action.up:
return state[Util.index(Util.x(i),Util.y(i) - 1)];
case Action.down:
return state[Util.index(Util.x(i),Util.y(i) + 1)];
case Action.right:
return state[Util.index(Util.x(i) + 1,Util.y(i))];
case Action.left:
return state[Util.index(Util.x(i) - 1,Util.y(i))];
}
}
Array.prototype.clone = function() { return this.slice(0); };
Array.prototype.swap = function(i1,i2) {
var copy = this.clone();
var tmp = copy[i1];
copy[i1] = copy[i2];
copy[i2] = tmp;
return copy;
};
var Problem = function(start_state) {
this.init_state = start_state;
return this;
}
Problem.prototype.is_solvable = function(start) {
start = start.clone(); start.splice(start.indexOf(25), 1);
start[24] = 25;
var count = 0;
for(var i = 0; i < 24; i++) {
if(start[i] != i+1) {
count++;
var j = start.indexOf(i+1);
start[j] = start[i];
start[i] = i+1;
}
}
return count % 2 == 0;
}
.box {
border-style: solid;
border-color: black;
border-width: 5px;
margin: 5px;
}
.cell {
width: 60px;
height: 60px;
margin: 1px;
text-align: center;
background-color: black;
font-weight: bold;
font-size: x-large;
padding: 0px;
}
.wCell {
width: 60px;
height: 60px;
margin: 1px;
text-align: center;
background-color: white;
text:white;
font: black;
font-weight: bold;
font-size: x-large;
padding: 0px;
}
.empty {
background-color: white;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<link href="style.css" rel="stylesheet" />
<script src="puzzle.js" type="text/javascript"></script>
</head>
<body onload="startPuzzle()">
<h2></h2>
<p id="moves"></p>
<p id="time"></p>
<p>
<button onclick="window.location.reload()">Shuffle Tiles</button>
</p>
<p>
</p>
<table class="box">
<tr>
<td id="0" class="wCell" onclick="clickCell(this)">1</td>
<td id="1" class="wCell" onclick="clickCell(this)">2</td>
<td id="2" class="wCell" onclick="clickCell(this)">3</td>
<td id="3" class="wCell" onclick="clickCell(this)">4</td>
<td id="4" class="wCell" onclick="clickCell(this)">5</td>
</tr>
<tr>
<td id="5" class="wCell" onclick="clickCell(this)">6</td>
<td id="6" class="wCell" onclick="clickCell(this)">7</td>
<td id="7" class="wCell" onclick="clickCell(this)">8</td>
<td id="8" class="wCell" onclick="clickCell(this)">9</td>
<td id="9" class="wCell" onclick="clickCell(this)">10</td>
</tr>
<tr>
<td id="10" class="wCell" onclick="clickCell(this)">11</td>
<td id="11" class="cell" onclick="clickCell(this)">12</td>
<td id="12" class="wcell" onclick="clickCell(this)">13</td>
<td id="13" class="wcell" onclick="clickCell(this)">14</td>
<td id="14" class="cell" onclick="clickCell(this)">15</td>
</tr>
<tr>
<td id="15" class="cell" onclick="clickCell(this)">16</td>
<td id="16" class="cell" onclick="clickCell(this)">17</td>
<td id="17" class="cell" onclick="clickCell(this)">18</td>
<td id="18" class="cell" onclick="clickCell(this)">19</td>
<td id="19" class="cell" onclick="clickCell(this)">20</td>
</tr>
<tr>
<td id="20" class="cell" onclick="clickCell(this)">21</td>
<td id="21" class="cell" onclick="clickCell(this)">22</td>
<td id="22" class="cell" onclick="clickCell(this)">23</td>
<td id="23" class="cell" onclick="clickCell(this)">24</td>
<td id="24" class="cell" onclick="clickCell(this)">25</td>
</tr>
</table>
</body>
</html>

Hi your every cell has different id you can use the id to colour each cell differently.
#12{ background: green;}

In this Snippet:
Every <td> is collected into an array
Next an array of 25 strings representing 11 black, 13 white, and 1 transparent is shuffled.
Then the newly shuffled array of colors and the array of <td>s are merged by .map() method.
As the 2 arrays are being merged, each pair is ran through a switch. This switch will color each <td> background.
A new array is returned comprising of the colored pattern the table is displaying.
SNIPPET
var x = 0,
y = 0,
temp = null;
// Collect every <td> into an array
const tiles = Array.from(document.querySelectorAll('td'));
const colors = ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 'w', 't'];
// Fisher-Yates Shuffle
for (x = colors.length - 1; x > 0; x -= 1) {
y = Math.floor(Math.random() * (x + 1));
temp = colors[x];
colors[x] = colors[y];
colors[y] = temp;
}
console.log(colors);
// Map() both arrays into one
const mixArray = tiles.map(function(cell, idx) {
[cell, colors[idx]];
var cc = colors[idx];
// Determine tile color
switch (cc) {
case 'b':
cell.style.backgroundColor = 'black';
break;
case 'w':
cell.style.backgroundColor = 'white';
break;
case 't':
cell.style.backgroundColor = 'transparent';
break;
}
return cell;
});
console.log(mixArray);
table { border:1px solid grey; table-layout:fixed;}
tbody {background:#555;}
td {border:1px solid red; width:50px;height:50px;}
<table>
<tbody>
<tr class='A'>
<td class='A1'> </td>
<td class='A2'> </td>
<td class='A3'> </td>
<td class='A4'> </td>
<td class='A5'> </td>
</tr>
<tr class='B'>
<td class='B1'> </td>
<td class='B2'> </td>
<td class='B3'> </td>
<td class='B4'> </td>
<td class='B5'> </td>
</tr>
<tr class='C'>
<td class='C1'> </td>
<td class='C2'> </td>
<td class='C3'> </td>
<td class='C4'> </td>
<td class='C5'> </td>
</tr>
<tr class='D'>
<td class='D1'> </td>
<td class='D2'> </td>
<td class='D3'> </td>
<td class='D4'> </td>
<td class='D5'> </td>
</tr>
<tr class='E'>
<td class='E1'> </td>
<td class='E2'> </td>
<td class='E3'> </td>
<td class='E4'> </td>
<td class='E5'> </td>
</tr>
</tbody>
</table>

Related

Getting an Uncaught TypeError that is preventing a score alert that I'm unsure how to fix even though my game plays as normal

So with my Yahtzee code, my game plays normally, but I am unable to get my alert for the total score and the alert that you received bonus points. I've discovered where the issues are I'm just unsure as to how to fix it. I tried debugging through alerts and from what I can gather it seems like the dice rolls aren't adding together to make the total unless my assumption is wrong.
Error I am Receiving
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Yahtzee</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<style>
........
</style>
<script>
.......
</script>
</head>
<body style="background-color: black;" onload="getUser()">
<div class="container">
<header id="pageHeader">
<h1> <img src="yahtzee.jpg" width="100px"> YAHTZEE </h1>
</header>
<ul class="nav nav-pills red">
<li class="active"> Color Scheme </li>
</ul>
<br>
<div class="container">
<div class="row">
<div class="col-sm">
<table>
<br>
<span style="color: white"> Player Name: </span>
<span style="color: white" id="player"> </span>
<br>
<span style="color:white;"> <strong> SCORE BOARD </strong> </span>
<br>
<tr>
<th> Win Points </th>
<th> 200</th>
</tr>
<tr>
<td> Wins </td>
<td> 0 </td>
</tr>
<tr>
<td> Losses </td>
<td> 0 </td>
</tr>
</table>
</div>
<div class="col-4">
<table class="table table-bordered border-dark border border-2 table-md">
<tr>
<th>Upper Section</th>
<th>How to Score</th>
<th>Game #1</th>
</tr>
<tr>
<td> ACE <img src="Die1.PNG" width="45px"> = 1 </td>
<td> COUNT AND ADD ONLY ACES </td>
<td><div id="aces1"></div></td>
</tr>
<tr>
<td> TWOS <img src="Die2.PNG" width="45px"> = 2 </td>
<td> COUNT AND ADD ONLY TWOS </td>
<td><div id="twos1"></div></td>
</tr>
<tr>
<td> THREES <img src="Die3.PNG" width="45px"> = 3</td>
<td> COUNT AND ADD ONLY THREES</td>
<td><div id="threes1"></div></td>
</tr>
<tr>
<td> FOURS <img src="Die4.PNG" width="45px"> = 4 </td>
<td> COUNT AND ADD ONLY FOURS </td>
<td><div id="fours1"></div></td>
</tr>
<tr>
<td> FIVES <img src="Die5.PNG" width="45px"> = 5</td>
<td>COUNT AND ADD ONLY FIVES</td>
<td><div id="fives1"></div></td>
</tr>
<tr>
<td> SIXES <img src="Die6.PNG" width="45px"> = 6 </td>
<td> COUNT AND ADD ONLY SIXES </td>
<td><div id="sixes1"></div></td>
</tr>
<tr>
<td> 3 OF A KIND </td>
<td> ADD TOTAL OF ALL DICE </td>
<td></td>
</tr>
<tr>
<td> 4 OF A KIND </td>
<td> ADD TOTAL OF ALL DICE </td>
<td></td>
</tr>
<tr>
<td> FULL HOUSE </td>
<td> SCORE 25 </td>
<td></td>
</tr>
<tr>
<td style="font-size: 30px"> TOTAL SCORE </td>
<td> <img src="whitearrow.png" width="100px" > </td>
<td></td>
</tr>
<tr>
<td style="font-size: 30px"> BONUS w/ total score </td>
<td style="font-size: 30px"> SCORE 35 </td>
<td></td>
</tr>
<tr>
<td style="font-size: 30px"> TOTAL </td>
<td> <img src="whitearrow.png" width="100px" > </td>
<td></td>
</tr>
</table>
</div>
<div id="yourRoll" class="col-sm">
<h2 style="color: white"> Your Roll </h2>
<div id="die1">
<img src="Die1.PNG" width="45px">
</div>
Die 1 <input type="checkbox" name="options" id="cdie1" />
<div id="die2">
<img src="Die2.PNG" width="45px">
</div>
Die 2 <input type="checkbox" name="options" id="cdie2" />
<div id="die3">
<img src="Die3.PNG" width="45px">
</div>
Die 3 <input type="checkbox" name="options" id="cdie3" />
<div id="die4">
<img src="Die4.PNG" width="45px">
</div>
Die 4 <input type="checkbox" name="options" id="cdie4" />
<div id="die5">
<img src="Die5.PNG" width="45px">
</div>
Die 5 <input type="checkbox" name="options" id="cdie5" />
<div id="die6">
<img src="Die6.PNG" width="45px">
</div>
Die 6 <input type="checkbox" name="options" id="cdie6" />
<br>
<div>
</br>
<p> Rolls Left: <span id="rollsRem"> 2 </span> Turns Left: <span id='turnsLeft'> 5 </span> </p>
</br>
<button type="button" id="rollbutt" onclick="roll();" style="color: black"> Roll Button </button>
</br>
<button style="color: black" type="button" id="reset"> Reset </button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
body {
display: grid;
grid-template-areas:
"header";
}
#pageHeader {
grid-area: header;
}
header {
background: black;
}
header h1 {
font-family: Verdana;
font-size: 32px;
color: white;
}
.nav-pills > li.active > a, .nav-pills > li.active > a:focus {
color: black;
background-color: #f80000;
}
.nav-pills > li.active > a:hover {
background-color: #f80000;
color:black;
}
th, td {
border-style:solid;
border-color: white;
font-family: "Arial Rounded MT Bold";
font-weight: bolder;
border-width: 2px;
color: white;
}
#scoreCard {
right: 500px;
top: 150px;
border-style:solid;
border-color: black;
font-family: "Arial Rounded MT Bold";
font-weight: bolder;
width: 300px;
}
#yourRoll {
color: white;
}
div h2 img {
color: white;
float: right;
padding-right: 150px;
}
let dice = [
{'img':"Die1.PNG", 'value': 1},
{'img':"Die2.PNG", 'value': 2},
{'img':"Die3.PNG", 'value': 3},
{'img':"Die4.PNG", 'value': 4},
{'img':"Die5.PNG", 'value': 5},
{'img':"Die6.PNG", 'value': 6}
]
let checkedDice = [
{'dice':0, 'checked': false, 'id' : "die1"},
{'dice':0, 'checked': false, 'id' : "die2"},
{'dice':0, 'checked': false, 'id' : "die3"},
{'dice':0, 'checked': false, 'id' : "die4"},
{'dice':0, 'checked': false, 'id' : "die5"},
{'dice':0, 'checked': false, 'id' : "die6"},
]
let scoreCard = [
{'num' : 1, 'value' : 0, 'area' : "aces1"},
{'num' : 2, 'value' : 0, 'area' : "twos1"},
{'num' : 3, 'value' : 0, 'area' : "threes1"},
{'num' : 4, 'value' : 0, 'area' : "fours1"},
{'num' : 5, 'value' : 0, 'area' : "fives1"},
{'num' : 6, 'value' : 0, 'area' : "sixes1"},
]
var turns = 5;
var savedValue = 0;
var keeper = 0;
var rollsRem = 3;
var wins =0;
var losses = 0;
const winPoints = 200;
function getUser()
{
document.getElementById("player").innerHTML = prompt(" Please Enter your name: ");
}
// Function that will roll dice
function roll() {
if (rollsRem > 0) {
for (let i = 0; i < checkedDice.length; i++) {
if (checkedDice[i].checked == false) {
let rollDice = Math.floor(Math.random() * 6);
document.getElementById(checkedDice[i].id).innerHTML = `<img src="${dice[rollDice].img}" width='45px'>`;
checkedDice[i].value = dice[rollDice].value;
}
}
rollsRem--;
var display = document.getElementById("rollsRem");
display.innerHTML = rollsRem;
} else {
nextRound();
for(let j = 0; j < checkedDice.length; j++)
{
checkedDice[j].checked = false;
//rollsRem = 4;
}
}
}
$( document ).ready(function() {
reset();
function reset() {
roll();
}
$("#reset").click(function () {
alert("reset this");
rollsRem = 3;
var display = document.getElementById("rollsRem");
display.innerHTML = rollsRem;
roll();
$('input[type=checkbox]:checked').each(function () {
$(this).prop('checked', false);
});
$('input[type=checkbox]:checked').each(function () {
$(this).prop('value', 0);
});
turns--;
document.getElementById("turnsLeft").innerHTML = `${turns}`;
})
$("#cdie1").click(function () {
if (checkedDice[0].checked) {
checkedDice[0].checked = false;
} else {
checkedDice[0].checked = true;
}
})
$("#cdie2").click(function () {
if (checkedDice[1].checked) {
checkedDice[1].checked = false;
} else {
checkedDice[1].checked = true;
}
})
$("#cdie3").click(function () {
if (checkedDice[2].checked) {
checkedDice[2].checked = false;
} else {
checkedDice[2].checked = true;
}
})
$("#cdie4").click(function () {
if (checkedDice[3].checked) {
checkedDice[3].checked = false;
} else {
checkedDice[3].checked = true;
}
})
$("#cdie5").click(function () {
if (checkedDice[4].checked) {
checkedDice[4].checked = false;
} else {
checkedDice[4].checked = true;
}
})
$("#cdie6").click(function () {
if (checkedDice[5].checked) {
checkedDice[5].checked = false;
} else {
checkedDice[5].checked = true;
}
})
});
// Adds points into the scorecard, provides total score, as well as enters the next turn
// function nextRound() {
// let keeper;
// let sumRound = 0;
// let totalSum = 0;
// let bonus = 35;
//
// if (turns > 0) {
//
// keeper = prompt("Which Numbers Would You Want to keep?: ")
//
// for (let i = 0; i < checkedDice.length; i++) {
// if (checkedDice[i].value == keeper) {
// sumRound += checkedDice[i].value
// }
// }
// scoreCard[keeper - 1].value = sumRound;
//
// document.getElementById(scoreCard[keeper - 1].area).innerHTML = sumRound.toString();
// // alert("Did it make it here?")
//
// } else {
// // alert("In the else?")
// keeper = prompt("Choose which die to keep ");
//
// for(let i = 0; i < checkedDice.length; i++){
// if(checkedDice[i].value == keeper){
// sumRound += checkedDice[i].value;
// }
// }
// //alert("around here?")
// scoreCard[keeper-1].value = sumRound;
// document.getElementById(scoreCard[keeper-1].area).innerHTML = sumRound.toString();
//
// for(let j = 0; j < checkedDice.length+1; j++){
// //alert("maybe here?")
// totalSum += scoreCard[j].value;
// }
//
// document.getElementById("sum1").innerHTML = totalSum.toString();
// // alert("Here?")
// if(totalSum > 62){
// totalSum += bonus;
// alert("You get a bonus for more than 63 points!")
// document.getElementById("bonus1").innerHTML = bonus.toString();
// document.getElementById("sum1").innerHTML = totalSum.toString();
// }
// else {
// document.getElementById("bonus1").innerHTML = "0";
// }
//
// alert("Game Over. Score is " + totalSum)
//
// }
// }
function nextRound(){
let keep = 0;
let totalSum= 0;
let roundSum = 0;
let bonus = 35;
if (turns > 0) {
keep = prompt("What number do you wish to keep? ");
for (let i = 0; i < checkedDice.length; i++) {
if (checkedDice[i].value == keep) {
roundSum += checkedDice[i].value
}
}
scoreCard[keep - 1].value = roundSum;
document.getElementById(scoreCard[keep - 1].area).innerHTML = roundSum.toString();
}
else
{
keep = prompt("What number do you wish to keep? ");
for (let i = 0; i < checkedDice.length; i++) {
if (checkedDice[i].value == keep) {
roundSum += checkedDice[i].value
}
}
scoreCard[keep - 1].value = roundSum;
document.getElementById(scoreCard[keep - 1].area).innerHTML = roundSum.toString();
for (let j = 0; j < checkedDice.length + 1; j++)
{
totalSum += scoreCard[j].value;
}
document.getElementById("total1").innerHTML = totalSum.toString();
if (totalSum > 62)
{
totalSum += bonus;
alert("You get a bonus!!")
document.getElementById("bonus1").innerHTML = bonus.toString();
document.getElementById("total1").innerHTML = totalSum.toString();
}
else
{
document.getElementById("bonus1").innerHTML = "0";
}
alert("Game is over. You achieved a score of " + totalSum + "!");
alert("game over")
}
}
This is your definition/initialization for the checkedDice array
let checkedDice = [
{'dice':0, 'checked': false, 'id' : "die1"},
{'dice':0, 'checked': false, 'id' : "die2"},
{'dice':0, 'checked': false, 'id' : "die3"},
{'dice':0, 'checked': false, 'id' : "die4"},
{'dice':0, 'checked': false, 'id' : "die5"},
{'dice':0, 'checked': false, 'id' : "die6"},
]
Notice that none of the objects in the array has a "value" property
The only place I see that the value property can be created/set is in the roll function
if (checkedDice[i].checked == false) {
let rollDice = Math.floor(Math.random() * 6);
document.getElementById(checkedDice[i].id).innerHTML = `<img src="${dice[rollDice].img}" width='45px'>`;
checkedDice[i].value = dice[rollDice].value;
}
But, its theoretically possible to have object that never gets a value property added beacuse in that function, the line that sets the .value property is buried within an IF block. So, if whenever roll runs there is an object in checkedDice that has never had .checked == false, then that object never gets a .value property created and you end up getting the typeof error because that property is undefined when you try to reference it in later IF statements
Easy fix is to add the value property with an initial value to each object in the checkedDice array when it is initialized.

Javascript Interval continues endless without conditions met

var counter;
var count = 0;
var equalsPressed = false;
var dritter = false;
var array = new Array();
window.onload = function() {
let x = document.getElementsByClassName('zahlen')
let i;
for (i = 0; i < x.length; i++) {
let y = x[i];
x[i].addEventListener('mousedown', function() {
add(this.className, this.value.replace(/\s/g, ''));
}, true);
//x[i].addEventListener(mousedown,function('Hi')
x[i].onmousedown = debounce(function() {
start(y.className, y.value.replace(/\s/g, ''));
}, 200);
}
}
function debounce(a, b) {
return function() {
let timer;
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
function start(clicked_className, Zeichen) {
counter = setInterval(function() {
add(clicked_className, Zeichen);
count++;
}, 370);
}
function end() {
booli = false;
clearInterval(counter);
}
function Check(Eingabe) {
// indexof=suche in "0123456789[]()-+*%/" nach den chars der eingabe(0 bis 1 kleiner als länge (also alle)) und schaue an welcher position im string diese sind.wenn position kleiner0(also nicht vorhanden)
// dann return false, ansonsten alles gut
var inhalt = "0123456789[]().-+*%/=e";
for (var i = 0; i < Eingabe.length; i++)
if (inhalt.indexOf(Eingabe.charAt(i)) < 0) return false;
return true;
}
function Ergebnis() {
var z = document.getElementById("Historie");
z.style.display = "block";
var ausg = 0;
if (equalsPressed && Check(window.document.Rechner.Display.value)) {
var o = window.document.Rechner.Display2.value;
var p = window.document.Rechner.Display.value;
p = p.replace("=", '');
const chars = ["+", "-", "*", "/"];
var last;
for (const rechenarten of o) {
if (chars.includes(rechenarten)) {
last = rechenarten;
}
}
//lastIndexOf zählt von hinten und fängt bei o.length - 1 also der letzten Position an
//und sucht last, also die am weitesten hinten vorkommende der Rechenarten
o = o.slice(o.lastIndexOf(last, o.length - 1), o.lenght);
ausg = eval(p + o);
ausg = ausg.toFixed(getDecimalPlaces(p));
window.document.Rechner.Display.value = ausg;
window.document.Rechner.Display2.value = window.document.Rechner.Display2.value + o;
dritter = true;
} else {
var y = 0;
var x = 0;
if (Check(window.document.Rechner.Display.value))
y = window.document.Rechner.Display.value;
window.document.Rechner.Display2.value = y;
ausg = eval(window.document.Rechner.Display.value);
ausg = ausg.toFixed(getDecimalPlaces(y)); //
window.document.Rechner.Display.value = "=" + ausg;
}
}
function getDecimalPlaces(numb) {
var highest = 0;
var counter = 0;
for (a = 0; a < numb.length; a++) {
if (numb.charAt(a - 1) == ".") {
do {
counter++;
a++;
}
while (!isNaN(numb.charAt(a)) && a < numb.length);
}
if (counter > highest) {
highest = counter;
}
counter = 0;
}
return highest;
}
function add(clicked_className, Zeichen) {
if (equalsPressed == false && clicked_className == 'zahlen') {
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
} else if (dritter && equalsPressed && clicked_className == 'zahlen') {
var array = new Array();
array.push(window.document.Rechner.Display2.value + "=" +
window.document.Rechner.Display.value);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (equalsPressed && clicked_className == 'zahlen') {
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (clicked_className == 'ops') {
var x;
window.document.Rechner.Display.value = window.document.Rechner.Display.value.replace("=", '');
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
}
}
function gleichPressed() {
equalsPressed = true;
}
function backspace() {
var abschneiden = window.document.Rechner.Display.value;
for (var i = 0; i < abschneiden.length; i++) {
var output = abschneiden.slice(0, -1);
window.document.Rechner.Display.value = output;
}
}
function ausgabe() {
if (equalsPressed) {
} else {
array.push(window.document.Rechner.Display2.value +
window.document.Rechner.Display.value);
console.log(array);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
}
}
body {
font-family: "Century Gothic", CenturyGothic, Geneva, AppleGothic, sans-serif;
}
.button,
.ops,
.zahlen,
.sonst,
.istgleich {
background-color: #A4A4A4;
background: linear-gradient(240deg, grey, white);
color: black;
width: 60px;
text-align: center;
font-family: System, sans-serif;
font-size: 100%;
}
.button:hover,
.zahlen:hover,
.sonst:hover,
.ops:hover,
.istgleich:hover {
color: #2E2E2E;
background-color: #FAFAFA;
background: linear-gradient(30deg, darkgrey, lightgrey, grey);
;
}
.display {
width: 100%;
text-align: right;
font-family: System, sans-serif;
font-size: 100%;
}
#Historie {
background: linear-gradient(30deg, silver, white, grey);
;
border: 5px outset;
float: left;
text-align: right;
}
#eins {
background: linear-gradient(30deg, silver, grey, DimGray);
;
}
#zwei {
background: linear-gradient(90deg, silver, grey);
;
}
#tabelle {
width: 300px;
height: 235px;
float: left;
}
<html onmouseup="end()">
<head>
<meta charset="UTF-8">
<title>Taschenrechner</title>
</head>
<body bgcolor="#FFFFE0" text="#000000">
<form name="Rechner" action="" onSubmit="Ergebnis();return false;">
<table id="tabelle" style="float:left" border="7" cellpadding="12" cellspacing="0">
<tr>
<td id="eins">
<input type="text" name="Display2" class="display" readonly>
<input type="text" name="Display" class="display" readonly></td>
</tr>
<tr>
<td id="zwei">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td><input type="button" class="zahlen" value=" 7 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 8 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 9 " onmouseleave="end()">
</td>
<td><input type="button" class="sonst" value=" &#171 " onClick="backspace()">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 4 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 5 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 6 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" + " onClick="add(this.className,'+')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 1 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 2 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 3 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" - " onClick="add(this.className,'-')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" . ">
</td>
<td><input type="button" class="zahlen" value=" 0 " onmouseleave="end()">
</td>
<td><input type="button" class="istgleich" value=" = " onClick="Ergebnis();ausgabe();gleichPressed()">
</td>
<td><input type="button" class="ops" value=" * " onClick="add(this.className,'*')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" ( ">
</td>
<td><input type="button" class="zahlen" value=" ) ">
</td>
<td><input type="reset" class="button" value=" C ">
</td>
<td><input type="button" class="ops" value=" / " onClick="add(this.className,'/')">
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<div class="Historie" id="Historie" hidden="true">
</div>
</body>
</html>
Instruction___: doubleclick and hold
Im really really helpless in finding that bug tried to find where it originates, and build in couple of booleans so the loop only runs if theyre true but they were all false and it still continued running.
Im looking for a solution or a good way to adress the problem:(
What i found very noteworthy is that it only occurs when doing the needed keypresses fast, if done slower it doesnt result in that bug, also when done multiple times, it loops multiple times.
Just like Bergi said, your debounce function is broken. You need to initialize the timer variable outside the returned function.
This is your implementation:
function debounce(a, b) {
return function() {
let timer;
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
And this is how you fix your bug:
function debounce(a, b) {
let timer;
return function() {
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
var counter;
var count = 0;
var equalsPressed = false;
var dritter = false;
var array = new Array();
window.onload = function() {
let x = document.getElementsByClassName('zahlen')
let i;
for (i = 0; i < x.length; i++) {
let y = x[i];
x[i].addEventListener('mousedown', function() {
add(this.className, this.value.replace(/\s/g, ''));
}, true);
//x[i].addEventListener(mousedown,function('Hi')
x[i].onmousedown = debounce(function() {
start(y.className, y.value.replace(/\s/g, ''));
}, 200);
}
}
function debounce(a, b) {
let timer;
return function() {
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if (booli) {
a();
} else {
clearInterval(counter);
}
}, b);
};
}
function start(clicked_className, Zeichen) {
counter = setInterval(function() {
add(clicked_className, Zeichen);
count++;
}, 370);
}
function end() {
booli = false;
clearInterval(counter);
}
function Check(Eingabe) {
// indexof=suche in "0123456789[]()-+*%/" nach den chars der eingabe(0 bis 1 kleiner als länge (also alle)) und schaue an welcher position im string diese sind.wenn position kleiner0(also nicht vorhanden)
// dann return false, ansonsten alles gut
var inhalt = "0123456789[]().-+*%/=e";
for (var i = 0; i < Eingabe.length; i++)
if (inhalt.indexOf(Eingabe.charAt(i)) < 0) return false;
return true;
}
function Ergebnis() {
var z = document.getElementById("Historie");
z.style.display = "block";
var ausg = 0;
if (equalsPressed && Check(window.document.Rechner.Display.value)) {
var o = window.document.Rechner.Display2.value;
var p = window.document.Rechner.Display.value;
p = p.replace("=", '');
const chars = ["+", "-", "*", "/"];
var last;
for (const rechenarten of o) {
if (chars.includes(rechenarten)) {
last = rechenarten;
}
}
//lastIndexOf zählt von hinten und fängt bei o.length - 1 also der letzten Position an
//und sucht last, also die am weitesten hinten vorkommende der Rechenarten
o = o.slice(o.lastIndexOf(last, o.length - 1), o.lenght);
ausg = eval(p + o);
ausg = ausg.toFixed(getDecimalPlaces(p));
window.document.Rechner.Display.value = ausg;
window.document.Rechner.Display2.value = window.document.Rechner.Display2.value + o;
dritter = true;
} else {
var y = 0;
var x = 0;
if (Check(window.document.Rechner.Display.value))
y = window.document.Rechner.Display.value;
window.document.Rechner.Display2.value = y;
ausg = eval(window.document.Rechner.Display.value);
ausg = ausg.toFixed(getDecimalPlaces(y)); //
window.document.Rechner.Display.value = "=" + ausg;
}
}
function getDecimalPlaces(numb) {
var highest = 0;
var counter = 0;
for (a = 0; a < numb.length; a++) {
if (numb.charAt(a - 1) == ".") {
do {
counter++;
a++;
}
while (!isNaN(numb.charAt(a)) && a < numb.length);
}
if (counter > highest) {
highest = counter;
}
counter = 0;
}
return highest;
}
function add(clicked_className, Zeichen) {
if (equalsPressed == false && clicked_className == 'zahlen') {
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
} else if (dritter && equalsPressed && clicked_className == 'zahlen') {
var array = new Array();
array.push(window.document.Rechner.Display2.value + "=" +
window.document.Rechner.Display.value);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (equalsPressed && clicked_className == 'zahlen') {
window.document.Rechner.Display2.value = "";
window.document.Rechner.Display.value = "";
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
} else if (clicked_className == 'ops') {
var x;
window.document.Rechner.Display.value = window.document.Rechner.Display.value.replace("=", '');
window.document.Rechner.Display.value =
window.document.Rechner.Display.value + Zeichen;
equalsPressed = false;
}
}
function gleichPressed() {
equalsPressed = true;
}
function backspace() {
var abschneiden = window.document.Rechner.Display.value;
for (var i = 0; i < abschneiden.length; i++) {
var output = abschneiden.slice(0, -1);
window.document.Rechner.Display.value = output;
}
}
function ausgabe() {
if (equalsPressed) {
} else {
array.push(window.document.Rechner.Display2.value +
window.document.Rechner.Display.value);
console.log(array);
var myTableDiv = document.getElementById("Historie")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '0';
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD')
td.width = '275';
td.style.textAlign = "right";
td.appendChild(document.createTextNode(array[0]));
tr.appendChild(td);
myTableDiv.appendChild(table)
}
}
body {
font-family: "Century Gothic", CenturyGothic, Geneva, AppleGothic, sans-serif;
}
.button,
.ops,
.zahlen,
.sonst,
.istgleich {
background-color: #A4A4A4;
background: linear-gradient(240deg, grey, white);
color: black;
width: 60px;
text-align: center;
font-family: System, sans-serif;
font-size: 100%;
}
.button:hover,
.zahlen:hover,
.sonst:hover,
.ops:hover,
.istgleich:hover {
color: #2E2E2E;
background-color: #FAFAFA;
background: linear-gradient(30deg, darkgrey, lightgrey, grey);
;
}
.display {
width: 100%;
text-align: right;
font-family: System, sans-serif;
font-size: 100%;
}
#Historie {
background: linear-gradient(30deg, silver, white, grey);
;
border: 5px outset;
float: left;
text-align: right;
}
#eins {
background: linear-gradient(30deg, silver, grey, DimGray);
;
}
#zwei {
background: linear-gradient(90deg, silver, grey);
;
}
#tabelle {
width: 300px;
height: 235px;
float: left;
}
<html onmouseup="end()">
<head>
<meta charset="UTF-8">
<title>Taschenrechner</title>
</head>
<body bgcolor="#FFFFE0" text="#000000">
<form name="Rechner" action="" onSubmit="Ergebnis();return false;">
<table id="tabelle" style="float:left" border="7" cellpadding="12" cellspacing="0">
<tr>
<td id="eins">
<input type="text" name="Display2" class="display" readonly>
<input type="text" name="Display" class="display" readonly></td>
</tr>
<tr>
<td id="zwei">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td><input type="button" class="zahlen" value=" 7 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 8 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 9 " onmouseleave="end()">
</td>
<td><input type="button" class="sonst" value=" &#171 " onClick="backspace()">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 4 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 5 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 6 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" + " onClick="add(this.className,'+')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" 1 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 2 " onmouseleave="end()">
</td>
<td><input type="button" class="zahlen" value=" 3 " onmouseleave="end()">
</td>
<td><input type="button" class="ops" value=" - " onClick="add(this.className,'-')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" . ">
</td>
<td><input type="button" class="zahlen" value=" 0 " onmouseleave="end()">
</td>
<td><input type="button" class="istgleich" value=" = " onClick="Ergebnis();ausgabe();gleichPressed()">
</td>
<td><input type="button" class="ops" value=" * " onClick="add(this.className,'*')">
</td>
</tr>
<tr>
<td><input type="button" class="zahlen" value=" ( ">
</td>
<td><input type="button" class="zahlen" value=" ) ">
</td>
<td><input type="reset" class="button" value=" C ">
</td>
<td><input type="button" class="ops" value=" / " onClick="add(this.className,'/')">
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<div class="Historie" id="Historie" hidden="true">
</div>
</body>
</html>

Change Which Table Row Background Color Based on Time of Day

I try to adjust this code not only for hours but for minutes. But I'm wrong somewhere. Can you tell me where, please?
checkUpdateColors = function() {
var d = new Date();
var hourCompare = d.getHours();
var minsCompare = d.getMinutes();
if ((hourCompare = 7 && minsCompare >= 30) | (hourCompare = 8 minsCompare < 10)) {
$('#r1').css("background-color", "ceeca5");
if (hourCompare = 11 && minsCompare >= 0 && minsCompare < 40) {
$('#r9').css("background-color", "blue");
} else {
$('#r1').css("background-color", "blue");
$('#r2').css("background-color", "red");
}
}();
setInterval(function() {
checkUpdateColors();
}, 3000);
This is the whole code:
<style>
table, th, td {
color: black;
background-color: white;
text-align: center;
border: 2px solid black;
border-collapse: collapse;
font-size: 16px;
margin: auto;
padding: 5px;
}
td:nth-child(1) {
width: 20px;
}
td:nth-child(2) {
width: 160px;
}
</style>
<script type="text/javascript">
checkUpdateColors = function() {
var d = new Date();
var hourCompare = d.getHours();
var minsCompare = d.getMinutes();
if ((hourCompare = 7 && minsCompare >= 30) | (hourCompare = 8 minsCompare < 10)) {
$('#r1').css("background-color", "ceeca5");
if (hourCompare = 11 && minsCompare >= 0 && minsCompare < 40) {
$('#r9').css("background-color", "blue");
} else {
$('#r1').css("background-color", "blue");
$('#r2').css("background-color", "red");
}
}();
setInterval(function() {
checkUpdateColors();
}, 3000);
</script>
<div class="table">
<table class="schedule">
<tr> <th width="200" colspan="2">I СМЯНА</th> </tr>
<tr> <td id="r1">1</td><td>7:30 - 8:10</td> </tr>
<tr> <td id="r2" colspan="2">Междучасие</td> </tr>
<tr> <td id="r3">2</td><td>8:20 - 9:00</td> </tr>
<tr> <td id="r4" colspan="2">Междучасие</td> </tr>
<tr> <td id="r5">3</td><td>9:20 - 10:00</td> </tr>
<tr> <td id="r6" colspan="2">Междучасие</td> </tr>
<tr> <td id="r7">4</td><td>10:10 - 10:50</td> </tr>
<tr> <td id="r8" colspan="2">Междучасие</td> </tr>
<tr> <td id="r9">5</td><td>11:00 - 11:40</td> </tr>
<tr> <td id="r10" colspan="2">Междучасие</td> </tr>
<tr> <td id="r11">6</td><td>11:50 - 12:30</td> </tr>
<tr> <td id="r12" colspan="2">Междучасие</td> </tr>
<tr> <td id="r13">7</td><td>12:40 - 13:20</td> </tr>
<tr> <td id="r14" colspan="2">Междучасие</td> </tr>
<tr> <td id="r15">8</td><td>1:15 - 2:01</td> </tr>
</table>
</div>
I uploaded the code: http://jsfiddle.net/6h7u434j/.
try this java script code :
<script type="text/javascript">
function checkUpdateColors() {
var d = new Date();
var hourCompare = d.getHours();
var minsCompare = d.getMinutes();
if ((hourCompare == 7 && minsCompare >= 30) || (hourCompare == 8 && minsCompare < 10)) {
$('#r1').css("background-color", "ceeca5");
if (hourCompare = 11 && minsCompare >= 0 && minsCompare < 40) {
$('#r9').css("background-color", "blue");
}
else {
$('#r1').css("background-color", "blue");
$('#r2').css("background-color", "red");
}
}
}
setInterval(function() { checkUpdateColors(); }, 3000);
</script>

Indicator error in tic tac toe javascript

I am having problem based on the indicator created in my tic tac toe javascript codes. can you help me solve it?
cell.indicator = indicator;
the console mentioned this
Uncaught TypeError: Cannot set property 'indicator' of null
at onload (javascript.js:54)
here are the codings.
var squares =[];
var EMPTY = '\xA0'
var score;
var moves;
var turn = 'X';
var wins = [ 119, 8064, 516096, 17930144, 2113929216, (1.352914698*10^10),
2181570690, 4363141380,8726282760,(1.745256552*10^10), (3.490513104*10^10),
(6.981026208*10^10),(96.926057496*10^10), 2216757312];
var startNewGame = function (){
turn = 'X';
score = {'X': 0 , 'O': 0};
moves =0;
for (var i = 0; i < squares.length; i += 1){
squares[i].firstChild.nodeValue = EMPTY;
}
};
var win = function (score){
for (var i = 0; i < wins.length; i++){
if ((wins[i] & score) == wins[i]){
}
}
return false;
};
var set = function(){
if (this.firstChild.nodeValue !== EMPTY){
return;
}
this.firstChild.nodeValue = turn;
moves += 1;
score[turn] += this.indicator;
if (win(score[turn])){
alert(turn + "wins!");
startNewGame();
}
else if (moves === 36){
alert("Beemo\u2019s game!");
startNewGame();
}
else {
turn = turn === 'X' ? 'O' : 'X';
}
};
onload = function(){
var indicator = 1;
for (var i = 0; i < 6; i++){
for (var j = 0; j < 6; j++){
var cell = document.getElementById("cell" + i + j);
cell.indicator = indicator;
cell.onclick = set;
cell.appendChild(document.createTextNode(''));
squares.push(cell);
indicator += indicator;
}
}
startNewGame();
};
here's the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>ULTIMATE TIC TAC TOE</title>
<script src="javascript.js"></script>
<style type="text/css">
h1{
text-align: center;
}
table{
border: outset 1px rgb(200, 200, 200)
}
td{
width: 50px;
height: 50px;
vertical-align: middle;
border: inset 1px rgb(200,200,200)
}
tr{
text-align: center;
}
</style>
</head>
<body>
<h1>Tic Tac Toe</h1>
<table align="center">
<tr>
<td id cell="cell00"></td>
<td id cell="cell01"></td>
<td id cell="cell02"></td>
<td id cell="cell03"></td>
<td id cell="cell04"></td>
<td id cell="cell05"></td>
</tr>
<tr>
<td id cell="cell10"></td>
<td id cell="cell11"></td>
<td id cell="cell12"></td>
<td id cell="cell13"></td>
<td id cell="cell14"></td>
<td id cell="cell15"></td>
</tr>
<tr>
<td id cell="cell20"></td>
<td id cell="cell21"></td>
<td id cell="cell22"></td>
<td id cell="cell23"></td>
<td id cell="cell24"></td>
<td id cell="cell25"></td>
</tr>
<tr>
<td id cell="cell30"></td>
<td id cell="cell31"></td>
<td id cell="cell32"></td>
<td id cell="cell33"></td>
<td id cell="cell34"></td>
<td id cell="cell35"></td>
</tr>
<tr>
<td id cell="cell40"></td>
<td id cell="cell41"></td>
<td id cell="cell42"></td>
<td id cell="cell43"></td>
<td id cell="cell44"></td>
<td id cell="cell45"></td>
</tr>
<tr>
<td id cell="cell50"></td>
<td id cell="cell51"></td>
<td id cell="cell52"></td>
<td id cell="cell53"></td>
<td id cell="cell54"></td>
<td id cell="cell55"></td>
</tr>
</table>
</body>
</html>
The cells you're looking for cannot be found because all of their id attributes are empty, so document.getElementById("cell" + i + j) returns nothing. Change to <td id="cellxx"> and you'll be fine.
Then you will probably find that an HTML element doesn't have a property indicator; look into using the data- property instead: cell.setAttribute('data-indicator', indicator). You should also modify your set() method to read that property instead.

Autocomplete the numbers

I need to expand this code to make it so I have 9 x 9 board and when I put some nunbers in it then press the button it completes the 9x9 with numbers unique in line and column
<meta charset="utf-8">
<style>
input { font-size: 20px; width: 30px; text-align: center; }
</style>
<h1 id="a"></h1>
<button type="button" id="b" onClick="uzup()">uzupe�nij</button>
for( i=1; i<6; i++ ) {
document.getElementById('a').innerHTML += '<input id="a' + i + '" maxlength="1" pattern="^[1-5]$">';
}
function uzup() {
for(i=1;i<6;i++){
w = document.getElementById('a'+i).value;
if( w == '' ) {
w = Number(w);
for(j=1;j<6;j++){
jest = false;
for(k=1;k<6;k++){
w = document.getElementById('a'+k).value;
if( w != '' ){
if( Number(w) == j ) jest = true;
}
}
if( !jest ) {
document.getElementById('a'+i).value = j; break;
}
}
}
}
}
I don't know if I got it right. With an input like this
1 3 _
4 _ 5
5 _ 2
you want a result like this?
1 3 4
4 1 5
5 4 2
is that correct?
I tried to do it in the most obvious and legible way (real code would do it in about 10% of that amount of lines but would have the legibility of a well designed Perl script ;-) and I hope you understand the flow without extensive comments.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Nine By Nine</title>
<script type="text/javascript">
function clearTable(){
for(var i = 0; i<9; i++){
document.getElementById("c"+i).style.border = "1px solid grey";
document.getElementById("i"+i).value = "";
}
}
// Some checks & balances omitted!
function fillUp(){
var m = [],d,c,r;
var gotoError = function(idx){
document.getElementById("c"+idx).style.border = "1px solid red";
};
var checkField = function(n, row, col){
for(var i=0;i<3;i++){
if(i !== col && m[row * 3 + i] === n)
return false;
}
for(var i=0;i<3;i++){
if(i !== row && m[col + 3 * i] === n)
return false;
}
return true;
};
var resetTable = function(){
for(var i = 0; i<9; i++){
m[i] = -1;
document.getElementById("c"+i).style.border = "1px solid grey";
}
};
resetTable();
for(var i = 0; i<9; i++){
var val = document.getElementById("i"+i).value;
if(val){
d = parseInt(val);
if(isNaN(d)){
gotoError(i);
return;
}
c = i%3;
r = Math.floor(i/3);
if(!checkField(d,r,c)){
gotoError(i);
return;
}
m[i] = d;
}
}
for(var i=0;i<9;i++){
if(m[i] === -1){
for(var j = 1;j<6;j++){
c = i%3;
r = Math.floor(i/3);
if(checkField(j,r,c)){
document.getElementById("i"+i).value = j;
m[i] = j
break;
}
}
}
}
}
window.addEventListener('submit', function(ev) {
ev.preventDefault();
fillUp();
}, false)
</script>
<style type="text/css">
table {
padding: 1em 1em 1em 1em;
background-color: lightgreen;
}
td {
border: 1px solid grey;
padding: 5px 5px 5px 5px;
margin: 5px 5px 5px 5px;
background-color: lighgrey;
}
input {
width: 1.1em;
height: 1.1em;
text-align:center;
}
</style>
</head>
<body>
<form id="form0">
<table id="table0">
<tr id="r0">
<td id="c0"><input id="i0" maxlength="1" pattern="^[1-5]$"></td>
<td id="c1"><input id="i1" maxlength="1" pattern="^[1-5]$"></td>
<td id="c2"><input id="i2" maxlength="1" pattern="^[1-5]$"></td>
</tr>
<tr id="r1">
<td id="c3"><input id="i3" maxlength="1" pattern="^[1-5]$"></td>
<td id="c4"><input id="i4" maxlength="1" pattern="^[1-5]$"></td>
<td id="c5"><input id="i5" maxlength="1" pattern="^[1-5]$"></td>
</tr>
<tr id="r2">
<td id="c6"><input id="i6" maxlength="1" pattern="^[1-5]$"></td>
<td id="c7"><input id="i7" maxlength="1" pattern="^[1-5]$"></td>
<td id="c8"><input id="i8" maxlength="1" pattern="^[1-5]$"></td>
</tr>
</table>
<button id="bt0" type="button" onclick="fillUp()">Fill Up</button>
<button id="bt1" type="button" onclick="clearTable()">Clear Table</button>
<form>
</body>
</html>

Categories

Resources