I need to remove newCircle.fillColor = "red"; in order to get colors other than red but when i remove it, it says the property of hue is undefined.
var circles = [];
function onKeyDown(event) {
var maxPoint = new Point(view.size.width, view.size.height);
var randomPoint = Point.random();
var point = maxPoint * randomPoint;
var newCircle = new Path.Circle(point,500)
if(event.key === "a"){
bubbles.play();
newCircle.fillColor = "#2c3e50";
}
else if(event.key === "b"){
newCircle.fillColor = "#2c3e50";
clay.play();
}
else if(event.key === "c"){
newCircle.fillColor = "#00ff0f";
confetti.play();
}
newCircle.fillColor = "red";
circles.push(newCircle);
}
function onFrame(event){
for(var i = 0; i < circles.length; i++){
circles[i].fillColor.hue += 1;
circles[i].scale(.9);
}
}
Either set the fillColor before the if statements (like the below code snippet) or have an else statement.
var circles = [];
function onKeyDown(event) {
var maxPoint = new Point(view.size.width, view.size.height);
var randomPoint = Point.random();
var point = maxPoint * randomPoint;
var newCircle = new Path.Circle(point,500)
newCircle.fillColor = "red";
if(event.key === "a"){
bubbles.play();
newCircle.fillColor = "#2c3e50";
}
else if(event.key === "b"){
newCircle.fillColor = "#2c3e50";
clay.play();
}
else if(event.key === "c"){
newCircle.fillColor = "#00ff0f";
confetti.play();
}
circles.push(newCircle);
}
function onFrame(event){
for(var i = 0; i < circles.length; i++){
circles[i].fillColor.hue += 1;
circles[i].scale(.9);
}
}
I would also suggest using a switch statement and moving that if else section to another function.
Related
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>
I made a snake game that works almost completely. I have one snake head, and an array which contains the head and all of the tails. When the snake eats a food, the food moves location, but my tail isn't getting bigger when I eat the food. I don't have an IMMENSE understanding of arrays, perhaps I'm doing it wrong?
Here is the code:
setSize(400, 400);
var background = new Rectangle(getWidth(), getHeight());
background.setPosition(0, 0);
background.setColor(Color.black);
add(background);
// ------------------------------------------------
var gameTime = 0;
var snakeX = (Randomizer.nextInt(0, 19)) * 20;
var snakeY = (Randomizer.nextInt(0, 19)) * 20;
var foodX;
var foodY;
var snakeFood = new Rectangle(20, 20);
snakeFood.setColor(Color.red);
var food_eaten = 0;
var snakeSpeed = 20;
var keyLeft = false;
var keyRight = false;
var keyUp = false;
var keyDown = false;
var snake_size = 10;
var snakeHead = new Rectangle(20, 20);
snakeHead.setColor(Color.green);
var snakes = [snakeHead];
// ------------------------------------------------
function start(){
setup();
keyDownMethod(checkKey);
setTimer(counter, 250);
}
function counter(){
gameTime += 0.25;
updateSnake();
}
function setup(){
foodX = (Randomizer.nextInt(0, 19)) * 20;
foodY = (Randomizer.nextInt(0, 19)) * 20;
snakeHead.setPosition(snakeX, snakeY);
add(snakeHead);
snakeFood.setPosition(foodX, foodY);
add(snakeFood);
}
function checkKey(e){
if(e.keyCode == Keyboard.LEFT){
keyRight = false;
keyUp = false;
keyDown = false;
keyLeft = true;
}else if(e.keyCode == Keyboard.RIGHT){
keyLeft = false;
keyUp = false;
keyDown = false;
keyRight = true;
}else if(e.keyCode == Keyboard.UP){
keyRight = false;
keyLeft = false;
keyDown = false;
keyUp = true;
}else if(e.keyCode == Keyboard.DOWN){
keyRight = false;
keyLeft = false;
keyUp = false;
keyDown = true;
}
}
function updateSnake(){
if(foodX == snakeX && foodY == snakeY){
eat();
}
var dirX = 0;
var dirY = 0;
if(keyLeft == true){
dirX = -(snakeSpeed);
dirY = 0;
}else if(keyRight == true){
dirX = snakeSpeed;
dirY = 0;
}else if(keyUp == true){
dirY = -(snakeSpeed);
dirX = 0;
}else if(keyDown == true){
dirY = snakeSpeed;
dirX = 0;
}
// moving the snake head
snakeHead.setPosition(snakeX + dirX, snakeY + dirY);
snakeX += dirX;
snakeY += dirY;
// moving the snake body
if(snakes.length > 1){
for(var i = 0; i < snakes.length; i++){
var curr_body = snakes[i];
curr_body.setPosition(snakeX + dirX, snakeY + dirY);
}
}
}
function eat(){
foodX = (Randomizer.nextInt(0, 19)) * 20;
foodY = (Randomizer.nextInt(0, 19)) * 20;
var tail = new Snake(snakeX, snakeY);
snakeFood.setPosition(foodX, foodY);
}
function Snake(x, y){
var snakeBody = new Rectangle(20, 20);
if(keyLeft == true){
snakeBody.setPosition(x + snake_size, y);
}if(keyRight == true){
snakeBody.setPosition(x - snake_size, y);
}if(keyUp == true){
snakeBody.setPosition(x, y + snake_size);
}if(keyDown == true){
snakeBody.setPosition(x, y - snake_size);
}
snakeBody.setColor(Color.green);
snakes.push(snakeBody);
add(snakeBody);
}
In your eat() function, you assign a new Snake object to a var tail, but then do nothing with it. I think you need to add it to your snakes array (which I assume represents the entire snake?)
I have three variables that I need to put in the innerHTML of four spans. The variables I use are seconds, accurateclick, and inaccurateclick. The process I use to get these variables is fine. The problem is I can't figure out how to bring them over to another function. I will make a replica of what I have. This will be a simpler version.
var x;
var y;
var z;
function A(){
x = 1;
y = 2;
z = 3;
B();
}
function B(){
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
}
What would happen is, instead of a being equal to 1, b being equal to 2, and c being equal to 3, they would all equal to undefined. I don't know why that is happening when x, y, and z are global variables. I thought they should change when set to a different value.
Here is my actual code:
var seconds;
var accurateclicks;
var inaccurateclicks;
var windowheight = window.innerHeight;
var windowwidth = window.innerWidth;
var colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Purple"];
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
function BeginGameLoad(){
var BottomLabel1 = document.getElementById("bl1");
var BeginGameContainer = document.getElementById("BGC1");
var RightClick = false;
BottomLabel1.addEventListener("mousedown", BL1MD);
BottomLabel1.addEventListener("mouseup", BL1MU);
BottomLabel1.style.cursor = "pointer";
window.addEventListener("resize", BeginGameResize);
window.addEventListener("contextmenu", BeginGameContextMenu);
function BeginGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL1MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel1.style.color = randomcolor;
RightClick = false;
}
}
function BL1MU(){
if(RightClick == false){
window.location.href = "Game.html";
GameLoad();
}
else{
RightClick = false;
}
}
if(windowheight < 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
BeginGameContainer.style.width = "800px";
}
function BeginGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
BeginGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
BeginGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
BeginGameContainer.style.width = "100%";
}
}
}
function GameLoad(){
var LeftPanel2 = document.getElementById("lp2");
var LeftColorPanel2 = document.getElementById("lcp2");
var TopPanel2 = document.getElementById("tp2");
var TopLabel2 = document.getElementById("tl2");
var RightPanel2 = document.getElementById("rp2")
var RightLabel2 = document.getElementById("rl2");
var GameContainer = document.getElementById("GC2");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var clickedRightName = false;
var clickedRightColor = false;
var clickedRightNameColor = false;
var RightClick = false;
var ClickedLeftColorPanel = false;
var ClickedRightLabel = false;
var ClickedTopLabel = false;
var Timer;
TopPanel2.addEventListener("mouseup", TP2MU);
TopLabel2.addEventListener("mousedown", TL2MD);
TopLabel2.addEventListener("mouseup", TL2MU);
TopLabel2.style.cursor = "pointer";
LeftPanel2.addEventListener("mouseup", LP2MU);
LeftColorPanel2.addEventListener("mouseup", LCP2MU);
LeftColorPanel2.addEventListener("mousedown", LCP2MD);
LeftColorPanel2.style.cursor = "pointer";
RightPanel2.addEventListener("mouseup", RP2MU);
RightLabel2.addEventListener("mouseup", RL2MU);
RightLabel2.addEventListener("mousedown", RL2MD);
RightLabel2.style.cursor = "pointer";
window.addEventListener("resize", GameResize);
window.addEventListener("contextmenu", GameContextMenu);
function AddSeconds(){
seconds++;
}
function GameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function TL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true){
TopLabel2.style.color = randomcolor;
RightClick = false;
}
}
function TP2MU(){
if(ClickedTopLabel == false){
inaccurateclicks++;
}
else{
ClickedTopLabel = false;
}
}
function TL2MU(){
ClickedTopLabel = true;
if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
accurateclicks++;
window.location.href = "EndGame.html";
EndGameLoad();
}
else if (!clickedRightName == true && !clickedRightColor == true && !clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
Timer = setInterval(AddSeconds, 1000);
seconds = 0;
accurateclicks = 0;
inaccurateclicks = 0;
TopLabel2.innerHTML = randomcolor;
RightClick = false;
}
else{
inaccurateclicks++;
}
RightClick == false
}
function LCP2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function LCP2MU(){
ClickedLeftColorPanel = true;
if(clickedRightColor == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == LeftColorPanel2.style.backgroundColor){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.color){
LeftColorPanel2.style.backgroundColorr = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.backgroundColor){
LeftColorPanel2.style.backgroundColor = randomcolor2;
accurateclicks++;
}
if (LeftColorPanel2.style.backgroundColor == randomcolor.toLowerCase()){
clickedRightColor = true;
LeftColorPanel2.style.cursor = "auto";
}
randomcolor2 = null;
RightClick = false;
}
else if(clickedRightColor == true && RightClick == false){
inaccurateclicks++;
}
}
function LP2MU(){
if(ClickedLeftColorPanel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
function RL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function RL2MU(){
ClickedRightLabel = true;
if(clickedRightName == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2 == RightLabel2.innerHTML){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2 != RightLabel2.innerHTML){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2 != RightLabel2.color){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
}
if (RightLabel2.innerHTML == randomcolor){
clickedRightName = true;
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == false && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == RightLabel2.style.color){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
}
if (RightLabel2.style.color == randomcolor.toLowerCase()){
clickedRightNameColor = true;
RightLabel2.style.cursor = "auto";
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == true && RightClick == false){
inaccurateclicks++;
}
}
function RP2MU(){
if(ClickedRightLabel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
if(windowheight < 600)
{
GameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
GameContainer.style.width = "800px";
}
function GameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
GameContainer.style.height = "600px";
}
if(windowheight > 600)
{
GameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
GameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
GameContainer.style.width = "100%";
}
}
}
function EndGameLoad(){
var BottomLabel3 = document.getElementById("bl3");
var EndGameContainer = document.getElementById("EGC3");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var RightClick = false;
BottomLabel3.addEventListener("mousedown", BL3MD);
BottomLabel3.addEventListener("mouseup", BL3MU);
BottomLabel3.style.cursor = "pointer";
window.addEventListener("resize", EndGameResize);
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
window.addEventListener("contextmenu", EndGameContextMenu);
function EndGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL3MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true
}
else{
randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel3.style.color = randomcolor;
RightClick = false;
}
}
function BL3MU(){
if(RightClick == false){
MiddleLabelTwo.innerHTML = "Time (Seconds): "
MiddleLabelThree.innerHTML = "Accurate Clicks: "
MiddleLabelFour.innerHTML = "Inaccurate Clicks: "
MiddleLabelFive.innerHTML = "Score: "
window.location.href = "Game.html";
}
}
if(windowheight < 600)
{
EndGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
EndGameContainer.style.width = "800px";
}
function EndGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
EndGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
EndGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
EndGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
EndGameContainer.style.width = "100%";
}
}
}
Whenever I run it, it works up to this point
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
It says seconds, accurateclicks, and inaccurateclicks are all undefined. I don't know why this would happen given that they were defined in the previous function [Game()].
try writing,
x = 1;
y = 2;
z = 3;
function A() {
B();
}
function B() {
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
console.log(a, b, c, d);
}
A();
Reason: 'var' defines variables locally!
You did make two html files and this caused the js file to reload. This is why the global variables are declared again and are renewed to undefined.The solution is to work with one html file and to only reload the body.
My syntax was right, but as #Julie mentioned, the variables were being reloaded. How to get JS variable to retain value after page refresh? this helped me solve my problem.
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 really new to Javascript, so I decided to create a simple SnakeGame to embed in HTML. However, my code for changing the snake's direction freezes up after a few turns.
Note: I'm running this in an HTML Canvas.
Source:
var Canvas;
var ctx;
var fps = 60;
var x = 0;
var seconds = 0;
var lastLoop;
var thisLoop;
var tempFPS = 0;
var blockList = [];
var DEFAULT_DIRECTION = "Right";
var pendingDirections = [];
function update() {
x += 1;
thisLoop = new Date();
tempFPS = 1000 / (thisLoop - lastLoop);
lastLoop = thisLoop;
tempFPS = Math.round(tempFPS*10)/10;
if (x==10){
document.getElementById("FPS").innerHTML = ("FPS: " + tempFPS);
}
//Rendering
for (var i = 0; i<blockList.length; i++){
var block = blockList[i];
draw(block.x, block.y);
}
if (x==5){
x=0;
seconds+=1;
//Updates once per x frames
moveBlocks();
}
}
function moveBlocks(){
if(blockList.length === 0){
return;
}
for (var j = 0; j<pendingDirections.length; j++){
if (b >= blockList.length -1){
pendingDirections.shift();
}else {
//Iterates through each direction that is pending
var b = pendingDirections[j].block;
try{
blockList[b].direction = pendingDirections[j].direction;
} catch(err){
alert(err);
}
pendingDirections[j].block++;
}
}
for (var i = 0; i<blockList.length; i++){
var block = blockList[i];
clear(block.x, block.y);
if (block.direction == "Down"){
block.y += BLOCK_SIZE;
} else if (block.direction == "Up"){
block.y -= BLOCK_SIZE;
} else if (block.direction == "Left"){
block.x -= BLOCK_SIZE;
} else if (block.direction == "Right"){
block.x += BLOCK_SIZE;
} else {
alert(block.direction);
}
draw(block.x, block.y);
}
}
function init(){
lastLoop = new Date();
window.setInterval(update, 1000/fps);
Canvas = document.getElementById("Canvas");
ctx = Canvas.getContext("2d");
}
//The width/height of each block
var BLOCK_SIZE = 30;
//Draws a block
function draw(x, y) {
ctx.fillStyle = "#000000";
ctx.fillRect(x,y,BLOCK_SIZE,BLOCK_SIZE);
}
function clear(x,y){
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(x,y,BLOCK_SIZE,BLOCK_SIZE);
}
function processInput(key){
if (key == 110){
//n (new)
newBlock(BLOCK_SIZE*4,0);
newBlock(BLOCK_SIZE*3,0);
newBlock(BLOCK_SIZE*2,0);
newBlock(BLOCK_SIZE*1,0);
newBlock(0,0);
} else if (key == 119){
changeDirection("Up");
} else if (key == 115){
changeDirection("Down");
} else if (key == 97){
changeDirection("Left");
} else if (key == 100){
changeDirection("Right");
} else if (key==122){
var pDir = "Pending Directions: ";
for (var i = 0; i<pendingDirections.length; i++){
pDir += pendingDirections[i].direction + ", ";
}
alert(pDir);
} else if (key == 120){
var dir = "Directions: ";
for (var j = 0; j<blockList.length; j++){
dir += blockList[j].direction + ", ";
}
alert(dir);
} else {
alert("KEY: " +key);
}
}
function changeDirection(d){
var LD = blockList[0].direction;
var valid = false;
if (d == "Up"){
if(LD != "Down"){
valid = true;
}
} else if (d == "Down"){
if(LD != "Up"){
valid = true;
}
} else if (d == "Left"){
if(LD != "Right"){
valid = true;
}
} else if (d == "Right"){
if(LD != "Left"){
valid = true;
}
}
if (d == LD) { valid = false;}
if (valid){
var dir = {'direction' : d, 'block' : 0};
pendingDirections.unshift(dir);
}
}
function newBlock(x, y){
var block = {'x': x, 'y' : y, 'direction' : DEFAULT_DIRECTION};
//This works: alert(block['x']);
draw(x,y);
blockList.push(block);
}
Thanks
As Evan said, the main issue is how you are handling pending directions.
The issue occurs when you turn twice in rapid succession, which causes two pending directions to be added for the same block. If these aren't handled in the correct order, then the blocks may move in the wrong direction. On every update, only one pending direction for each block is needed, so I redesigned how this is handled to avoid multiple directions on one block during a single update.
Here is the link to it: http://jsbin.com/EkOSOre/5/edit
Notice, when a change in direction is made, the pending direction on the first block is updated, overwriting any existing pending direction.
if (valid) {
blockList[0].pendingDirection = direction;
}
Then, when an update occurs, the list of blocks is looped through, and the pending direction of the next block is set to be the current direction of the current block.
if(!!nextBlock) {
nextBlock.pendingDirection = block.direction;
}
If the current block has a pending direction, set the direction to the pending direction.
if(block.pendingDirection !== null) {
block.direction = block.pendingDirection;
}
Then update the block locations like normal.
You also had various other issues, such as using a variable (b) before it was initialized, and how you caught the null/undefined error (you should just do a check for that situation and handle it appropriately), but this was the main issue with your algorithm.
You'll also want to remove the old blocks when the user hits 'n', because the old one is left, increasing the speed and number of total blocks present.
Good luck with the rest of the game, and good luck learning JavaScript.