I'm trying to create an object with an array of multiple objects inside it, each inner-object representing a card.
I initialise all three outside of a forEach() loop, push each item into the array and then assign that array to a key in my outer-object:
const cart = {};
const cartItems = [];
const cartItem = {}
cart['cart-items'] = cartItems;
cartItems.push(cartItem);
Inside the forEach() I take the card data, every time that cards button is clicked, and assign it to the inner-object:
///forEach() with 'click' event-handler for the buttons...
if (cartItem.id !== currentCardId) {
cartItem['id'] = currentCardId;
cartItem['name'] = currentCardName;
cartItem['price'] = this.dataset.cardPrice;
cartItem['quantity'] = 1;
} else {
cartItem.quantity = cartItem.quantity + 1;
}
///...end of forEach()
This increments the 'quantity' of the 'card' if I click the same button multiple times, but when I click on a separate button it overwrites the existing card and it's 'quantity' value.
I understand if I initialise cartItem and cartItems inside the loop it prevents this overwriting, but then the cards 'quantity' doesn't increment, it just creates a separate object with a 'quantity' of '1'.
Any idea how I can work around this?
Edit
Complete code:
addCartBtn.forEach(i => {
i.addEventListener('click', function(e) {
let currentCardId = this.dataset.cardId;
let currentCardName = this.dataset.cardName;
let currentCardQuantity = 0;
let currentCardPrice;
let removeCartItem = document.getElementsByClassName('remove-cart-item');
if (cartItem.id !== currentCardId) {
cartItem['id'] = currentCardId;
cartItem['name'] = currentCardName;
cartItem['price'] = this.dataset.cardPrice;
cartItem['quantity'] = 1;
} else {
cartItem.quantity = cartItem.quantity + 1;
}
if (this.dataset.cardPrice >= 1) {
currentCardPrice = '£' + this.dataset.cardPrice;
} else {
currentCardPrice = this.dataset.cardPrice + 'p';
}
if (currentCardName.length > 10) {
currentCardName = currentCardName.substring(0, 9) + '...';
}
if (document.getElementById(`${currentCardId}`)) {
cartItems.forEach(i => {
if (currentCardId === i) {
currentCardQuantity += 1;
document.getElementById(
`${currentCardId}`
).innerHTML = `x${currentCardQuantity}`;
} else {
document.getElementById(`${currentCardId}`).innerHTML = 'x1';
}
});
} else {
dropdownCheckoutContainer.innerHTML += `<div class="dropdown-card" id="remove-${currentCardId}"><div class="dropdown-card-display"><p class="remove-${currentCardId}"><i class="fa fa-minus-square remove-cart-item" data-remove-id="${currentCardId}"></i>${currentCardName}</p></div><div class="dropdown-quantity"><p class="remove-${currentCardId}" id="${currentCardId}">x1</p></div><div class="dropdown-price"><p class="remove-${currentCardId}">${currentCardPrice}</p></div><div class="dropdown-hidden-id"><input class="remove-${currentCardId}" type="hidden" name="${currentCardId}" data-remove-id="${currentCardId}"></div></div>`;
}
if (dropdownCheckoutContainer.childElementCount >= 7) {
dropdownCheckoutContainer.style.overflow = 'scroll';
dropdownCheckoutContainer.style.borderBottom =
'1px solid rgba(255, 98, 0, 0.5)';
}
if (dropdownCheckoutContainer.childElementCount > 1) {
notificationIconContainer.style.display = 'flex';
notificationIcon.innerHTML =
dropdownCheckoutContainer.childElementCount - 1;
}
for (const i of removeCartItem) {
i.addEventListener('click', function(e) {
let btnId = this.dataset.removeId;
let currentRow = document.getElementById(`remove-${btnId}`);
let idIndexes = [];
if (dropdownCheckoutContainer.childElementCount > 1) {
dropdownCheckoutContainer.removeChild(currentRow);
}
notificationIcon.innerHTML = notificationIcon.innerText - 1;
if (!(dropdownCheckoutContainer.childElementCount >= 7)) {
dropdownCheckoutContainer.style.borderBottom = 'none';
if (checkoutFull.childElementCount === 1) {
checkoutFull.innerHTML = '';
}
}
cartItems.forEach(i => {
if (i === btnId) {
idIndexes.push(cartItems.indexOf(i));
}
});
for (let i = idIndexes.length - 1; i >= 0; i--) {
cartItems.splice(idIndexes[i], 1);
}
});
i.addEventListener('mouseup', () => {
if (dropdownCheckoutContainer.childElementCount <= 2) {
document.getElementById('empty-cart').style.display = 'block';
checkoutLink.classList.add('checkout-link-disabled');
}
if (dropdownCheckoutContainer.childElementCount <= 2) {
notificationIconContainer.style.display = 'none';
}
});
}
console.log(cart);
});
i.addEventListener('mouseup', () => {
document.getElementById('empty-cart').style.display = 'none';
checkoutLink.removeAttribute('class', 'checkout-link-disabled');
});
});
suppose, You have a data like that
let cart = { 'cart-items': [{id: 1, name: 'test 1', price: 30.9, quantity: 1}] }
When You are going to click on button then currentCardId = 1
Then you need to the following at click event.
const existsIndex = cart['cart-items'].findIndex((item) => item.id === currentCardId )
if (existsIndex !== -1) {
cart['cart-items'][existsIndex].quantity++
} else {
cart['cart-items'].push({id: currentCardId, name: 'sadsad', quantity: 1})
}
Related
I'm trying to make a Farm Clicker game myself with javascript. In other words, as you click the Add Gold button, the player will have more gold and will be able to buy new animals with the gold he has earned. But in my code I come across the following error: script.js:42 Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
at addGold (script.js:42:54)
at HTMLButtonElement. (script.js:11:42)
What is this error caused by? I leave the codes below.
// global variables
const myContent = document.getElementById("content");
var gold = 0;
let animals = {};
var goldToAdd = 0;
// global functions
function addGoldButton() {
let myButton = document.createElement("button");
myButton.addEventListener("click", () => addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
myContent.appendChild(myButton);
}
function passiveGold() {
if (animals.goats > 0) {
goldToAdd += animals.goats * 5; //50=>5 10=>1
}
if (animals.pigs > 0) {
goldToAdd += animals.pigs * 10; //90=>10 9=>1
}
if (animals.cows > 0) {
goldToAdd += animals.cows * 15; //120=>15 8=>1
}
addGold(goldToAdd);
}
addGoldButton();
function addGold(goldToAdd) {
console.trace();
if (gold = null) {
gold = goldToAdd;
let goldCounter = document.createElement("h2");
goldCounter.id = "goldCounter";
goldCounter.innerHTML = "Gold: " + gold;
myContent.appendChild(goldCounter);
} else {
gold += goldToAdd;
document.getElementById("goldCounter").innerHTML = "Gold: " + gold;
}
// check for events on current gold level
checkGold();
}
function checkGold() {
if (gold >= 50 && document.getElementById("goatBuyButton") == null) {
let buttonBar = document.createElement("div");
buttonBar.id = "buttonBar";
let buyButton = document.createElement("button");
buyButton.id = "goatBuyButton";
buyButton.innerHTML = "Buy Goat (50g)";
buyButton.addEventListener("click", () => buyAnimal("goat"));
myContent.appendChild(buttonBar);
buttonBar.appendChild(buyButton);
}
if (gold >= 90 && document.getElementById("pigBuyButton") == null) {
let buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "pigBuyButton";
buyButton.dinnerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", () => buyAnimal("pig"));
buttonBar.appendChild(buyButton);
}
if (gold >= 120 && document.getElementById("cowBuyButton") == null) {
buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "cowBuyButton";
buyButton.innerHTML = "Buy Cow (120g)";
buyButton.addEventListener("click", () => buyAnimal("cow"));
buttonBar.appendChild(buyButton);
}
function buyAnimal(animal) {
let itemBar = document.getElementById('itemBar');
if (itemBar == null) {
itemBar = document.createElement("div");
itemBar.id != "itemBar";
myContent.appendChildren(itemBar);
}
switch (animal) {
//do something, don't and forget the break;
case "goat":
if (gold >= 50) {
addGold(-50);
if (animals.goats == null) {
animals.goats = 1;
let myElement = document.createElement("div");
myElement.id = "goats";
myElement.innerHTML = "Goat Quantity: " + animals.goats;
itemBar.appendChild(myElement);
} else {
animals.goats += 1;
document.getElementById("goats").innerHTML = "Goat Quantity: " + animals.goats;
}
}
break;
case "pig":
if (gold >= 90) {
addGold(-90);
if (animals.pigs == null) {
animals.pigs = 1;
let myElement = document.createElement("div");
myElement, id = "pigs";
myElement.innerHTML = "Pig Quantity: " + animals.pigs;
itemBar.appendChild(myElement);
} else {
animals.pigs += 1;
document.getElementById("pigs").innerHTML = "Pig Quantity: " + animals.pigs;
}
}
break;
case "cow":
if (gold >= 120) {
addGold(-120);
if (animals.cows == null) {
animals.cows = 1;
let myElement = document.createElement("div");
myElement.id = "cows";
myElement.innerHTML = "Cow Quantity: " + animals.cows;
itemBar.appendChild(myElement);
} else {
animals.cows += 1;
document.getElementById("cows").innerHTML = "Cow Quantity: " + animals.cows;
}
}
break;
default:
console.log("geen dier gevonden");
}
}
// add elements
// start application
setInterval(passiveGold, 5000);
}
<div id="content"></div>
<!--<script src="script.js"></script> script is referenced right before </body> -->
the element goldCounter is never going to be added to your dom, that's why it says "Cannot set properties of null". At line number 33, in the if statement there is an error.
Replace line 33, this
if (gold = null) {
with
if (gold == 0) {
Hope, it helps!!
The null do not equals to 0, so if the gold contents 0, gold==null will return false and try find the element with goldCounter id (but the easyest way if(!gold))
At the passiveGold function, you do not have to check the animals bigger than 0, because n*0=0, so nothing will happen (it just make your code nicer).
And the buyAnimal function's front: not appendChildren (perhaps you just misspelled it)
I am trying to re-create a the card game war using JS/HTML/CSS. I am trying to begin physically building my player cards, but I keep running into this error: Uncaught TypeError: Cannot set property 'innerHTML' of null #runGame(logic.js:63) and at HTMLButtonElement.start(logic.js.47). It keeps highlighting the line playerCard.innerHTML = displayCard(player,0); Does anyone know what my issue is ?
let userScore = document.querySelector('.score span')
userScore.innerText = 26;
let score = 26;
let cpuScore = document.querySelector('.cpuScore span')
cpuScore.innerText = 26;
let compScore = 26;
const suits = ['spades', 'diamonds', 'clubs', 'hearts'];
const cardValue = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14'];
let player = [];
let computer = [];
let startGame = true;
let endGame = false;
separateCards = [
[],
[]
]
let playerCard = document.querySelector("#user cardSpot");
let computerCard = document.querySelector("#cpu cpuHand");
let deck = []
function start() { // function that begins game.
if (startGame) {
startGame = false;
shuffleCards(deck)
splitCards(deck)
document.getElementById('start').style.visibility = 'hidden'
}
runGame()
}
document.getElementById('start').addEventListener('click', start)
function runGame() { //compares the user's card to computer's card
if (!endGame) {
player = separateCards[0].shift()
computer = separateCards[1].shift()
let totalCards = [player, computer]
playerCard.innerHTML = displayCard(player, 0);
computerCard.innerHTML = displayCard(computer, 0);
war(player, computer, totalCards)
userScore.innerHTML = separateCards[0].length
cpuScore.innerHTML = separateCards[1].length;
// console.log('player is : ',player)
// console.log('computer is: ',computer)
console.log(separateCards)
} else {
document.getElementById('warButton').style.visibility = 'hidden'
document.querySelector('#warButton span').innerText = 'GAME OVER'
document.getElementById('start').style.visibility = 'visible'
}
}
function displayCard(c, p) {
let move = p * 40;
console.log(c, move);
}
function war(player, computer, totalCards) {
if ((separateCards[0].length === 52) || (separateCards[1].length === 52)) {
endGame = true;
return;
}
if (player.value > computer.value) {
separateCards[0] = separateCards[0].concat(totalCards)
} else if (player.value < computer.value) {
separateCards[1] = separateCards[1].concat(totalCards)
} else if (player.value === computer.value) {
fight(totalCards)
}
}
function fight(totalCards) {
if ((separateCards[0].length === 52) || (separateCards[1].length === 52)) {
endGame = true;
return
} else {
for (i = 0; i < 4; i++) {
player = separateCards[0].shift();
totalCards = totalCards.concat(player)
}
for (i = 0; i < 4; i++) {
computer = separateCards[1].shift();
totalCards = totalCards.concat(computer)
}
war(player, computer, totalCards)
}
}
document.getElementById('warButton').addEventListener('click', start) //event listener for war button
function createDeck(suits, cardValue) { //function for creating cards
for (i = 0; i < suits.length; i++) {
for (j = 0; j < cardValue.length; j++) {
let card = {
value: parseInt(cardValue[j]),
suit: suits[i]
}
deck.push(card)
}
}
}
createDeck(suits, cardValue)
function shuffleCards(deck) { //function for shuffling cards
for (let i = 0; i < deck.length; i++) {
let index1 = Math.floor((Math.random() * deck.length)); //random number used as index to find a random value within the deck
let index2 = Math.floor((Math.random() * deck.length));
let tmp = deck[index1];
deck[index1] = deck[index2];
deck[index2] = tmp;
}
}
function splitCards(deck) {
for (i = 0; i < deck.length; i++) {
separateCards[i % 2].push((deck[i]))
}
}
<header>
<h1 id="title">Let's Play War!</h1>
<h3 id="userTitle">User:<span></span></h3>
</header>
<div id='user' class='player'></div>
<div class='score'>Score: <span></span></p>
<div class='cardSpot'></div>
<section id="buttons">
<button id="warButton" class="button">WAR!<span></span></button>
<button id="start" class="button" ;>Start</button>
<h3 id="cpuTitle">CPU: <span></span></h3>
</section>
</div>
</header>
<div id='cpu' class='player'>
<div class="cpuScore">Score: <span></span></p>
<div class="cpuHand"></div>
ISSUES
In your code, playerCard was assigned to null because there is no .cardSpot in #user. .cardSpot is outside of the #user
displayCard does not have a return value so it will cause another error
Your 's closes with 's it might cause some errors when you start refferring to the elements without proper closures
let userScore = document.querySelector('.score span')
userScore.innerText = 26;
let score = 26;
let cpuScore = document.querySelector('.cpuScore span')
cpuScore.innerText = 26;
let compScore = 26;
const suits = ['spades', 'diamonds', 'clubs', 'hearts'];
const cardValue = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14'];
let player = [];
let computer = [];
let startGame = true;
let endGame = false;
separateCards = [
[],
[]
]
const playerCard = document.querySelector("#user .cardSpot")
const computerCard = document.querySelector(".cpuHand")
//console.log(playerCard)
let deck = []
function start() { // function that begins game.
if (startGame) {
startGame = false;
shuffleCards(deck)
splitCards(deck)
document.getElementById('start').style.visibility = 'hidden'
}
runGame()
}
document.getElementById('start').addEventListener('click', start)
function runGame() { //compares the user's card to computer's card
if (!endGame) {
player = separateCards[0].shift()
computer = separateCards[1].shift()
let totalCards = [player, computer]
playerCard.innerHTML = displayCard(player, 0);
computerCard.innerHTML = displayCard(computer, 0);
war(player, computer, totalCards)
userScore.innerHTML = separateCards[0].length
cpuScore.innerHTML = separateCards[1].length;
// console.log('player is : ',player)
// console.log('computer is: ',computer)
//console.log(separateCards)
} else {
document.getElementById('warButton').style.visibility = 'hidden'
document.querySelector('#warButton span').innerText = 'GAME OVER'
document.getElementById('start').style.visibility = 'visible'
}
}
function displayCard(c, p) {
let move = p * 40;
let suit = ' style=color:black>♠';
switch (c.suit) {
case 'spades':
suit = ' style=color:black>♠';
break;
case 'diamonds':
suit = ' style=color:red>♦';
break;
case 'hearts':
suit = ' style=color:red>♥';
break;
case 'clubs':
suit = ' style=color:black>♣';
break;
}
return `<span>${c.value}</span><span${suit}</span><span>${c.value}</span>` // this is what's missing
} // must have a return value
function war(player, computer, totalCards) {
if ((separateCards[0].length === 52) || (separateCards[1].length === 52)) {
endGame = true;
}
if (player.value > computer.value) {
separateCards[0] = separateCards[0].concat(totalCards)
} else if (player.value < computer.value) {
separateCards[1] = separateCards[1].concat(totalCards)
} else if (player.value === computer.value) {
fight(totalCards)
}
}
function fight(totalCards) {
if ((separateCards[0].length === 52) || (separateCards[1].length === 52)) {
endGame = true;
return
} else {
for (i = 0; i < 4; i++) {
player = separateCards[0].shift();
totalCards = totalCards.concat(player)
}
for (i = 0; i < 4; i++) {
computer = separateCards[1].shift();
totalCards = totalCards.concat(computer)
}
war(player, computer, totalCards)
}
}
document.getElementById('warButton').addEventListener('click', start) //event listener for war button
function createDeck(suits, cardValue) { //function for creating cards
for (i = 0; i < suits.length; i++) {
for (j = 0; j < cardValue.length; j++) {
let card = {
value: parseInt(cardValue[j]),
suit: suits[i]
}
deck.push(card)
}
}
}
createDeck(suits, cardValue)
function shuffleCards(deck) { //function for shuffling cards
for (let i = 0; i < deck.length; i++) {
let index1 = Math.floor((Math.random() * deck.length)); //random number used as index to find a random value within the deck
let index2 = Math.floor((Math.random() * deck.length));
let tmp = deck[index1];
deck[index1] = deck[index2];
deck[index2] = tmp;
}
}
function splitCards(deck) {
for (i = 0; i < deck.length; i++) {
separateCards[i % 2].push((deck[i]))
}
}
:is(.cardSpot, .cpuHand) {
display: grid;
box-sizing:border-box;
grid-template-rows: 1fr 2fr 1fr;
height: 5rem;
width: 4rem;
border: 1px solid #000;
padding: 2px;
}
:is(.cardSpot, .cpuHand) span:nth-child(1) {
justify-self: start;
}
:is(.cardSpot, .cpuHand) span:nth-child(2) {
justify-self: center;
font-size: 2rem
}
:is(.cardSpot, .cpuHand) span:nth-child(3) {
justify-self: end;
}
<header>
<h1 id="title">Let's Play War!</h1>
<h3 id="userTitle">User:<span></span></h3>
</header>
<!--
playerCard = document.querySelector("#user .cardSpot") returns null because .cardspot is outside #user
<div id='user' class='player'></div>
<div class='score'>Score: <span></span> // your tags are also open, they don't have closing tags
<div class='cardSpot'></div>
-->
<div id='user' class='player'>
<div class='score'>Score: <span></span></div>
<div class='cardSpot'></div>
</div>
<br><br>
<section id="buttons">
<button id="warButton" class="button">WAR!<span></span></button>
<button id="start" class="button" ;>Start</button>
<h3 id="cpuTitle">CPU: <span></span></h3>
</section>
</div>
</header>
<div id='cpu' class='player'>
<div class="cpuScore">Score: <span></span></div>
<div class="cpuHand"></div>
</div>
I have a function that checking board is there a searching element.
First script creating a board with different elements. Element in the square next to board is element that user has to find on the board and click them.
User has to click (as quick as possible) all searching elements. After click on element function checking a board, is there more elements. If yes then nothing happen and user has to click another one. If on board there isn’t searching elements then function display a time and new board create.
But some reason function works correct only first time after page load. Latter function ignore more then one element on board or see element that doesn’t exist on board any more.
Can you tell me what is wrong.
Part of code bellow and there is a link to testing page.
http://doomini2.linuxpl.info/font/
Thank you
function secondStage() {
createBoxes(59);
var usingSet = [];
var i = 0;
var boxList = document.querySelectorAll("#board > div");
createSet(usingSet, 20, shapes);
(function paint() {
if (i <= 59) {
var curentBox = boxList[i];
curentBox.className = usingSet[draw(20)];
curentBox.style.color = colors[draw(colors.length - 5)];
timeStop = setTimeout(paint, 50);
i++;
} else {
var findShape = boxList[draw(59)];
toFind.className = findShape.className;
toFind.style.color = findShape.style.color;
findBoxes(boxList);
clearTimeout(timeStop);
}
})();
}
//function checks boxes to find a proper shape
function findBoxes(boxList) {
startTime = Date.now();
board.addEventListener("mousedown", function (e) {
if ((e.target.className === toFind.className)) {
e.target.className = "correct";
e.target.innerHTML = "OK";
checkBoard();
} else if (e.target.id === "board" || e.target.className === "correct") {
} else {
e.target.className = "false";
e.target.innerHTML = "NO";
}
}, false);
function checkBoard() {
var condition = false;
console.log(condition);
for (var x = 0; x < boxList.length; x++) {
if ((boxList[x].className === toFind.className)) {
condition = true;
console.log(condition);
}
}
if (condition === false) {
var clickTime = Date.now();
var timeResult = parseFloat(((clickTime - startTime) / 1000).toFixed(3));
lastResult.innerHTML = timeResult + "s";
secondResult[secondResult.length] = timeResult;
console.log(secondResult);
displayResult(secondStage);
}
}
}
//function displaig results after every single round
function displayResult(stage) {
cover.className = "";
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeOut, right: (winWidth / 4), });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: (winWidth / 3), onComplete: function () {
goButton.addEventListener("click", function () {
clear();
}, false);
}});
//clear board and return to play
function clear() {
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeIn, right: winWidth, });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: -100, onComplete: function () {
cover.className = "hide";
lastResultDiv.style.right = "-592px";
toFind.className = "";
board.innerHTML = "";
if (firstStageRound === 10) {
secondStage();
} else if (secondStageRound === 5) {
thirdStage();
} else {
stage();
}
}});
}
}
Not Load this File http://cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/TweenMax.min.js
try to local path
MAJOR EDIT: Re-Did a lot of things. But similar error.
var white = 1;
var turn = white;
var table = document.getElementById("game");
function createTable(table, white) {
var i,j,tr;
for(i=0;i<8;i++)
{
tr = document.createElement('tr');
for(j=0;j<8;j++)
tr.appendChild(document.createElement('td')).id = String.fromCharCode( (white == 1 ? j : 8-j) +97)+(white == 1 ? 8-i : i+1);
table.appendChild(tr);
}
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
table.rows[i].cells[j].setAttribute("class","cell");
}
}
}
function onImageLoad(t) {
console.log(t);
}
function createImageArray() {
var w,c,p;
var image = new Array(2);
for(w=0;w<2;w++)
{
image[w] = new Array(2);
for(c=0;c<2;c++)
{
image[w][c] = new Array(6);
for(p=0;p<6;p++)
{
image[w][c][p] = new Array(2);
}
}
}
return image;
}
function createBlankimageArray() {
var blank = new Array(2);
return blank;
}
function bufferImages(image,blank) {
var w, c, p, s, word;
for(w=0;w<2;w++)
{
for(c=0;c<2;c++)
{
for(p=0;p<6;p++)
{
for(s=0;s<2;s++)
{
word = w.toString() + c.toString() + (p+1).toString() + s.toString() + ".png";
//console.log(word);
image[w][c][p][s] = new Image();
image[w][c][p][s].onload = onImageLoad(word);
image[w][c][p][s].src='final images/'+ word;
}
}
}
}
for(i=0;i<2;i++)
{
blank[i] = new Image();
word = i.toString() + '.png';
blank[i].onload = onImageLoad(word);
blank[i].src= 'final images/'+ word;
}
}
function intializeState() {
var x,y,temp;
var state = new Array(8);
for(y=0;y<8;y++)
{
state[y] = new Array(8);
for(x=0;x<8;x++)
{
state[y][x] = new Array(3);
// Set Cell White or Black.
state[y][x][0] = (x+y)%2;
if(y==1 || y == 6)
{
temp = 0;
state[y][x][1] = temp;
state[y][x][2] = ( white==1 ? 0 : 1);
}
else if(x==0 || x==7) {temp = 1;}
else if(x==1 || x==6) {temp = 2;}
else if(x==2 || x==5) {temp = 3;}
else if(x==3) {temp = 4;}
else if(x==4) {temp = 5;}
if(temp!=0)
{
if(y==0)
{
state[y][x][1] = temp;
state[y][x][2] = (white == 1 ? 0 : 1);
}
else if(y==7)
{
state[y][x][1] = temp;
state[y][x][2] = (white == 1 ? 1 : 0);
}
else
{
state[y][x][1] = 7;
state[y][x][2] = 7;
}
}
}
}
return state;
}
function drawState(table,state,image,blank) {
var y,x;
//var table = document.getElementById("game");
var w,c,p;
for(y=0;y<8;y++)
{
for(x=0;x<8;x++)
{
c = state[y][x][0];
w = state[y][x][1];
p = state[y][x][2];
if(p!=7)
{
table.rows[y].cells[x].appendChild(image[w][c][p][0]);
}
else
{
table.rows[y].cells[x].appendChild(blank[c]);
}
}
}
}
var state = intializeState();
var image = createImageArray();
var blank = createBlankimageArray();
createTable(table, white);
bufferImages(image,blank);
intializeState(state);
drawState(table,state,image,blank);
HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Anti Chess</title>
<link rel="stylesheet" type="text/css" href="screen2.css">
</head>
<body>
<h1 id="game_title">Anti Chess by theManikJindal</h1>
Visit Blog!
<br />
<br />
<table id="game"></table>
<script src="req_logic.js"></script>
</body>
</html>
The above script is required to create a chess board in the initial position.
The problem that I am encountering is in the drawState function.
Console: (has printed out all the image names after loading them) After that:
Uncaught TypeError: Cannot read property '1' of undefined req_logic.js:154
Which is the line: table.rows[y].cells[x].appendChild(image[w][c][p][0]);
so where have I gone wrong.
EDIT: jsFiddle.net link : http://jsfiddle.net/8H3Ha/1/
Change the definition ot initializeState() to:
function intializeState() {
var x,y,temp;
var state = new Array(8);
for(y=0;y<8;y++)
{
state[y] = new Array(8);
for(x=0;x<8;x++)
{
state[y][x] = new Array(3);
// Set Cell White or Black.
state[y][x][0] = (x+y)%2;
if(y==1 || y == 6)
{
temp = 0;
state[y][x][1] = temp;
state[y][x][2] = ( white==1 ? 0 : 1);
}
else if(x==0 || x==7) {temp = 1;}
else if(x==1 || x==6) {temp = 2;}
else if(x==2 || x==5) {temp = 3;}
else if(x==3) {temp = 4;}
else if(x==4) {temp = 5;}
if(temp!=0)
{
if(y==0)
{
state[y][x][1] = temp;
state[y][x][2] = (white == 1 ? 0 : 1);
}
else if(y==7)
{
state[y][x][1] = temp;
state[y][x][2] = (white == 1 ? 1 : 0);
}
else
{
state[y][x][1] = 7;
state[y][x][2] = 7;
}
}
}
}
return state;
}
Then call it as:
state = initializeState();
The problem is that the parameter variable named state was shadowing the global variable with the same name inside initializeState.
I also suggest that the elements of the state array should be objects, not arrays. Arrays should be used when the elements are uniform, but each of these sub-elements have different purposes: [0] is the cell color, [1] is the piece, and [2] is the piece color.
I have a table that calculates a total depending on the input the user types. My problem is that the jquery code is calculating each key stroke and not "grabbing" the entire number once you stop typing. Code is below, any help woud be greatly appreciated.
$(document).ready(function() {
$('input.refreshButton').bind('click', EstimateTotal);
$('input.seatNumber').bind('keypress', EstimateTotal);
$('input.seatNumber').bind('change', EstimateTotal);
});
//$('input[type=submit]').live('click', function() {
function EstimateTotal(event) {
var tierSelected = $(this).attr('data-year');
var numberSeats = Math.floor($('#numberSeats_' + tierSelected).val());
$('.alertbox_error_' + tierSelected).hide();
if (isNaN(numberSeats) || numberSeats == 0) {
$('.alertbox_error_' + tierSelected).show();
} else {
$('.alertbox_error_' + tierSelected).hide();
var seatHigh = 0;
var seatLow = 0;
var seatBase = 0;
var yearTotal = 0;
var totalsArray = [];
var currentYear = 0;
$('.tier_' + tierSelected).each(function() {
seatLow = $(this).attr('data-seat_low');
firstSeatLow = $(this).attr('data-first_seat_low');
seatHigh = $(this).attr('data-seat_high');
seatBase = $(this).attr('data-base_cost');
costPerSeat = $(this).attr('data-cost_per_seat');
years = $(this).attr('data-year');
seats = 0;
if (years != currentYear) {
if (currentYear > 0) {
totalsArray[currentYear] = yearTotal;
}
currentYear = years;
yearTotal = 0;
}
if (numberSeats >= seatHigh) {
seats = Math.floor(seatHigh - seatLow + 1);
} else if (numberSeats >= seatLow) {
seats = Math.floor(numberSeats - seatLow + 1);
}
if (seats < 0) {
seats = 0;
}
yearTotal += Math.floor(costPerSeat) * Math.floor(seats) * Math.floor(years) + Math.floor(seatBase);
});
totalsArray[currentYear] = yearTotal;
totalsArray.forEach(function(item, key) {
if (item > 1000000) {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('Contact Us');
} else {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('$' + item);
}
});
}
}
You'll need a setTimeout, and a way to kill/reset it on the keypress.
I'd personally do something like this:
var calc_delay;
$(document).ready(function() {
$('input.refreshButton').bind('click', runEstimateTotal);
$('input.seatNumber').bind('keypress', runEstimateTotal);
$('input.seatNumber').bind('change', runEstimateTotal);
});
function runEstimateTotal(){
clearTimeout(calc_delay);
calc_delay = setTimeout(function(){ EstimateTotal(); }, 100);
}
function EstimateTotal() {
....
What this does is prompt the system to calculate 100ms after every keypress - unless another event is detected (i.e. runEstimateTotal is called), in which case the delay countdown resets.