Possible to have two conditions for an IF statement in javascript? - javascript

Alright so I am currently making a PBBG based game. However, I have been having trouble with my function for a button click and two conditions in my if statement. I am actually not positive if this is at all possible, I searched everywhere I could think of but nothing gave me a definitive answer for getting this to work.
Basically, what I am trying to achieve, is that when a player presses the 'Attack' button, the player then receives the amount of experience points and gold they get from defeating that monster. Then, after that function runs, I am setting a delay of 6 seconds to where they can't press the button to attack again until the 6 seconds have passed.
I did get the function and onClick to work where when they win the fight, the game awards them the experience and gold from the kill. That all worked great and I made sure that was all working BEFORE I started adding in the time delay function and all.
Here is my code for the function with the time delay I am trying to add: Code
(Won't allow me to embed pictures yet so a link will have to do for now) and I am using just an HTML button with the onClick value set to SingleAttack(). The code with the problem appears to be in this part...
if (attackReady) || (currentExp >= NeededExp) {...}
What I have done here is I am holding a boolean, named attackReady and setting it to 'true'. When the player presses the Attack button, it then changes the 'true' value to 'false' and then adds a setTimeout() and period in miliseconds for delay. It then sets attackReady back to true and puts a 6 second time delay before the function can be called again.
You'll notice there is an if and an else if in my function. The if code runs only when a players current experience points are greater than or equal to the needed experience points. I think my problem is coming from having two conditions in the if statement. I am not entirely sure if that is possible, I have looked everywhere to find an answer and nothing for javascript specifically. I know C# allows it, does javascript allow it and if so, did I do it right or have I done it wrong?
When the Attack button is clicked and the function is called, it does nothing at all. Any insights?

As #Thomas noted, the entire test needs to also be enclosed in braces. You currently have:
if (attackReady) || (currentExp >= NeededExp) {...}
and what you want is either:
if ( (attackReady) || (currentExp >= NeededExp) ) {...}
or more simply:
if (attackReady || currentExp >= NeededExp) {...}
One more thing:
From your description, it might be the case that you want both tests to be true to execute that block of code. If that is the case you want to use an AND with && rather than the || OR test. OR is true if either the left or the right hand side is true.

Related

Data-percent works only sometimes javascript

(Sorry for bad english) Hi, I'm trying to make a JavaScript app which is basically a music player and I can't figure out why one thing is not working. There's a chart that displays the music percentage (here's a screenshot) made with jQuery CDN and a GitHub source. The percentage resets at the beginning of the song (and this works) because of songTime.dataset.percent = 0;.
Then, there's the songTime.dataset.percent = sliderPosition; in a function that calculate at what point are you in the song
function chartUpdate() {
let sliderPosition = 0;
if (currentSong.duration != NaN) {
sliderPosition = Math.round(currentSong.currentTime * (100 / currentSong.duration));
songTime.dataset.percent = sliderPosition;
}}
It is in an if statement which is in a function, but this doesn't work (it's not because of the variable, I've checked it).
I've tested it several times, and the only difference between the two lines is that the one that doesn't work is in an if statement (as I already said, which is in a function).
I know it can be difficult to understand me because there isn't any code (I tried to add it, but in stackoverflow it doesn't work, I don't know why), but if you need (I don't know if it can be helpful) I hosted the non-working website here. Summing up, my problem is that the data-percent works only sometimes.
Your if statement contains invalid syntax. Replace
if (currentSong.duration != NaN)
with
if ( ! isNaN(currentSong.duration) )

Javascript recursion onEvent on Code.org

I am having trouble with a project for my AP CompSci class. We're supposed to create programs using the App Lab on code.org. The problem is every time I stop the timed loop, the resulting number gets printed more than once after the first stop. I'm pretty sure I didn't add a recursion element so it's odd. Is there something wrong with the code or is it something else?
https://studio.code.org/projects/applab/KeB7MbUhChuQbQ6HiAA7GeED7Y9trOEJJ9GXld7lOfc
Edit:
onEvent("stop3", "click", function(){
hideElement("stop3");
stopTimedLoop();
showElement("return3");
var points = Math.round(10*(15-(time/100)));
console.log(time);
score = score + points;
update();
});
The recursion happens after the first time the button is clicked. On the second click the function would rerun after completing the update. On face value the code should only run once per click, but it runs according to how many previous clicks have been made. I can't tell if its a server side problem or something wrong with the editor. The problem seems to be isolated to this function, but there is no recursion so I'm starting to wonder if there is a problem with it server side.

Whack-A-Mole game with huge bug! Can I get some help fixing it?

I am writing a Whack-A-Mole game for class using HTML5, CSS3 and JavaScript. I have run into a very interesting bug where, at seemingly random intervals, my moles with stop changing their "onBoard" variables and, as a result, will stop being assigned to the board. Something similar has also happened with the holes, but not as often in my testing. All of this is completely independent of user interaction.
You guys and gals are my absolute last hope before I scrap the project and start completely from scratch. This has frustrated me to no end. Here is the Codepen and my github if you prefer to have the images.
Since Codepen links apparently require accompanying code, here is the function where I believe the problem is occuring.
// Run the game
function run() {
var interval = (Math.floor(Math.random() * 7) * 1000);
if(firstRound) {
renderHole(mole(), hole(), lifeSpan());
firstRound = false;
}
setTimeout(function() {
renderHole(mole(), hole(), lifeSpan());
run();
}, interval);
}
What I believe is happening is this. The function runs at random intervals, between 0-6 seconds. If the function runs too quickly, the data that is passed to my renderHole() function gets overwritten with the new data, thus causing the previous hole and mole to never be taken off the board (variable wise at least).
EDIT: It turns out that my issue came from my not having returns on my recursive function calls. Having come from a different language, I was not aware that, in JavaScript, functions return "undefined" if nothing else is indicated. I am, however, marking GameAlchemist's answer as the correct one due to the fact that my original code was convoluted and confusing, as well as redundant in places. Thank you all for your help!
You have done here and there in your code some design mistakes that, one after another, makes the code hard to read and follow, and quite impossible to debug.
the mole() function might return a mole... or not... or create a timeout to call itself later.. what will be done with the result when mole calls itself again ? nothing, so it will just be marked as onBoard never to be seen again.
--->>> Have a clear definition and a single responsibility for mole(): for instance 'returns an available non-displayed mole character or null'. And that's all, no count, no marking of the objects, just KISS (Keep It Simple S...) : it should always return a value and never trigger a timeout.
Quite the same goes for hole() : return a free hole or null, no marking, no timeout set.
render should be simplified : get a mole, get a hole, if either couldn't be found bye bye. If a mole+hole was found, just setup the new mole/hole couple + event handler (in a separate function). Your main run function will ensure to try again and again to spawn moles.

Why does clearInterval(...) not seem to be doing its job here?

Repro steps:
Go to http://playclassicsnake.com/Play
Click "Fast" (or "Slow" or even "Medium") on "Set Speed" under "Controls"
Hit left arrow key and wait until snake hits left wall and "Game Over!"
Look at JavaScript console
See something like
Uncaught TypeError: Cannot read property '0' of undefined
Refresh the page
Hit left arrow key and wait until snake hits left wall and "Game Over!"
Don't see same error in the console as before
My investigation:
The reason for the error is that the function move in the first case is being called after "Game Over!" and in the second case isn't. The second case is the correct behavior. In both cases a function endGame that starts out like
this.endGame = function ( msg )
{
this.inProgress = false;
clearInterval(this.mover);
is being called, but for some reason the interval is failing to clear in the first case. It makes no sense because the only difference between what happens in the first case and second case is that in the second case the speed is set with
SG.setSpeed($('#speed-form input[type="radio"]:checked').val());
on page load to start game, and in the first case it is set with that and then updated with
$('#speed-form input[type="radio"]').click(function ( )
{
SG.setSpeed($(this).val());
});
when you click one of the radio buttons. I've tested with
this.endGame = function ( msg )
{
console.log(this.mover); // TEST
this.inProgress = false;
clearInterval(this.mover);
that in both cases this.mover is defined. For reasons I don't understand and that may have to do with my problem, in the first case the the ID of the interval is always a high number like 68, 74, etc., while in the second case it is always 2!
I have no idea what's going on here. Any help is greatly appreciated.
Full code here.
The problem was that when you were calling clearInterval(this.mover);, you were only clearing the last interval set to this.mover, and all intervals before it were being left untouched. The solution I proposed (which seems to have worked) was to clear the previous interval every time a new one is set. This takes care of that issue because there is at most one interval at any given moment.

CreateJS: Unable to get tweening to work

So,
I'm just starting to learn CreateJS and I encountered my first problem: I can't get tweening to work (as I expect it should work).
Here is the example: http://www.hakoniemi.net/labs/createjs-test/
I want to get that cloud to move from right to left - at the moment it only jumps to the target.
The code looks:
createjs.Tween.get(stack["cloud"]).to({"x":25}, 1000).call(test);
where createjs.Tween.get(stack["cloud"]) is valid and function test is executed. However there's no visual effect of 1000ms taking place at all.
I've looked through the tutorials and this is how things should work, but they're not. What am I doing wrong?
Edit: if I re-execute code in console with different value, then tweening and visual effect happens normally (here's a version where setTimeout is used: http://www.hakoniemi.net/labs/createjs-test/index2.html)
You have a type problem when setting the initial x value in
if (this.getAttribute("x")) {
ref.x = this.getAttribute("x");
}
The problem is that getAttribute() returns a string, which you can verify outputing Object.prototype.toString.call(ref.x). This way, it seems the first time the tween tries to run it can't do the proper math. In the end, it correctly updates the value to the end value as a number and that's why next calls to the same method work properly.
You can fix this just by making sure that ref.x is a number. For example:
if (this.getAttribute("x")) {
ref.x = parseInt(this.getAttribute("x"));
}
You can see it working in this fiddle.
One last thing, BitmapImageLoaded is adding the assets to the stage as soon as they are loaded. If your clouds image gets loaded before the background, it will be placed under it and you won't be able to see them. (just in case :))

Categories