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>
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>
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>
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);
}
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;
}