Farm Clicker game - Gold's value is increasing more than necessary - javascript

I'm trying to make a Farm Clicker game myself with Javascript. (In other words, as you click the Add Gold button, the user earns 1 gold and can obtain passive gold by buying some animals according to the number of gold he has.) But there is a problem with the program: If I save 50 gold and buy a goat, the gold suddenly increases more than necessary. The problem is most likely in the section that says setInterval, but I still couldn't find the exact solution.
HTML
<head>
<title>Farm clicker</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content"></div>
<script src="script.js"></script>
</body>
JS
// 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.id = "addButton";
myButton.addEventListener("click", ()=>addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
myContent.appendChild(myButton);
}
addGoldButton();
function addGold(goldToAdd) {
console.trace();
if (gold == 0) {
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();
goldToAdd=0;
}
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.innerHTML = "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.appendChild(itemBar);
}
switch (animal) {
case "":
//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("no animal found");
}
}
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);
}
setInterval(passiveGold, 10000);
}

So here the problem is in the passiveGold Function.It runs in to a infinite loop because after you are buying an animal the animal count is obviously greater than 0.So the if condition will be evaluated to true always inside the passiveGold function and as a result of that it runs into a infinite loop.
function passiveGold() {
if (animals.goats > 0) {
goldToAdd += animals.goats*5; //50=>5 10=>1
return;
}
if (animals.pigs > 0) {
goldToAdd += animals.pigs*10; //90=>10 9=>1
return;
}
if (animals.cows > 0) {
goldToAdd += animals.cows*15; //120=>15 8=>1
return;
}
addGold(goldToAdd);
}
So here i just did a small modification by adding return statements into every if condition code blocks.So that after executing once it will return to the main function.
// 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.id = "addButton";
myButton.addEventListener("click", ()=>addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
myContent.appendChild(myButton);
}
addGoldButton();
function addGold(goldToAdd) {
console.trace();
if (gold == 0) {
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();
goldToAdd=0;
}
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.innerHTML = "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.appendChild(itemBar);
}
switch (animal) {
case "":
//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("no animal found");
}
}
function passiveGold() {
if (animals.goats > 0) {
goldToAdd += animals.goats*5; //50=>5 10=>1
return;
}
if (animals.pigs > 0) {
goldToAdd += animals.pigs*10; //90=>10 9=>1
return;
}
if (animals.cows > 0) {
goldToAdd += animals.cows*15; //120=>15 8=>1
return;
}
addGold(goldToAdd);
}
setInterval(passiveGold, 10000);
}
<head>
<title>Farm clicker</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content"></div>
<script src="script.js"></script>
</body>
Hope I solved your problem.And if you need anything to be clarified let me know.

There are two main issues with the gold incrementation here. There's a brace out of place leading to (I think) the setInterval be created several times (each time checkGold is called, in fact). Secondly, the goldToAdd amount is not zero at the start of passiveGold. I've also edited addGold so that two gold counters don't turn up when you hit 0 gold. Snippet below:
const myContent = document.getElementById("content");
var gold=0;
let animals = {};
var goldToAdd = 0;
// global functions
function addGoldButton() {
let myButton = document.createElement("button");
myButton.id = "addButton";
myButton.addEventListener("click", ()=>addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
myContent.appendChild(myButton);
}
addGoldButton();
function addGold(goldToAdd) {
if(document.getElementById("goldCounter") == null) {
let goldCounter = document.createElement("h2");
goldCounter.id = "goldCounter";
myContent.appendChild(goldCounter);
}
gold += goldToAdd;
document.getElementById("goldCounter").innerHTML = "Gold: " + gold;
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.innerHTML = "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.appendChild(itemBar);
}
switch (animal) {
case "":
//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("no animal found");
}
}
function passiveGold() {
goldToAdd = 0;
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);
}
setInterval(passiveGold, 10000);
<div id="content"></div>

I've refactored your code and broke it down and remade it. i've made the logic simpler and more like an actual game loop demo
<head>
<title>Farm clicker</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content"></div>
</body>
// global state
let game_state = {
gold: 50,
animals: {
goats: 0,
pigs: 0,
cows: 0
},
}
// global variables
const content = document.getElementById("content");
let passiveGoldInterval = null;
// helper functions
function addGold(value){
game_state.gold += value;
updateUI();
}
function buyAnimal(animal){
switch(animal){
case 'goat':
if(game_state.gold >= 50){
addGold(-50);
game_state.animals.goats++;
}
break;
case 'pig':
if(game_state.gold >= 90){
addGold(-90);
game_state.animals.pigs++;
}
break;
case 'cow':
if(game_state.gold >= 120){
addGold(-120);
game_state.animals.cows++;
}
break;
default: // do nothing
}
updateUI();
}
// background function
function passiveGold(){
addGold(game_state.animals.goats * 5); // add gold for goats
addGold(game_state.animals.pigs * 10); // add gold for pigs
addGold(game_state.animals.cows * 15); // add gold for cows
}
// game state management (init)
function init(){
passiveGoldInterval = setInterval(passiveGold, 10000); // calss this function every 10 seconds
updateUI();
}
function updateUI(){
if (!(document.getElementById("addButton"))) {
let myButton = document.createElement("button");
myButton.id = "addButton";
myButton.addEventListener("click", ()=>addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
content.appendChild(myButton);
}
if (!(document.getElementById("goldCounter"))) {
let goldCounter = document.createElement("h2");
goldCounter.id = "goldCounter";
goldCounter.innerHTML = "Gold: " + game_state.gold;
content.appendChild(goldCounter);
} else
{
document.getElementById("goldCounter").innerHTML = "Gold: " + game_state.gold;
}
let itemBar = document.getElementById('itemBar');
if (itemBar == null) {
itemBar = document.createElement("div");
itemBar.id = "itemBar";
content.appendChild(itemBar);
}
// animals (display counts)
if (game_state.animals.goats >= 1 && !(document.getElementById("goats"))) {
let myElement1 = document.createElement("div");
myElement1.id = "goats";
myElement1.innerHTML = "Goat Quantity: " + game_state.animals.goats;
document.getElementById('itemBar').appendChild(myElement1);
} else if(document.getElementById("goats")) {
document.getElementById("goats").innerHTML = "Goat Quantity: " + game_state.animals.goats;
}
if (game_state.animals.pigs >= 1 && !(document.getElementById("pigs"))) {
let myElement2 = document.createElement("div");
myElement2.id = "pigs";
myElement2.innerHTML = "Pig Quantity: " + game_state.animals.pigs;
document.getElementById('itemBar').appendChild(myElement2);
} else if(document.getElementById("pigs")) {
document.getElementById("pigs").innerHTML = "Pig Quantity: " + game_state.animals.pigs;
}
if (game_state.animals.cows >= 1 && !(document.getElementById("cows"))) {
let myElement3 = document.createElement("div");
myElement3.id = "cows";
myElement3.innerHTML = "Cow Quantity: " + game_state.animals.cows;
document.getElementById('itemBar').appendChild(myElement3);
} else if(document.getElementById("cows")) {
document.getElementById("cows").innerHTML = "Cow Quantity: " + game_state.animals.cows;
}
// display buttons if match
// button container
if(!(document.getElementById("buttonBar"))){
let buttonBar = document.createElement("div");
buttonBar.id = "buttonBar";
content.appendChild(buttonBar);
}
// goats buy
if(game_state.gold >= 50){
if(!(document.getElementById("goatBuyButton"))){
let buyButton = document.createElement("button");
buyButton.id = "goatBuyButton";
buyButton.innerHTML = "Buy Goat (50g)";
buyButton.addEventListener("click", () => buyAnimal("goat"));
content.appendChild(buyButton);
}
} else {
if(document.getElementById("goatBuyButton")){
document.getElementById("goatBuyButton").remove();
}
}
// pigs buy
if(game_state.gold >= 90){
if(!(document.getElementById("pigBuyButton"))){
let buyButton = document.createElement("button");
buyButton.id = "pigBuyButton";
buyButton.innerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", () => buyAnimal("pig"));
content.appendChild(buyButton);
}
} else {
if(document.getElementById("pigBuyButton")){
document.getElementById("pigBuyButton").remove();
}
}
// cows buy
if(game_state.gold >= 120){
if(!(document.getElementById("cowBuyButton"))){
let buyButton = document.createElement("button");
buyButton.id = "cowBuyButton";
buyButton.innerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", () => buyAnimal("cow"));
content.appendChild(buyButton);
}
} else {
if(document.getElementById("cowBuyButton")){
document.getElementById("cowBuyButton").remove();
}
}
}
init();

Related

Nested if else statements only works on first statement

I am having an issue with nested if else statements. In this issue, it only executes the first if statement and skips all of the rest, when I want every statement to be executed. The else if statement works fine when there is nothing nested inside it, but when I nest additional if else statements only the first one seems to work. Here is my javascript code:
const apiURL2 = "https://api.openweathermap.org/data/2.5/forecast?id=5604473&appid=6d1d830097a2c0bac1aba2337d0139e6";
fetch(apiURL2).then((response) => response.json()).then((jsonObject) => {
const list = jsonObject['list'];
console.log(jsonObject);
for ( let i = 0; i < 5; i++){
let divForecastData = document.querySelector('div.weather-forecast-wrapper');
let temp1 = document.createElement("div");
let tempday = document.createElement("p");
let temperature = document.createElement("p");
let icon = document.createElement("i");
temperature.className = "temp";
tempday.className = "weekday";
temp1.className = "day";
if (i == 0){
tempday.textContent = "Sat";
temperature.textContent = list[i].main.temp;
if (list[i].weather[i].main = "Clear"){
icon.className = "worked"
}
else {
icon.className = " still worked"
}
}
else if (i == 1){
tempday.textContent = "Sun";
var far = list[i].main.temp
var kel = far * (9/5) - 459.67;
temperature.textContent = Math.round(kel) + "℉";
if (list[i].weather[i].main = "Clear"){
icon.className = "worked"
}
else {
icon.className = " still worked"
}
}
else if (i == 2){
tempday.textContent = "Mon";
temperature.textContent = list[i].main.temp;
}
else if (i == 3){
tempday.textContent = "Wed";
temperature.textContent = list[i].main.temp;
}
else{
tempday.textContent = "Thu";
temperature.textContent = list[i].main.temp;
}
divForecastData.appendChild(temp1);
temp1.appendChild(tempday);
temp1.appendChild(icon);
temp1.appendChild(temperature);
}
});
any suggestions?
Comparaison are coded with == or ===...
So this is not good.
if (list[i].weather[i].main = "Clear")
But list[i].weather[i] something doesn't exists, I know because it's there is a big red message that appears on the console just by running the code. You maybe wanted to use list[i].weather[0].
Here is a corrected code snippet
const apiURL2 = "https://api.openweathermap.org/data/2.5/forecast?id=5604473&appid=6d1d830097a2c0bac1aba2337d0139e6";
fetch(apiURL2).then((response) => response.json())
.then((jsonObject) => {
let divForecastData = document.querySelector('div.weather-forecast-wrapper');
console.log(jsonObject);
const list = jsonObject['list'];
for ( let i = 0; i < 5; i++){
const item = list[i];
let temp1 = document.createElement("div");
let tempday = document.createElement("p");
let temperature = document.createElement("p");
let icon = document.createElement("i");
temperature.className = "temp";
tempday.className = "weekday";
temp1.className = "day";
if (i == 0){
tempday.textContent = "Sat";
temperature.textContent = item.main.temp;
if (item.weather[i].main = "Clear"){
icon.className = "worked"
} else {
icon.className = " still worked"
}
} else if (i == 1){
tempday.textContent = "Sun";
var far = item.main.temp
var kel = far * (9/5) - 459.67;
temperature.textContent = Math.round(kel) + "℉";
if (item.weather[0].main === "Clear"){
icon.className = "worked"
} else {
icon.className = " still worked"
}
} else if (i == 2){
tempday.textContent = "Mon";
temperature.textContent = item.main.temp;
} else if (i == 3){
tempday.textContent = "Wed";
temperature.textContent = item.main.temp;
} else{
tempday.textContent = "Thu";
temperature.textContent = item.main.temp;
}
divForecastData.appendChild(temp1);
temp1.appendChild(tempday);
temp1.appendChild(icon);
temp1.appendChild(temperature);
}
});
<div class='weather-forecast-wrapper'></div>

Can't figure out how to add a little space between blocks

I wrote the little snake game at the bottom of this post.
Now I would like to separate each block of snake body by a little bit of (black) space between the blocks so that the green blocks are clearly a bit apart from each other.
Something like [s] [s] [s] [s]. [s] is what it's now a single green block of snake body, but I don't know how to add the space in between.
I am comfortable in JS, but these specifics of CSS are still a mystery to me. I'm not even sure I'm using the right approach to "draw" the snake in the first place.
let _game;
var gameLoopHandle;
var pollingHandle;
let Snake = function(forGame,startingDirection, startingBody){
this.going = startingDirection || "RIGHT";
this.go = function(direction){
let snakeHead = {x:this.getHead().x,y:this.getHead().y};
switch(direction.toLowerCase()){
case "left":
snakeHead.y--;
this.going = "LEFT";
break;
case "right":
snakeHead.y++;
this.going = "RIGHT";
break;
case "up":
snakeHead.x--;
this.going = "UP";
break;
case "down":
snakeHead.x++;
this.going = "DOWN";
break;
}
let newBlock =
generateBlock(snakeHead.x,snakeHead.y,
this.gameInstance.boardSizeX,this.gameInstance.boardSizeY);
if (this.posIsApple(newBlock)) {
this.gameInstance.score++;
this.gameInstance.genApple = true;
} else {
this.removeBockTailFromSnake();
}
if (this.posIsTail(newBlock)){
this.gameInstance.ended = true;
}
this.addBlockHeadToSnake(newBlock);
};
this.body = startingBody || [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11}
];
this.gameInstance = forGame;
this.getHead = function(){
return this.body[this.body.length-1];
};
this.posIsTail = function(pos){
for (let i = 0; i<this.body.length;i++){
if (pos.x === this.body[i].x && pos.y === this.body[i].y) {
return true;
}
}
return false;
};
this.posIsApple = function(pos){
return pos.x === this.gameInstance.apple.x && pos.y === this.gameInstance.apple.y;
};
this.addBlockHeadToSnake = function(block){
this.body.push(block);
}
this.removeBockTailFromSnake = function(){
this.body.shift();
}
}
let serverListener = function(keyEvents){
console.log(keyEvents);
for (let i = 0; i<keyEvents.length;i++) {
var event = new Event('keydown');
event.key="Arrow" + capitalizeFirstLetter(keyEvents[i].toLowerCase());
document.dispatchEvent(event);
}
}
let SnakeGame = function(){
this.board = [];
this.snake = {};
this.apple = {};
this.score = 0;
this.speed = 500;
this.ended = false;
this.genApple = true;
this.boardSizeX = 20;
this.boardSizeY = 20;
this.manager = {};
}
SnakeGame.prototype.init = function(options){
options = options || {};
this.boardSizeX = options.boardSizeX || 20;
this.boardSizeY = options.boardSizeY || 20;
this.snake = options.snake || new Snake(this);
}
SnakeGame.prototype.setSnake = function(){
// sets snake to provided params
}
SnakeGame.prototype.generateBoard = function(){
this.board = [];
for (let i=0;i<this.boardSizeX;i++){
let boardRow=[];
for (let j = 0; j < this.boardSizeY; j++) {
let havePixel = false;
for (let k = 0; k<this.snake.body.length;k++){
if (this.snake.body[k].x === i && this.snake.body[k].y === j ){
havePixel = true;
}
}
if (havePixel) {
boardRow.push(1);
} else {
boardRow.push(0);
}
}
this.board.push(boardRow);
}
}
SnakeGame.prototype.setSpeed = function(speed){
this.speed = speed;
}
SnakeGame.prototype.setScore = function(score){
this.score = score;
}
let generateBlock = function(x,y,limitX,limitY){
let block = {};
if (x===limitX) {
block.x = 0;
} else if (x == -1) {
block.x = limitX-1;
} else {
block.x = x;
}
if (y===limitY) {
block.y = 0;
} else if (y == -1) {
block.y = limitY-1;
} else {
block.y = y;
}
return block;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
let genericDiv = function(color){
let returnDiv = document.createElement("div");
returnDiv.style.height = "10px";
returnDiv.style.width = "10px";
returnDiv.style.background = color;
return returnDiv;
}
let snakeDiv = function(){
return genericDiv("lime");
}
let emptyDiv = function(){
return genericDiv("black");
}
let appleDiv = function(){
return genericDiv("red");
}
function updateDOM(game) {
var el = document.getElementById("gameboard");
el.innerHTML = "";
el.style.position = "relative";
var scoreEl = document.getElementById("score");
scoreEl.innerText = game.score;
if (game.genApple) {
generateAppleNoCollision(game);
}
for (let i =0;i<game.board.length;i++){
let snakeRowDiv = document.createElement("div");
//snakeRowDiv.style.position = "absolute";
for (let j=0;j<game.board[i].length;j++){
let whichDiv = null;
if (game.board[i][j]){
whichDiv = snakeDiv();
} else if (i==game.apple.x && j == game.apple.y){
whichDiv = appleDiv();
}
if (whichDiv == null){
whichDiv = emptyDiv();
}
whichDiv.style.position = "absolute";
whichDiv.style.left = j * (parseInt(whichDiv.style.width)) + "px";
whichDiv.style.top = (i * (parseInt(whichDiv.style.height)) + 100) + "px";
snakeRowDiv.appendChild(whichDiv);
}
el.appendChild(snakeRowDiv);
}
}
function generateDomListener(game){
return function(event){
switch (event.key) {
case "ArrowUp":
if (game.snake.going != "DOWN"){
game.snake.going = "UP";
}
break;
case "ArrowDown":
if (game.snake.going != "UP"){
game.snake.going = "DOWN";
}
break;
case "ArrowLeft":
if (game.snake.going != "RIGHT") {
game.snake.going = "LEFT";
}
break;
case "ArrowRight":
if (game.snake.going != "LEFT") {
game.snake.going = "RIGHT";
}
break;
}
}
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function decreaseDifficulty(game){
if (game.speed <= 900) {
game.speed += 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function restart(game){
game.ended = false;
game.genApple = true;
game.score = 0;
game.speed = 500;
game.apple = {x:null,y:null}
game.snake.body = [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11},
]
game.snake.going = "RIGHT";
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function generateAppleNoCollision(game){
while(true){
game.apple.x = getRandomInt(0,game.board.length-1);
game.apple.y = getRandomInt(0,game.board.length-1);
let hasCollision = false;
for (let i = 0; i<game.snake.body.length;i++){
if(game.apple.x === game.snake.body[i].x &&
game.apple.y === game.snake.body[i].y) {
hasCollision = true;
}
}
if (!hasCollision) {
console.log("no collision, continuing with this apple")
break;
}
console.error("found collision, searching once more")
}
game.genApple = false;
}
function increaseDifficulty(game){
if (game.speed >= 100) {
game.speed -= 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function gameLoop(game){
return function(){
if (!game.ended) {
game.snake.go(game.snake.going);
game.generateBoard();
updateDOM(game);
} else {
clearInterval(gameLoopHandle);
alert ("GAME OVER");
}
}
}
function polling(game){
return function(){
var scriptsDiv = document.getElementById("scripts");
var script = document.createElement('script');
script.src="http://172.168.1.22/snake_relay/?command=get&callbackname=serverListener";
if (game.scripts) {
if (game.scripts.length == 100){
let msg = "too many scripts, clearing the div";
scriptsDiv.innerHTML = ""
}
game.scripts.push(script);
} else {
game.scripts = [script];
}
scriptsDiv.appendChild(script);
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var game = new SnakeGame();
_game =game;
game.init();
game.generateBoard()
updateDOM(game);
document.addEventListener("keydown", generateDomListener(game));
//pollingHandle = setInterval(polling(game), 100);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
})
<div id="gameboard"></div>
<div>
<h1>Score: <span id="score">0</span></h1>
<button onclick="increaseDifficulty(_game)">Increase difficulty</button>
<button onclick="decreaseDifficulty(_game)">Decrease difficulty</button>
<button onclick="restart(_game)">Restart</button>
</div>
<div id="scripts"></div>
You can set border in genericDiv and pass the necessary values into snakeDiv.
let snakeDiv = function(){
return genericDiv("lime", "1px solid #000000");
}
You can set the border size to whichever size you need.
let _game;
var gameLoopHandle;
var pollingHandle;
let Snake = function(forGame,startingDirection, startingBody){
this.going = startingDirection || "RIGHT";
this.go = function(direction){
let snakeHead = {x:this.getHead().x,y:this.getHead().y};
switch(direction.toLowerCase()){
case "left":
snakeHead.y--;
this.going = "LEFT";
break;
case "right":
snakeHead.y++;
this.going = "RIGHT";
break;
case "up":
snakeHead.x--;
this.going = "UP";
break;
case "down":
snakeHead.x++;
this.going = "DOWN";
break;
}
let newBlock =
generateBlock(snakeHead.x,snakeHead.y,
this.gameInstance.boardSizeX,this.gameInstance.boardSizeY);
if (this.posIsApple(newBlock)) {
this.gameInstance.score++;
this.gameInstance.genApple = true;
} else {
this.removeBockTailFromSnake();
}
if (this.posIsTail(newBlock)){
this.gameInstance.ended = true;
}
this.addBlockHeadToSnake(newBlock);
};
this.body = startingBody || [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11}
];
this.gameInstance = forGame;
this.getHead = function(){
return this.body[this.body.length-1];
};
this.posIsTail = function(pos){
for (let i = 0; i<this.body.length;i++){
if (pos.x === this.body[i].x && pos.y === this.body[i].y) {
return true;
}
}
return false;
};
this.posIsApple = function(pos){
return pos.x === this.gameInstance.apple.x && pos.y === this.gameInstance.apple.y;
};
this.addBlockHeadToSnake = function(block){
this.body.push(block);
}
this.removeBockTailFromSnake = function(){
this.body.shift();
}
}
let serverListener = function(keyEvents){
console.log(keyEvents);
for (let i = 0; i<keyEvents.length;i++) {
var event = new Event('keydown');
event.key="Arrow" + capitalizeFirstLetter(keyEvents[i].toLowerCase());
document.dispatchEvent(event);
}
}
let SnakeGame = function(){
this.board = [];
this.snake = {};
this.apple = {};
this.score = 0;
this.speed = 500;
this.ended = false;
this.genApple = true;
this.boardSizeX = 20;
this.boardSizeY = 20;
this.manager = {};
}
SnakeGame.prototype.init = function(options){
options = options || {};
this.boardSizeX = options.boardSizeX || 20;
this.boardSizeY = options.boardSizeY || 20;
this.snake = options.snake || new Snake(this);
}
SnakeGame.prototype.setSnake = function(){
// sets snake to provided params
}
SnakeGame.prototype.generateBoard = function(){
this.board = [];
for (let i=0;i<this.boardSizeX;i++){
let boardRow=[];
for (let j = 0; j < this.boardSizeY; j++) {
let havePixel = false;
for (let k = 0; k<this.snake.body.length;k++){
if (this.snake.body[k].x === i && this.snake.body[k].y === j ){
havePixel = true;
}
}
if (havePixel) {
boardRow.push(1);
} else {
boardRow.push(0);
}
}
this.board.push(boardRow);
}
}
SnakeGame.prototype.setSpeed = function(speed){
this.speed = speed;
}
SnakeGame.prototype.setScore = function(score){
this.score = score;
}
let generateBlock = function(x,y,limitX,limitY){
let block = {};
if (x===limitX) {
block.x = 0;
} else if (x == -1) {
block.x = limitX-1;
} else {
block.x = x;
}
if (y===limitY) {
block.y = 0;
} else if (y == -1) {
block.y = limitY-1;
} else {
block.y = y;
}
return block;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
let genericDiv = function(color, border){
let returnDiv = document.createElement("div");
returnDiv.style.height = "10px";
returnDiv.style.width = "10px";
returnDiv.style.background = color;
returnDiv.style.border = border;
return returnDiv;
}
let snakeDiv = function(){
return genericDiv("lime", "1px solid #000000");
}
let emptyDiv = function(){
return genericDiv("black");
}
let appleDiv = function(){
return genericDiv("red");
}
function updateDOM(game) {
var el = document.getElementById("gameboard");
el.innerHTML = "";
el.style.position = "relative";
var scoreEl = document.getElementById("score");
scoreEl.innerText = game.score;
if (game.genApple) {
generateAppleNoCollision(game);
}
for (let i =0;i<game.board.length;i++){
let snakeRowDiv = document.createElement("div");
//snakeRowDiv.style.position = "absolute";
for (let j=0;j<game.board[i].length;j++){
let whichDiv = null;
if (game.board[i][j]){
whichDiv = snakeDiv();
} else if (i==game.apple.x && j == game.apple.y){
whichDiv = appleDiv();
}
if (whichDiv == null){
whichDiv = emptyDiv();
}
whichDiv.style.position = "absolute";
whichDiv.style.left = j * (parseInt(whichDiv.style.width)) + "px";
whichDiv.style.top = (i * (parseInt(whichDiv.style.height)) + 100) + "px";
snakeRowDiv.appendChild(whichDiv);
}
el.appendChild(snakeRowDiv);
}
}
function generateDomListener(game){
return function(event){
switch (event.key) {
case "ArrowUp":
if (game.snake.going != "DOWN"){
game.snake.going = "UP";
}
break;
case "ArrowDown":
if (game.snake.going != "UP"){
game.snake.going = "DOWN";
}
break;
case "ArrowLeft":
if (game.snake.going != "RIGHT") {
game.snake.going = "LEFT";
}
break;
case "ArrowRight":
if (game.snake.going != "LEFT") {
game.snake.going = "RIGHT";
}
break;
}
}
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function decreaseDifficulty(game){
if (game.speed <= 900) {
game.speed += 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function restart(game){
game.ended = false;
game.genApple = true;
game.score = 0;
game.speed = 500;
game.apple = {x:null,y:null}
game.snake.body = [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11},
]
game.snake.going = "RIGHT";
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function generateAppleNoCollision(game){
while(true){
game.apple.x = getRandomInt(0,game.board.length-1);
game.apple.y = getRandomInt(0,game.board.length-1);
let hasCollision = false;
for (let i = 0; i<game.snake.body.length;i++){
if(game.apple.x === game.snake.body[i].x &&
game.apple.y === game.snake.body[i].y) {
hasCollision = true;
}
}
if (!hasCollision) {
console.log("no collision, continuing with this apple")
break;
}
console.error("found collision, searching once more")
}
game.genApple = false;
}
function increaseDifficulty(game){
if (game.speed >= 100) {
game.speed -= 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function gameLoop(game){
return function(){
if (!game.ended) {
game.snake.go(game.snake.going);
game.generateBoard();
updateDOM(game);
} else {
clearInterval(gameLoopHandle);
alert ("GAME OVER");
}
}
}
function polling(game){
return function(){
var scriptsDiv = document.getElementById("scripts");
var script = document.createElement('script');
script.src="http://172.168.1.22/snake_relay/?command=get&callbackname=serverListener";
if (game.scripts) {
if (game.scripts.length == 100){
let msg = "too many scripts, clearing the div";
scriptsDiv.innerHTML = ""
}
game.scripts.push(script);
} else {
game.scripts = [script];
}
scriptsDiv.appendChild(script);
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var game = new SnakeGame();
_game =game;
game.init();
game.generateBoard()
updateDOM(game);
document.addEventListener("keydown", generateDomListener(game));
//pollingHandle = setInterval(polling(game), 100);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
})
<div id="gameboard"></div>
<div>
<h1>Score: <span id="score">0</span></h1>
<button onclick="increaseDifficulty(_game)">Increase difficulty</button>
<button onclick="decreaseDifficulty(_game)">Decrease difficulty</button>
<button onclick="restart(_game)">Restart</button>
</div>
<div id="scripts"></div>
You need to do the following
css:
#gameboard > div > div {
box-sizing: border-box;
}
And update snakeDiv as follows:
// pass extra parameter to track the snake blocks
let snakeDiv = function(){
return genericDiv("lime", 'snake');
}
// depending on the extra parameter add extra css property to snake blocks only
let genericDiv = function(color, snake){
let returnDiv = document.createElement("div");
returnDiv.style.height = "10px";
returnDiv.style.width = "10px";
returnDiv.style.background = color;
if(snake){
returnDiv.style.borderWidth = "1px";
returnDiv.style.borderColor = "black";
returnDiv.style.borderStyle = "solid";
}
return returnDiv;
}
Working fiddle:
let _game;
var gameLoopHandle;
var pollingHandle;
let Snake = function(forGame,startingDirection, startingBody){
this.going = startingDirection || "RIGHT";
this.go = function(direction){
let snakeHead = {x:this.getHead().x,y:this.getHead().y};
switch(direction.toLowerCase()){
case "left":
snakeHead.y--;
this.going = "LEFT";
break;
case "right":
snakeHead.y++;
this.going = "RIGHT";
break;
case "up":
snakeHead.x--;
this.going = "UP";
break;
case "down":
snakeHead.x++;
this.going = "DOWN";
break;
}
let newBlock =
generateBlock(snakeHead.x,snakeHead.y,
this.gameInstance.boardSizeX,this.gameInstance.boardSizeY);
if (this.posIsApple(newBlock)) {
this.gameInstance.score++;
this.gameInstance.genApple = true;
} else {
this.removeBockTailFromSnake();
}
if (this.posIsTail(newBlock)){
this.gameInstance.ended = true;
}
this.addBlockHeadToSnake(newBlock);
};
this.body = startingBody || [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11}
];
this.gameInstance = forGame;
this.getHead = function(){
return this.body[this.body.length-1];
};
this.posIsTail = function(pos){
for (let i = 0; i<this.body.length;i++){
if (pos.x === this.body[i].x && pos.y === this.body[i].y) {
return true;
}
}
return false;
};
this.posIsApple = function(pos){
return pos.x === this.gameInstance.apple.x && pos.y === this.gameInstance.apple.y;
};
this.addBlockHeadToSnake = function(block){
this.body.push(block);
}
this.removeBockTailFromSnake = function(){
this.body.shift();
}
}
let serverListener = function(keyEvents){
console.log(keyEvents);
for (let i = 0; i<keyEvents.length;i++) {
var event = new Event('keydown');
event.key="Arrow" + capitalizeFirstLetter(keyEvents[i].toLowerCase());
document.dispatchEvent(event);
}
}
let SnakeGame = function(){
this.board = [];
this.snake = {};
this.apple = {};
this.score = 0;
this.speed = 500;
this.ended = false;
this.genApple = true;
this.boardSizeX = 20;
this.boardSizeY = 20;
this.manager = {};
}
SnakeGame.prototype.init = function(options){
options = options || {};
this.boardSizeX = options.boardSizeX || 20;
this.boardSizeY = options.boardSizeY || 20;
this.snake = options.snake || new Snake(this);
}
SnakeGame.prototype.setSnake = function(){
// sets snake to provided params
}
SnakeGame.prototype.generateBoard = function(){
this.board = [];
for (let i=0;i<this.boardSizeX;i++){
let boardRow=[];
for (let j = 0; j < this.boardSizeY; j++) {
let havePixel = false;
for (let k = 0; k<this.snake.body.length;k++){
if (this.snake.body[k].x === i && this.snake.body[k].y === j ){
havePixel = true;
}
}
if (havePixel) {
boardRow.push(1);
} else {
boardRow.push(0);
}
}
this.board.push(boardRow);
}
}
SnakeGame.prototype.setSpeed = function(speed){
this.speed = speed;
}
SnakeGame.prototype.setScore = function(score){
this.score = score;
}
let generateBlock = function(x,y,limitX,limitY){
let block = {};
if (x===limitX) {
block.x = 0;
} else if (x == -1) {
block.x = limitX-1;
} else {
block.x = x;
}
if (y===limitY) {
block.y = 0;
} else if (y == -1) {
block.y = limitY-1;
} else {
block.y = y;
}
return block;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
let genericDiv = function(color, border){
let returnDiv = document.createElement("div");
returnDiv.style.height = "10px";
returnDiv.style.width = "10px";
returnDiv.style.background = color;
if(border){
returnDiv.style.borderWidth = "1px";
returnDiv.style.borderColor = "black";
returnDiv.style.borderStyle = "solid";
}
//returnDiv.style.border = border;
return returnDiv;
}
let snakeDiv = function(){
return genericDiv("lime", "1px solid #000000");
}
let emptyDiv = function(){
return genericDiv("black");
}
let appleDiv = function(){
return genericDiv("red");
}
function updateDOM(game) {
var el = document.getElementById("gameboard");
el.innerHTML = "";
el.style.position = "relative";
var scoreEl = document.getElementById("score");
scoreEl.innerText = game.score;
if (game.genApple) {
generateAppleNoCollision(game);
}
for (let i =0;i<game.board.length;i++){
let snakeRowDiv = document.createElement("div");
//snakeRowDiv.style.position = "absolute";
for (let j=0;j<game.board[i].length;j++){
let whichDiv = null;
if (game.board[i][j]){
whichDiv = snakeDiv();
} else if (i==game.apple.x && j == game.apple.y){
whichDiv = appleDiv();
}
if (whichDiv == null){
whichDiv = emptyDiv();
}
whichDiv.style.position = "absolute";
whichDiv.style.left = j * (parseInt(whichDiv.style.width)) + "px";
whichDiv.style.top = (i * (parseInt(whichDiv.style.height)) + 100) + "px";
snakeRowDiv.appendChild(whichDiv);
}
el.appendChild(snakeRowDiv);
}
}
function generateDomListener(game){
return function(event){
switch (event.key) {
case "ArrowUp":
if (game.snake.going != "DOWN"){
game.snake.going = "UP";
}
break;
case "ArrowDown":
if (game.snake.going != "UP"){
game.snake.going = "DOWN";
}
break;
case "ArrowLeft":
if (game.snake.going != "RIGHT") {
game.snake.going = "LEFT";
}
break;
case "ArrowRight":
if (game.snake.going != "LEFT") {
game.snake.going = "RIGHT";
}
break;
}
}
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function decreaseDifficulty(game){
if (game.speed <= 900) {
game.speed += 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function restart(game){
game.ended = false;
game.genApple = true;
game.score = 0;
game.speed = 500;
game.apple = {x:null,y:null}
game.snake.body = [
{x:9,y:8},
{x:9,y:9},
{x:9,y:10},
{x:9,y:11},
]
game.snake.going = "RIGHT";
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function generateAppleNoCollision(game){
while(true){
game.apple.x = getRandomInt(0,game.board.length-1);
game.apple.y = getRandomInt(0,game.board.length-1);
let hasCollision = false;
for (let i = 0; i<game.snake.body.length;i++){
if(game.apple.x === game.snake.body[i].x &&
game.apple.y === game.snake.body[i].y) {
hasCollision = true;
}
}
if (!hasCollision) {
console.log("no collision, continuing with this apple")
break;
}
console.error("found collision, searching once more")
}
game.genApple = false;
}
function increaseDifficulty(game){
if (game.speed >= 100) {
game.speed -= 50;
}
clearInterval(gameLoopHandle);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
}
function gameLoop(game){
return function(){
if (!game.ended) {
game.snake.go(game.snake.going);
game.generateBoard();
updateDOM(game);
} else {
clearInterval(gameLoopHandle);
alert ("GAME OVER");
}
}
}
function polling(game){
return function(){
var scriptsDiv = document.getElementById("scripts");
var script = document.createElement('script');
script.src="http://172.168.1.22/snake_relay/?command=get&callbackname=serverListener";
if (game.scripts) {
if (game.scripts.length == 100){
let msg = "too many scripts, clearing the div";
scriptsDiv.innerHTML = ""
}
game.scripts.push(script);
} else {
game.scripts = [script];
}
scriptsDiv.appendChild(script);
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var game = new SnakeGame();
_game =game;
game.init();
game.generateBoard()
updateDOM(game);
document.addEventListener("keydown", generateDomListener(game));
//pollingHandle = setInterval(polling(game), 100);
gameLoopHandle = setInterval(gameLoop(game), game.speed);
})
<div id="gameboard"></div>
<div>
<h1>Score: <span id="score">0</span></h1>
<button onclick="increaseDifficulty(_game)">Increase difficulty</button>
<button onclick="decreaseDifficulty(_game)">Decrease difficulty</button>
<button onclick="restart(_game)">Restart</button>
</div>
<div id="scripts"></div>
<style>
#gameboard > div > div {
box-sizing: border-box;
}
</style>

How to use AJAX or JSON in this code?

I am creating a website application that allows users to select a seat, if it is not already reserved, and reserve it.
I have created a very round about way of getting the seats that are previously reserved using iFrames, however that was temporarily, now I need to make it secure and "proper javascript code" using proper practices. I have no clue what AJAX (or JSON) is, nor how to add it to this code, but it needs to get the file "seatsReserved"+this.id(that is the date)+"Que.html" and compare the string of previously reserved seats to see which class to make the element. If this is horrible, or if any of the other things could work better, I am open to criticism to everything. Thank you all!
Here is the javascript code:
A little side note, all of the if statements are due to different amount of seats in each row
<script>
var i = " 0 ";
var counter = 0;
var leng=0;
document.getElementById("Show1").addEventListener("click", changeDay);
document.getElementById("Show2").addEventListener("click", changeDay);
document.getElementById("Show3").addEventListener("click", changeDay);
function changeDay() {
var iFrame = document.getElementById("seatList");
iFrame.src = "seatsReserved" + this.id + "Que.html";
document.getElementById('date').innerHTML = this.id;
var seatsTaken = iFrame.contentWindow.document.body.innerHTML;
var k = 0;
let = 'a';
var lc = 0;
for (lc = 1; lc <= 14; lc++) {
if (lc == 1) {
leng = 28;
}
else if (lc == 2) {
leng = 29;
}
else if (lc == 3) {
leng = 32;
}
else if (lc == 4 || lc == 6 || lc == 12 || lc == 14) {
leng = 33;
}
else if (lc == 5 || lc == 13) {
leng = 34;
}
else if (lc == 8 || lc == 10) {
leng = 35;
}
else {
leng = 36;
}
for (k = 1; k <= leng; k++) {
if (seatsTaken.indexOf((" " +
let +k + " ")) <= -1) {
seat = document.getElementById(let +k);
seat.removeEventListener("click", selectedSeat);
}
else {
document.getElementById(let +k).className = "openseat";
document.getElementById(let +k).removeEventListener("click", doNothing);
}
}
let = String.fromCharCode(let.charCodeAt(0) + 1);
}
}
function loadChanges() {
var iFrame = document.getElementById("seatList");
var seatsTaken = iFrame.contentWindow.document.body.innerHTML;
var k = 0;
let = 'a';
var lc = 0;
var leng = 0;
for (lc = 1; lc <= 14; lc++) {
if (lc == 1) {
leng = 28;
}
else if (lc == 2) {
leng = 29;
}
else if (lc == 3) {
leng = 32;
}
else if (lc == 4 || lc == 6 || lc == 12 || lc == 14) {
leng = 33;
}
else if (lc == 5 || lc == 13) {
leng = 34;
}
else if (lc == 8 || lc == 10) {
leng = 35;
}
else {
leng = 36;
}
for (k = 1; k <= leng; k++) {
if (seatsTaken.indexOf((" " +
let +k + " ")) <= -1) {
seat = document.getElementById(let +k);
seat.addEventListener("click", selectedSeat);
seat.className = "openseat";
}
else {
document.getElementById(let +k).className = "notAvailible";
document.getElementById(let +k).addEventListener("click", doNothing);
}
}
let = String.fromCharCode(let.charCodeAt(0) + 1);
}
i = " 0 ";
counter = 0;
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
document.getElementById("seatnums").innerHTML = counter;
}
i = document.getElementById("seatString").innerHTML;
counter = document.getElementById("seatnums").innerHTML;
function selectedSeat() {
var w = this.id;
var l = (" " + w);
var b = (" " + w + " ");
if (counter < 5) {
if (i.indexOf(b) <= 0) {
this.className = "closedseat";
i = i + b;
i = i.replace(" 0 ", " ");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter + 1;
document.getElementById("seatnums").innerHTML = counter;
}
else if (i.indexOf(b) > 0) {
this.className = "openseat";
i = i.replace(b, "");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter - 1;
document.getElementById("seatnums").innerHTML = counter;
}
}
else if (i.indexOf(b) > 0) {
this.className = "openseat";
i = i.replace(b, "");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter - 1;
document.getElementById("seatnums").innerHTML = counter;
}
}
function doNothing() {
}
var rannum = Math.random() * 1000;
document.getElementById('getConfirmation').value = rannum;
</script>

Javascript Check variable.Then gain ++ per second

I have a problem i want to check a variable.If its 0 then gain ++ after 1.5s.If its 10 then gain ++ after .4s.Its complicated.It doesnt really work.My code so far:
if(road == 1){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1400);}
else if(road == 2){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1300);}
else if(road == 3){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1200);}
else if(road == 4){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1100);}
else if(road == 5){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1000);}
else if(road == 6){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},900);}
else if(road == 7){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},800);}
else if(road == 8){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},600);}
else if(road == 9){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},400);}
else if(road == 10){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},200);}
else{setInterval(function(){stamina++;document.getElementById("stamina").innerHTML = stamina;},1500);}
And the code to build a road is this:
function build_road() {
if ((wood + tavern) >= 29 && stone > 4 && road < 10) {
road++;
document.getElementById("road_count").innerHTML = road;
wood = (wood + tavern) - 20;
stone = stone - 5;
document.getElementById("wood").innerHTML = wood;
document.getElementById("stone").innerHTML = stone;
exp = exp + 20;
var x = document.getElementById("PROGRESS");
x.setAttribute("value", exp);
x.setAttribute("max", max);
if (exp == 100) {
exp = 0;
level++;
document.getElementById("level").innerHTML = level;
}
alert("Congratulations,You've create a Road,Now you gain stamina slightly faster.");
}
else {
alert("You need: 30Wood,5Stone .Maximum 10 Roads.")
}
}
Make reusable functions (it's often a good practice, when you a difficulties with a piece of code, to break it into small functions):
var staminaIncreaseTimer = null;
function configureStaminaIncrease(delay) {
if (staminaIncreaseTimer !== null)
clearInterval(staminaIncreaseTimer);
staminaIncreaseTimer = setInterval(function () {
increaseStamina();
}, delay);
}
function increaseStamina() {
stamina += 1;
document.getElementById("stamina").innerHTML = stamina;
}
Solution with an array (suggested by Jay Harris)
var roadIndex = road-1;
var ROAD_DELAYS = [1400, 1300, 1200, /*...*/];
var DEFAULT_DELAY = 1500;
if (roadIndex < ROAD_DELAYS.length) {
configureStaminaIncrease(ROAD_DELAYS[roadIndex]);
} else {
configureStaminaIncrease(DEFAULT_DELAY);
}
Solution with a switch instead of you if-elseif mess:
switch (road) {
case 1:
configureStaminaIncrease(1400);
break;
case 2:
configureStaminaIncrease(1300);
break;
case 3:
configureStaminaIncrease(1200);
break;
//and so on...
default:
configureStaminaIncrease(1500);
}

Problems writing script for blackjack game

I'm trying to write a script for a Black Jack game but have run into some problems. This is the code I've included in the head:
<script type="text/javascript">
var J = 10;
var Q = 10;
var K = 10;
var A = 11;
var deck = [1,2,3,4,5,6,7,8,9,10,J,Q,K,A];
function deal() {
var test = "hello";
var f_card = Math.floor(Math.random() * deck.length);
var s_card = Math.floor(Math.random() * deck.length);
var card1 = deck[f_card];
var card2 = deck[s_card];
if (card1 == J) {
card1 = "Jack";
}
else if (card1 == Q) {
card1 = "Queen";
}
else if (card1 == K) {
card1 = "King"
}
else if (card1 == A) {
card1 = "Ace"
}
if (card2 == J) {
card2 = "Jack";
}
else if (card2 == Q) {
card2 = "Queen";
}
else if (card2 == K) {
card2 = "King"
}
else if (card2 == A) {
card2 = "Ace"
}
var bucket = card1 + ", " + card2;
var res = f_card + s_card
document.getElementById("result").innerHTML = bucket;
document.getElementById("test").innerHTML = f_card + ", " + s_card;
if (res == 22) {
alert("Blackjack!")
}
}
</script>
The body reads as follows:
<body>
<form>
<input type="button" value ="Deal" onclick="deal()" /><br /><br />
</form>
<div id = "result">
</div><br />
<div id = "test">
</div>
</body>
I added the "test" div to see what was happening inside the deal, and it looks like "Jack" is being assigned to all array value above 9. How can I have the other if statements processed as well? Any help at all would be much appreciated.
Put your J,Q,K,A in quotes:
var deck = [1,2,3,4,5,6,7,8,9,10,'J','Q','K','A'];
if (card1 == 'J') {
card1 = "Jack";
}
etc..
if (card1 == J) {
card1 = "Jack";
}
else if (card1 == Q) {
card1 = "Queen";
}
else if (card1 == K) {
card1 = "King"
}
Lets say you have a card == 10 (Jack / Queen / King)
You test with ifs.
the first if is hit because 10 == J
Even if it is a Queen / King (which also == 10)
Because the Jack is hit in the if statement the other ifs dont get run
Instead of card1 and card2 in if else ladder use "original card ID", ie
switch (f_card){
case 10: card1 = "Jack";
break;
case 11: card1 = "Queen";
break;
case 12: card1 = "King";
break;
case 13: card1 = "Ace";
break;
}

Categories

Resources