SetInterval not incrementing from interval - javascript

haha = 0;
function dodat(){
haha++;
code here...
}
setInterval(function(){
dodat();
}, 1500-haha);
It is strange, it doesn't seem like time is actually getting added to the setinterval...
Here is my code, SetInterval starts on line 57, function dodat():
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<!DOCTYPE html>
<body onkeypress="pretend();">
<span id="money">25</span>$ - <span id="lives">100</span>/100 lives
<br><br>
<span style="background-color:#2cafe4;cursor:pointer;width:1000px;height:175px;overflow:hidden;position:relative;display:block;" id="track"></span>
<br>
<span id="divthing" style="position:relative;display:block;"></span>
<script>
money = 25;
lives = 100;
mycars = {};
original = 0;
function doofus() {
if($("div:first").offset().left > 1000){
$("div:first").remove();
lives = lives-1;
document.getElementById("lives").innerHTML = lives;
}
}
haha = 0;
function dodat() {
haha = haha+100;
var btn = document.createElement("div");
anyArray = new Array('http://i44.tinypic.com/i4l1r8.png', 'http://i41.tinypic.com/nxs4k8.jpg');
function randOrd(){
return (Math.round(Math.random())-0.5); }
anyArray.sort(randOrd);
btn.innerHTML="<img src='"+anyArray+"' style='height:60px;'>";
btn.style.position = "absolute";
btn.style.left = "0px";
var numba = Math.round(Math.random() * 50);
btn.class = "haha";
btn.id = numba;
mycars[numba] = -50;
var move = function () {
mycars[numba] = mycars[numba] + 1.5;
document.getElementById(numba).style.left = mycars[numba] + "px";
if(mycars[numba] > 100 && mycars[numba] < 150){
document.getElementById(numba).style.top = mycars[numba]/0.5-200 + "px";
}
};
setInterval(move, 10);
document.getElementById("track").appendChild(btn);
}
setInterval(function(){
dodat();
}, 1500-haha);
setInterval(doofus, 200);
function dis1() {
$("#shoot1").css("background-color", "red");
setTimeout('$("#shoot1").css("background-color", "blue");', '1000');
compareEl = $("#shoot1");
// Let's find the closest block!
var otherEls = $('div'),
compareTop = compareEl.offset().top,
compareLeft = compareEl.offset().left,
winningScore = Infinity,
score, winner, curEl;
otherEls.each(function () {
// Calculate the score of this element
curEl = $(this);
score = Math.abs(curEl.offset().left - compareLeft);
if (score < winningScore) {
winningScore = score;
winner = this;
}
});
$("#"+winner.id+"").remove();
money = money+1;
document.getElementById("money").innerHTML=""+money+"";
}
function dis2() {
$("#shoot2").css("background-color", "red");
setTimeout('$("#shoot2").css("background-color", "blue");', '1000');
compareEl2 = $("#shoot2");
// Let's find the closest block!
var otherEls2 = $('div'),
compareTop2 = compareEl2.offset().top,
compareLeft2 = compareEl2.offset().left,
winningScore2 = Infinity,
score2, winner2, curEl2;
otherEls2.each(function () {
// Calculate the score of this element
curEl2 = $(this);
score2 = Math.abs(curEl2.offset().left - compareLeft2);
if (score2 < winningScore2) {
winningScore2 = score2;
winner2 = this;
}
});
$("#"+winner2.id+"").remove();
money = money+1;
document.getElementById("money").innerHTML=""+money+"";
}
function dis3() {
$("#shoot3").css("background-color", "red");
setTimeout('$("#shoot3").css("background-color", "blue");', '1000');
compareEl3 = $("#shoot3");
// Let's find the closest block!
var otherEls3 = $('div'),
compareTop3 = compareEl3.offset().top,
compareLeft3 = compareEl3.offset().left,
winningScore3 = Infinity,
score3, winner3, curEl3;
otherEls3.each(function () {
// Calculate the score of this element
curEl3 = $(this);
score3 = Math.abs(curEl3.offset().left - compareLeft3);
if (score3 < winningScore3) {
winningScore3 = score3;
winner3 = this;
}
});
$("#"+winner3.id+"").remove();
money = money+1;
document.getElementById("money").innerHTML=""+money+"";
}
function dis4() {
$("#shoot4").css("background-color", "red");
setTimeout('$("#shoot4").css("background-color", "blue");', '1000');
compareEl4 = $("#shoot4");
// Let's find the closest block!
var otherEls4 = $('div'),
compareTop4 = compareEl4.offset().top,
compareLeft4 = compareEl4.offset().left,
winningScore4 = Infinity,
score4, winner4, curEl4;
otherEls4.each(function () {
// Calculate the score of this element
curEl4 = $(this);
score4 = Math.abs(curEl4.offset().left - compareLeft4);
if (score4 < winningScore4) {
winningScore4 = score4;
winner4 = this;
}
});
$("#"+winner4.id+"").remove();
money = money+1;
document.getElementById("money").innerHTML=""+money+"";
}
function dis5() {
$("#shoot5").css("background-color", "red");
setTimeout('$("#shoot4").css("background-color", "blue");', '1000');
compareEl5 = $("#shoot5");
// Let's find the closest block!
var otherEls5 = $('div'),
compareTop5 = compareEl5.offset().top,
compareLeft5 = compareEl5.offset().left,
winningScore5 = Infinity,
score5, winner5, curEl5;
otherEls5.each(function () {
// Calculate the score of this element
curEl5 = $(this);
score5 = Math.abs(curEl5.offset().left - compareLeft5);
if (score5 < winningScore5) {
winningScore5 = score5;
winner5 = this;
}
});
$("#"+winner5.id+"").remove();
money = money+1;
document.getElementById("money").innerHTML=""+money+"";
}
function whatareyousingingpatrick(){
if(money >= 15){
money = money-15;
original = original+1;
setInterval("dis"+original+"();", 2400);
var btn = document.createElement("shooter");
btn.style.display = "block";
btn.id = "shoot"+original+"";
btn.style.height = "25px";
btn.style.width = "25px";
btn.style.backgroundColor = "blue";
btn.innerHTML = "<img src='http://www.bubblews.com/assets/images/news/1317280976_1370202845.png' style='height:100%;width:100%;border-radius:100%;opacity:0.7;'>";
btn.style.borderRadius= "100%";
btn.style.boxShadow= "0px 0px 200px 75px rgba(0, 0, 0, 0.2)";
btn.style.position = "absolute";
btn.style.left = event.pageX-8;
btn.style.top = event.pageY-44;
document.getElementById("track").appendChild(btn);
}
else{
alert("Sorry, this dude costs 15 bucks.");
}
}
function whatareyousingingpatrick2(){
if(money >= 25){
money = money-25;
original = original+1;
setInterval("dis"+original+"();", 2000);
var btn = document.createElement("shooter");
btn.style.display = "block";
btn.id = "shoot"+original+"";
btn.style.height = "25px";
btn.style.width = "25px";
btn.style.backgroundColor = "blue";
btn.innerHTML = "<img src='http://static3.wikia.nocookie.net/__cb62439/xwing-miniatures/images/thumb/1/18/Missile_Icon.png/100px-0,111,0,110-Missile_Icon.png' style='height:100%;width:100%;border-radius:100%;opacity:0.7;'>";
btn.style.borderRadius= "100%";
btn.style.boxShadow= "0px 0px 200px 75px rgba(0, 0, 0, 0.2)";
btn.style.position = "absolute";
btn.style.left = event.pageX-8;
btn.style.top = event.pageY-44;
document.getElementById("track").appendChild(btn);
}
else{
alert("Sorry, this dude costs 25 bucks.");
}
}
function pretend(){
if (event.keyCode == 13) {
if(money >= 5){
money = money-5;
$("div").hide();
alert("You have bought the INSTANT KILL feature. Note that you can purchase this feature an unlimited number of times.");
}
else
{
alert("Sorry, the cost of the INSTANT KILL feature is 5$");
}
}
if (event.keyCode == 49) {
if(money >= 40){
money = money-40;
alert("You have bought the FASTER SHOOTING upgrade for your first missile. Note that you can purchase this upgrade an unlimited number of times.");
setInterval("dis1();", "8000");
}
else
{
alert("Sorry, the cost of the FASTER SHOOTING upgrade for this missile is 40$");
}
}
if (event.keyCode == 50) {
if(money >= 40){
money = money-40;
alert("You have bought the FASTER SHOOTING upgrade for your second missile. Note that you can purchase this upgrade an unlimited number of times.");
setInterval("dis2();", "8000");
}
else
{
alert("Sorry, the cost of the FASTER SHOOTING upgrade for this missile is 40$");
}
}
if (event.keyCode == 51) {
if(money >= 40){
money = money-40;
alert("You have bought the FASTER SHOOTING upgrade for your third missile. Note that you can purchase this upgrade an unlimited number of times.");
setInterval("dis3();", "8000");
}
else
{
alert("Sorry, the cost of the FASTER SHOOTING upgrade for this missile is 40$");
}
}
if (event.keyCode == 52) {
if(money >= 40){
money = money-40;
alert("You have bought the FASTER SHOOTING upgrade for your fourth missile. Note that you can purchase this upgrade an unlimited number of times.");
setInterval("dis4();", "8000");
}
else
{
alert("Sorry, the cost of the FASTER SHOOTING upgrade for this missile is 40$");
}
}
}
</script>
<br><br>
<button onclick='$("#track").on("click", function() { whatareyousingingpatrick(); });'>
Get sniper for 15$
</button>
<br>
<button onclick='$("#track").on("click", function() { whatareyousingingpatrick2(); });'>
Get bomb for 25$
</button>

In
setInterval(function(){
dodat();
}, 1500-haha);
The 1500-haha part is only evaluated once, which means the -haha is useless.
If you want the interval to reduce at each call, you might use setTimeout :
(function doone(){
dodat();
setTimeout(doone, 1500-haha); // a halting condition here would be nice
})();

The setInterval will only read that value once. If you want to read it again you have to clear the interval and re-start it.
Something like:
var theInterval = setInterval(function () {
dodat();
}, 1500);
setInterval(doofus, 200);
function reSetIntevar(value) {
clearInterval(theInterval);
theInterval = setInterval(function () {
dodat();
}, 1500 - value);
setInterval(doofus, 200);
}

Related

How to create a dynamic progress bar forwards and backwards with the button controls stop and resume?

I am trying to create a dynamic progress bar forwards and backward with the button controls to stop and resume, how to add the logic to the function? Thanks!
//PROGRESS
function updateBar() {
if (i == 0) {
i = 1;
let filling = document.querySelector(".progress-filling");
let width = 0;
setInterval(update, 5);
function update() {
if (width <= 100) {
width++;
filling.style.width = width + "%";
} else {
width--;
filling.style.width = width + "%";
}
}
}
}
You need to check status of your button (i) inside the update loop and do nothing if it's stopped:
//PROGRESS
let btn = document.querySelector(".btn");
btn.textContent = "STOP";
btn.addEventListener("click", changeInnerHTML);
function changeInnerHTML() {
btn.textContent = btn.textContent === "STOP" ? "RESUME" : "STOP";
if (btn.textContent === "RESUME") {
i = 0;
} else if (btn.textContent === "STOP") {
i = 1;
}
}
let i = 1;
updateBar();
function updateBar() {
let filling = document.querySelector(".progress-filling");
let width = 0;
let step = 1;
setInterval(update, 5);
function update() {
if (!i)
return;
width += step;
filling.style.width = width + "%";
if (width >= 100 || width <= 0)
step = -step; //reverse
}
}
.progress-filling
{
height: 2em;
border: 1px solid black;
background-color: lightgreen;
}
<button class="btn">STOP</button>
<div class="progress-filling"></div>
I used progress element here u can use your wdth etc.... But Checkout the logic I think it's what you are looking for !
<progress id="progress" min="0" max="100" value="0"></progress>
<button id="progress-ctrl">START</button>
<button id="progress-stop">STOP</button>
Js
const progress = document.querySelector('#progress');
const button = document.querySelector('#progress-ctrl');
const sbutton = document.querySelector('#progress-stop');
let interval;
const time = 50; //in ms
button.addEventListener('click', (e)=> {
const text = button.innerText.toLowerCase();
switch (text) {
case 'start':
start();
button.innerText = "PAUSE";
break;
case 'pause':
pause()
button.innerText = "RESUME";
break;
case 'resume':
resume()
button.innerText = "PAUSE";
break;
default:
// nothing to do
}
});
sbutton.addEventListener('click', (e)=> {
sbutton.innerText = "STOPPED";
button.innerText = "START";
stop();
});
function start() {
interval = setInterval(function() {
progress.value += 1
}, time);
sbutton.innerText = "STOP";
}
function pause() {
clearInterval(interval);
}
function resume() {
interval = setInterval(function () {
progress.value += 1
}, time);
}
function stop() {
clearInterval(interval);
progress.value = 0;
}
```

Make movement more smooth on Java Script Game | JavaScript Canvas

I am working on very simple java script game. there's a falling random object (trash) and another object for catch the falling object (trash bin). everything seems fine but i wanted to make the movement of the trash bin more smooth. Do you have any idea to fix this? Thanks in Advance
this is my code
window.onload = function(){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var canvasBack = document.getElementById("backgroundCanvas");
var contextBack = canvasBack.getContext("2d");
var timer;
//mengatur hiscore
var hiscore = 0;
//Background image, musik and arrays musik.
var background = new Image();
background.src = 'assets/bgw2.jpg';
var catchSounds = [];
var catchSoundCounter = 0;
for(var i = 0; i < 5; i++)
{
var catchSound = new Audio();
catchSound.src = 'Audio/bleep.wav';
catchSounds.push(catchSound);
}
var music = new Audio();
music.src = 'Audio/MarimbaBoy.wav';
music.loop = true;
var smashSounds = [];
var smashCounter = 0;
for(var i = 0; i < 5; i++)
{
var smash = new Audio();
smash.src = 'Audio/smash.mp3';
smashSounds.push(smash);
}
var player;
var fruits = [];
var numberOfFruits = 15;
//Player constructor
function Player()
{
this.gameOver = false;
this.score = 0;
this.fruitsCollected = 0;
this.fruitsMissed = 0;
this.playerWidth = 150;
this.playerHeight = 90;
this.playerSpeed = 10;
this.x = canvas.width / 2;
this.y = canvas.height - this.playerHeight;
this.playerImage = new Image();
this.playerImage.src = 'assets/binn.png';
//Draws the player
this.render = function()
{
context.drawImage(this.playerImage, this.x, this.y);
}
//Moves the player left
this.moveLeft = function()
{
if(this.x > 0)
{
this.x -= this.playerSpeed;
}
}
//Moves the player right
this.moveRight = function()
{
if(this.x < canvas.width - this.playerWidth)
{
this.x += this.playerSpeed;
}
}
}
//Fruit constructor
function Fruit()
{
this.fruitNumber = Math.floor(Math.random() * 5);
this.fruitType = "";
this.fruitScore = 0;
this.fruitWidth = 50;
this.fruitHeight = 50;
this.fruitImage = new Image();
this.fruitSpeed = Math.floor(Math.random() * 2 + 1);
this.x = Math.random() * (canvas.width - this.fruitWidth);
this.y = Math.random() * -canvas.height - this.fruitHeight;
//Creates a different kind of fruit depending on the fruit number
//which is generated randomly
this.chooseFruit = function()
{
if(this.fruitNumber == 0)
{
this.fruitType = "pisang";
this.fruitScore = 5 * this.fruitSpeed;
this.fruitImage.src = 'assets/pisang.png';
}
else if(this.fruitNumber == 1)
{
this.fruitType = "rubbish";
this.fruitScore = 10 * this.fruitSpeed;
this.fruitImage.src = 'assets/rubbish.png';
}
else if(this.fruitNumber == 2)
{
this.fruitType = "botol";
this.fruitScore = 15 * this.fruitSpeed;
this.fruitImage.src = 'assets/botol.png';
}
else if(this.fruitNumber == 3)
{
this.fruitType = "coke";
this.fruitScore = 20 * this.fruitSpeed;
this.fruitImage.src = 'assets/coke.png';
}
else if(this.fruitNumber == 4)
{
this.fruitType = "apple";
this.fruitScore = 25 * this.fruitSpeed;
this.fruitImage.src = 'assets/apple.png';
}
else if(this.fruitNumber == 5)
{
this.fruitType = "papikra";
this.fruitScore = 30 * this.fruitSpeed;
this.fruitImage.src = 'assets/papikra.png';
}
}
//Makes the fruit descend.
//While falling checks if the fruit has been caught by the player
//Or if it hit the floor.
this.fall = function()
{
if(this.y < canvas.height - this.fruitHeight)
{
this.y += this.fruitSpeed;
}
else
{
smashSounds[smashCounter].play();
if(smashCounter == 4)
{
smashCounter = 0;
}
else
{
smashCounter++;
}
player.fruitsMissed += 1;
this.changeState();
this.chooseFruit();
}
this.checkIfCaught();
}
//Checks if the fruit has been caught by the player
//If it is caught, the player score and fruit counter is increased, and
//the current fruit changes its state and becomes a different fruit.
this.checkIfCaught = function()
{
if(this.y >= player.y)
{
if((this.x > player.x && this.x < (player.x + player.playerWidth)) ||
(this.x + this.fruitWidth > player.x && this.x + this.fruitWidth < (player.x + player.playerWidth)))
{
catchSounds[catchSoundCounter].play();
if(catchSoundCounter == 4)
{
catchSoundCounter = 0;
}
else
{
catchSoundCounter++;
}
player.score += this.fruitScore;
player.fruitsCollected += 1;
this.changeState();
this.chooseFruit();
}
}
}
//Randomly updates the fruit speed, fruit number, which defines the type of fruit
//And also changes its x and y position on the canvas.
this.changeState = function()
{
this.fruitNumber = Math.floor(Math.random() * 5);
this.fruitSpeed = Math.floor(Math.random() * 2 + 1);
this.x = Math.random() * (canvas.width - this.fruitWidth);
this.y = Math.random() * -canvas.height - this.fruitHeight;
}
//Draws the fruit.
this.render = function()
{
context.drawImage(this.fruitImage, this.x, this.y);
}
}
//Adds controls. Left arrow to move left, right arrow to move right.
//ENTER to restart only works at the game over screen.
window.addEventListener("keydown", function(e){
e.preventDefault();
if(e.keyCode == 37)
{
player.moveLeft();
}
else if(e.keyCode == 39)
{
player.moveRight();
}
else if(e.keyCode == 13 && player.gameOver == true)
{
main();
window.clearTimeout(timer);
}
});
main();
//Fills an array of fruits, creates a player and starts the game
function main()
{
contextBack.font = "bold 20px Dominique";
contextBack.fillStyle = "WHITE";
player = new Player();
fruits = [];
for(var i = 0; i < numberOfFruits; i++)
{
var fruit = new Fruit();
fruit.chooseFruit();
fruits.push(fruit);
}
startGame();
}
function startGame()
{
updateGame();
window.requestAnimationFrame(drawGame);
}
//Checks for gameOver and makes each fruit in the array fall down.
function updateGame()
{
music.play();
if(player.fruitsMissed >= 10)
{
player.gameOver = true;
}
for(var j = 0; j < fruits.length; j++)
{
fruits[j].fall();
}
timer = window.setTimeout(updateGame, 30);
}
//Draws the player and fruits on the screen as well as info in the HUD.
function drawGame()
{
if(player.gameOver == false)
{
context.clearRect(0, 0, canvas.width, canvas.height);
contextBack.clearRect(0, 0, canvasBack.width, canvasBack.height);
contextBack.drawImage(background, 0, 0);
player.render();
for(var j = 0; j < fruits.length; j++)
{
fruits[j].render();
}
contextBack.fillText("SCORE: " + player.score, 30, 50);
contextBack.fillText("HIGHEST SCORE: " + hiscore, 140, 50);
contextBack.fillText("FRUIT CAUGHT: " + player.fruitsCollected, 320, 50);
contextBack.fillText("FRUIT MISSED: " + player.fruitsMissed, 490, 50);
}
else
{
//Different screen for game over.
for(var i = 0; i < numberOfFruits; i++)
{
console.log("Speed was" + fruits[fruits.length - 1].fruitSpeed);
fruits.pop();
}
if(hiscore < player.score)
{
hiscore = player.score;
contextBack.fillText("NEW HI SCORE: " + hiscore, (canvas.width / 2) - 80, canvas.height / 2);
}
contextBack.fillText("PRESS ENTER TO RESTART", (canvas.width / 2) - 100, canvas.height / 2 + 50);
context.clearRect(0, 0, canvas.width, canvas.height);
}
window.requestAnimationFrame(drawGame);
}
}
First of all, just use one requestAnimationFrame and no other setTimeout code. These can start to run out of sync with each other and it's hard to pause them all when the player wants to pause the game.
Instead, use a counter instead of timeout.
let fruitCounter = 0
function drawGame() {
// all your draw code here
...
// every 60 frames drop a new fruit
fruitCounter++
if(fruitCounter > 60){
fruitCounter = 0
dropNewFruit()
}
// request the new frame unless its game over
if(!gameOver) {
requestAnimationFrame(drawGame)
}
}
Also, if you use keyboard events like this, it will always be choppy because there is a delay when typing on the keyboard (just press a letter for a long time in a text field, you will see that it takes a while until more letters appear)
You can fix this by setting a variable once a key gets pressed.
window.addEventListener("keydown", function(e){
if(e.keyCode == 37){
moveLeft = 1
}
}
window.addEventListener("keyup", function(e){
if(e.keyCode == 37){
moveLeft = 0
}
}
Then, you can use that variable in your animation code
function drawGame() {
// all your draw code here
player.x += moveLeft
// request the new frame unless its game over
if(!gameOver) {
requestAnimationFrame(drawGame)
}
}
These are just a few tips! This has always worked for me when I build a javascript game.

Calculate the score for Memory Game based on number of turns , time and matches

I'm developing a memory game and i need to calculate the fair score for the game, based on:
number of tries,
time and
number of matches
So, i tried using a function to calculate the score, but when i tried to display the score in the winning screen, the score do not appear. Help me out with this
the variables are
var matches = 0;
var moves = 0;
var counter = document.querySelector(".moves");
To check for the matches:
for (i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function (e) {
var turnable = e.target.dataset.turnable;
//first click
if (!wait && lastKnownButtonId == undefined && lastKnownButtonNumber == undefined && turnable == 'true') {
e.target.dataset.turnable = 'false';
e.target.innerHTML = getgImage(event.target.dataset.number);
e.target.style.backgroundColor = 'yellow';
lastKnownButtonId = e.target.id;
lastKnownButtonNumber = e.target.dataset.number;
}
//second click
else if (!wait && lastKnownButtonId != undefined && lastKnownButtonNumber != undefined && turnable == 'true' && e.target.id != lastKnownButtonId) {
e.target.dataset.turnable = 'false';
e.target.innerHTML = getgImage(event.target.dataset.number);
//match
if (e.target.dataset.number == lastKnownButtonNumber) {
e.target.style.backgroundColor = '#00FF7F';
document.getElementById(lastKnownButtonId).style.backgroundColor = '#00FF7F';
lastKnownButtonId = undefined;
lastKnownButtonNumber = undefined;
matches++;
if (matches == 8) {
document.getElementById("finalMove").innerHTML = moves;
showWinScreen();
//clearTimeout(timeoutHandle);
}
}
//no match
else {
document.getElementById(lastKnownButtonId).style.backgroundColor = 'red';
e.target.style.backgroundColor = 'red';
wait = true;
setTimeout(() => {
e.target.dataset.turnable = 'true';
e.target.style.backgroundColor = 'white'
e.target.innerHTML = getgImage(0);
var tempLastClickedButton = document.getElementById(lastKnownButtonId);
tempLastClickedButton.dataset.turnable = 'true';
tempLastClickedButton.style.backgroundColor = 'white';
tempLastClickedButton.innerHTML = getgImage(0);
lastKnownButtonId = undefined;
lastKnownButtonNumber = undefined;
wait = false;
}, 1000);
}
moveCounter();
}
});
}
i have inserted a function to calculate the score
function calcScore(){
var tilesbonus = (16 - matches) * 20; // 20 points for each successful tile
var timebonus = (60 - finaltime) * 8; // 8 points for each second
var triesbonus = (48 - moves) * 10; // (deduct) 10 points for each try
if (tilesbonus <0) { tilesbonus = 0; }
if (timebonus <0) { timebonus = 0; }
if (triesbonus <0) { triesbonus = 0; }
var totalscore= tilesbonus + timebonus + triesbonus;
return totalscore;
}
The function for timer:
window.onload = function() {
var timeoutHandle;
function countdown(minutes, seconds) {
function tick() {
var timecounter = document.getElementById("timer");
timecounter.innerHTML = minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
seconds--;
if (seconds >= 0) {
timeoutHandle = setTimeout(tick, 1000);
} else {
if (minutes >= 1) {
setTimeout(function () {
countdown(minutes - 1, 59);
}, 1000);
}
}
if (seconds==0 && minutes ==0){
alert("Game over");
//reset();
}
if (matches==8){
var totalscore = calcScore();
clearTimeout(timeoutHandle);
var finaltime= timecounter.innerHTML;
document.getElementById("seconds").innerHTML= finaltime;
document.getElementById("score").innerHTML=totalscore;
}
}
tick();
}
countdown(1, 00); }
the Move counter:
function moveCounter(){
moves++;
counter.innerHTML = moves;
}
the calscore() function is called when the game ends
if (matches==8){
calcScore();
clearTimeout(timeoutHandle);
var finaltime= timecounter.innerHTML;
document.getElementById("seconds").innerHTML= finaltime;
document.getElementById("score").innerHTML=totalscore;
document.getElementById("finalMove").innerHTML = moves;
}
The html code where the score should appear is :
<p><font size= "5">Your score: <span id=score> </span></font></p>
It's because you try to use a variables defined in a fonction from the global scope
here's an explanation of javascript scopes
basically if you declare a variable inside a fonction you can't use it outside of it
corrected and commented your code about this specific problem
var matches = 8
var finaltime = 42
var moves = 13
function calcScore(){
var tilesbonus = (16 - matches) * 20; // 20 points for each successful tile
var timebonus = (60 - finaltime) * 8; // 8 points for each second
var triesbonus = (48 - moves) * 10; // (deduct) 10 points for each try
if (tilesbonus <0) { tilesbonus = 0; }
if (timebonus <0) { timebonus = 0; }
if (triesbonus <0) { triesbonus = 0; }
var totalscore= tilesbonus + timebonus + triesbonus; // you defined the variable here
return totalscore;
} // totalscore is destroyed after the end of the function
if (matches==8){
var totalscore = calcScore(); // I modified this line and now it works
// I declare a new variable which contains the value returned by calcScore
clearTimeout(null); // i don't have the timeout var so I can't clear it
var finaltime= timecounter.innerHTML;
document.getElementById("seconds").innerHTML= finaltime;
document.getElementById("score").innerHTML=totalscore; // finally use the variable
}
<p><font size= "5">Your score: <span id=score> </span></font></p>
<p><font size= "5">finalTime: <span id=seconds> </span></font></p>
<span id=timecounter>42</span>

How to determine what JavaScript causes a browser crash?

I'm brand new to JavaScript, and have a crashing application. I have no idea what would cause the crash.
Here is the code:
<script>
//constants
var Col = 20, Rows = 20;
var cellHeight = 25;
var cellWidth = 25;
var foodX;
var score;
var foodY;
var Nothing = 0, Snake = 1, Food = 2;
var Left = 37, Up = 38, Right = 39, Down = 40;
var canvas = document.getElementById('snakeCanvas');
var context = canvas.getContext('2d');
var dead = "false";
var snakeDirection = null;
var keystate;
var snake = [];
function start() //this is where we begin the long journey
{
init();
Tick();
}
function init() {
snake = [{ x: 5, y: 5 }];
snakeDirection = null;
score = 0;
document.getElementById("score").innerHTML = "Score: " + score;
setFood();
keystate = null;
}
function Tick() // just liker a timer tick
{
document.addEventListener("keydown", function (evt) {
keystate = evt.keyCode; // checks key presses
});
//document.addEventListener("keyup", function (evt) {
//delete keystate[evt.keyCode];
//});
update(); //after we check for a key press we update alllll the
stuff
setTimeout(Tick, 300);
//}
}
function update()
{
checkKey(); // checks what key has been pressed
for (var i = snake.length-1; i > 0; i--) {
snake[i].y = snake[i-1].y;
snake[i].x = snake[i-1].x
}
switch (snakeDirection) { // keys
case "DOWN":
snake[0].y++;
break;
case "UP":
snake[0].y--;
break;
case "RIGHT":
snake[0].x++;
break;
case "LEFT":
snake[0].x--;
break;
}
draw(); //draws all the stuff like food and snake
checkCollisions(); // self explaintory name
}
function checkKey() //Change the direction of the snake cant go
backwards too
{
if (keystate == Left && snakeDirection != "RIGHT" )
{
snakeDirection = "LEFT";
}
if (keystate == Up && snakeDirection != "DOWN")
{
snakeDirection = "UP";
}
if (keystate == Right && snakeDirection != "LEFT")
{
snakeDirection = "RIGHT";
}
if (keystate == Down && snakeDirection != "UP")
{
snakeDirection = "DOWN";
}
}
function setFood()
{ //WE ARE RUNNING OUT OF FOOD WE NEED NEW PROVISIONS
var next = "true"
do {
foodX = Math.floor((Math.random() * Rows));
foodY = Math.floor((Math.random() * Col));
for (var i = 0; i < snake.length; i++) { // IT SUCKS WHEN I
CANT EAT FOOD BECAUSE ITS ALREADY INSIDE OF ME
if (snake[i].x == foodX && snake[i].y == foodY) {
next = "false"
}
}
}
while (next == "false")
draw(); // Pretty pictures
}
function checkCollisions()
{
for (var i = 1; i < snake.length; i++) { // STOP hitting
yourself
if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) {
init();
}
}
if (snake[0].y < 0 || snake[0].y > Rows || snake[0].x < 0 ||
snake[0].x > Col) // you are forbidon to veture from the canvas
{
init();
}
if (snake[0].x == foodX && snake[0].y == foodY) { //Yummy FOOD EAT
EAT EAT
score++;
document.getElementById("score").innerHTML = "Score: " + score;
setFood();
snake.push({ x: null, y: null }); // I got fatter
}
}
function draw()
{
context.clearRect(0, 0, canvas.width, canvas.height); // clears
canvas
context.fillStyle = "#FF0000"; // pretty colour for the head of
the snake
context.fillRect(snake[0].x * cellWidth, snake[0].y * cellWidth,
cellWidth, cellHeight);
context.fillStyle = "#09F";
for (var i = 1; i < snake.length; i++)
{
context.fillRect(snake[i].x * cellWidth, snake[i].y * cellWidth,
cellWidth, cellHeight);
}
context.fillStyle = "#F90"; // FOOD FOOD FOOD FOOD
context.fillRect(foodX * cellWidth, foodY * cellWidth, cellWidth,
cellHeight);
}
start(); // starts hence the name start
</script>
OK not bad for a beginer if you wrote it all your self.
Your problem is with the keydown event. You are creating a new handler each time you tick. This will lead to a crash. You only need to create the event handler once for the page, it will remain active until you leave the page.
To fix your problem move adding the keyDown listener to just above the function Start, as shown below.
var snake = [];
document.addEventListener("keydown", function (evt) {
keystate = evt.keyCode; // checks key presses
});
function start(){
init();
Tick();
}
Also just a because to me it looks weird. true and false are not strings you dont need to put quotes around them. Though using them as strings still works.
You have
function setFood() { //WE ARE RUNNING OUT OF FOOD WE NEED NEW PROVISIONS
var next = "true"
do {
foodX = Math.floor((Math.random() * Rows));
foodY = Math.floor((Math.random() * Col));
for (var i = 0; i < snake.length; i++) {
if (snake[i].x == foodX && snake[i].y == foodY) {
next = "false"
}
}
} while (next == "false")
draw();
}
would be better written as follows
function setFood() {
var next = true; // removed the qoutes
do {
foodX = Math.floor((Math.random() * Rows));
foodY = Math.floor((Math.random() * Col));
for (var i = 0; i < snake.length; i++) {
if (snake[i].x == foodX && snake[i].y == foodY) {
next = false; // removed the quotes.
// no point continuing the for loop as you know you need to
// reposition the food so use the break token
break; // breaks out of the closest loop
}
}
} while ( !next ) // removed next == "false" and replaced with
// ! next. "!" means "Not". do while next not true
// you have the draw here but you draw every tick so it would be best if
// you removed it as the next draw is less than 1/3 of a second away anyways
// draw(); // removed needless draw
}
Good work. Hope you get a good mark for it.

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

Categories

Resources