My method fires when it shouldn't - javascript

This code seems to loop through adding 1 to player1.score untill the score is === to whatever i put in the second if statement. Anyone know why?
pointScored: {
startNextSet: function(Scorer) {
if (gameController.bananasTaken < 3 && Scorer === "player1") {
console.log(gameController.player1.score);
gameController.player1.score += 1;
if (gameController.player1.score === 10 &&
gameController.bananasTaken === 0 &&
gameController.player1.bananaCount === 0) {
console.log(gameController.player1.score);
gameController.updatePlayerStats(gameController.Banana1, 20, gameController.canvas.height
- 20 - gameController.Banana1.height, gameController.player1, "left");
console.log("player 1's first point");
}
I'm currently learning about using a debugger but thought i'd leave this here to see if anyone knows why. Thanks.

There's a chance your values get evaluated as strings. The === operator doesn't do any type conversions, that's why its faster.
Consider changing your evaluation to use ==. The same issue has cropped up in another question.
I have refactored your code a bit & used the == notation I suggest above. Please try running it and tell me if it works.
pointScored:{
startNextSet: function(Scorer) {
gc=gameController; //to save thy fingers from typing ache
if (gc.bananasTaken > 2 || Scorer !== "player1")
return;
console.log(gc.player1.score); // this logs 6 times from 0 to 5
gc.player1.score += 1;
if (gc.player1.score == 5 && gc.bananasTaken == 0) {
alert(gc.player1.score); //*******!
if(gc.player1.bananaCount == 0) {
gc.updatePlayerStats(gc.Banana1, 20, gc.canvas.height - 20 - gc.Banana1.height, gc.player1, "left");
console.log("player 1's first point");
}
}
}
}

As I look at your function, it seems that this logic needs to be INSIDE the gameController object.

Related

Generate and compare random numbers(in a game)

**I'm stuck on this part of my code, I want to generate a random number and compare it to the number who selected the player and depending on the result give a message **
this is a picture of the program
let butons=document.querySelectorAll(".btn");
let result=document.getElementById('result');
let eleccionPc=document.getElementById('elP');
let eleccionPlayer=document.getElementById('elPlayer');
butons.forEach((button)=>{
button.addEventListener('click',()=>{
eleccionPc.textContent=Math.floor(Math.random()*3)+1;
if(button.textContent==='1' < eleccionPc.textContent) {
eleccionPlayer.textContent='1';
result.textContent='You are Loser';
}
else if (button.textContent==='3' > eleccionPc.textContent) {
eleccionPlayer.textContent='3';
result.textContent='You win MotherFucker';
}
/*else if (button.textContent=="2" > eleccionPc.textContent ){
}*/
})
})
PD:I still don't know how to make a decent publication
The problem is in the if statement, you need to use && in the if statement
if(button.textContent === '1' && button.textContent < eleccionPc.textContent)
else if (button.textContent === '3' && button.textContent > eleccionPc.textContent)
This will solve the problem, If you have any question just ask me
this doesn't make any sense:
button.textContent==='1' < eleccionPc.textContent
the first half of the statement returns with "true" or "false" and then tries to see if that is less than a number?
Maybe you mean this?
button.textContent < eleccionPc.textContent

After Effects: Javascript - Undefined value used in the expression(Could be out of range array subscript)

I'm not a programmer by any means. I'm an animator trying to use JS expressions in After Effects. I'm getting an "Undefined value used in expression" error on line 1 where I define a variable.I already showed it to my friend on discord who is a cs major, and he had no clue what was wrong with it.
Here's just a paste of the code if you need it:
var count = 1;
if (framesToTime(time) % 12 == 0) {
count = count + 1
if (count % 2 == 0){
thisProperty = 95
} else {
thisProperty = 20
};
} ;
Ok I don't know why the hell this fixed it, but I changed the name of the variable from "count" to just "x" and it works now. Go figure
Try it.
var count = 1;
if (framesToTime(time) % 12 == 0) {
count = count + 1;
if (count % 2 == 0){
thisProperty = 95;
} else {
thisProperty = 20;
}
}
thisProperty;
In your code, thisProperty has become an ordinary variable. If you write its name at the end of the code, then its value will be assigned to the property.
In AE, if there is nothing inside an if statement or the if statement contains malformed/error code you will receive this error. Put a temp value inside the curly braces or something to process and ensure nothing inside will throw an error.
I also received this error with this:
pastTime = timeToFrames(time)-1;
curPos = transform.xPosition;
pastPos = transform.xPosition.valueAtTime(framesToTime(pastTime));
if (curPos-pastPos[0] != 0) {
// Here is the problem in my case. added a value here 99 to fix until finished testing.
}
else {
effect("Angle Control")("Angle")
}
if/else statements are strict
The syntax for if/else statements is strict in the JavaScript engine
and need to be written for standardized JavaScript.
https://helpx.adobe.com/after-effects/using/expression-language-reference.html*
I got this error because there was a missing semicolon.

FizzBuzz: 15 shows Fizz but no Buzz on newline. Why? Just need clarification

Just trying to understand on why Buzz doesn't appear in the newline after Fizz for 15.
Trying to learn JavaScript from Eloquent Javascript and just got into doing the FizzBuzz exercise. Note that I've included a commented out solution where it does work (although not elegantly) but the thing I've notice that some solutions searched online show their 15 appearing with Fizz but Buzz is on a newline while my solution (which is not commented out) only shows Fizz.
Can anyone explain to me why does it do this? Just curious. The only thing I've noticed is when I use
if ((int%3 == 0) && (int%5 == 0))
either at the end or the beginning of the block is when the changes are visible.
Note:
I'm not asking for solutions. I just want an explanation to my question above. The commented solution does give me FizzBuzz for 15. Please do not misunderstand and thank you for taking your time to answer this.
My solution:
for(let int = 1; int <= 100; int++){
if(int%3 == 0){
console.log('Fizz');
}
else if(int%5 == 0){
console.log('Buzz');
}
else if ((int%3 == 0) && (int%5 == 0)){
console.log('Fizz'+'Buzz');
}
/*if ((int%3 == 0) && (int%5 == 0)){
console.log('Fizz'+'Buzz');
}
else if(int%3 == 0){
console.log('Fizz');
}
else if(int%5 == 0){
console.log('Buzz');
}*/
else{
console.log(int);
}
}
In you solution, the following block is dead code :
else if ((int%3 == 0) && (int%5 == 0)){
console.log('Fizz'+'Buzz');
This console.log('Fizz'+'Buzz') can never be reached because ((int%3 == 0) && (int%5 == 0)) would mean that (int%3 == 0) and so the first if is executed. Because of the meaning of else if, this later code block is never reached.
So to answer directly :
show their 15 appearing with Fizz but Buzz is on a newline
This probably is a coding error as FizzBuzz usually requires writing "Fizz Buzz" on a single line for 15. I would guess they did not use any "else if" - which you did.
my solution (which is not commented out) only shows Fizz.
Can anyone explain to me why does it do this.
Because else if blocks order is important, and you chose the wrong one.
If you remove else from else if(int%5 == 0) you will get your desired output I guess.
You should reverse the order of your if statements as you have in the commented out section. Otherwise, when int = 15, your code will match true for
if(int%3 == 0){
console.log('Fizz');
}
And it will never reach the other if statements.

Why are both my if statements activating?

I'm completely in awe right now, I usually am able to figure this stuff out quickly but this just isn't making any sense to me.
setTimeout(
function(){
if (user1.length || pass1.length <= 6) {
document.getElementById('verified').innerHTML="Error: Username or password too short!";
alert('Running');
setTimeout(function(){location.reload()},1000);
}
if (user1.length && pass1.length >= 7) {
document.getElementById('verified').innerHTML="You've been verified!";
}
}
,2000);
For some reason even if they don't meet the rules, the first if statement is activated and the page reloads/alert pops up.
Both your If statements are wrong. I think what you are looking for is:
if (user1.length <= 6 || pass1.length <= 6)
and
if (user1.length >= 7 && pass1.length >= 7)
When you use If in javascript anything holding a value returns true.
So if you write:
if (user1.length)
it will allways return true. You need to remember <= 6 on both sides of ||
Hope this helps :)
user1.length looks suspicious to me. Are you sure it's Boolean? There is no operator or operand before the ||.
It's because this condition
user1.length || pass1.length <= 6
If user1.length is non-zero then the second part will not even be checked because of short-circuit evaluation.
Did you mean to use logical and &&?
If user1.length is nonzero, that is a sufficient condition alone for the 1st if statement to be executed.
If additionally pass1.length >= 7, then also the 2nd statement will be executed.
Seemingly simple logic statements can be tricky, but it pays to stay cool and thing through them.
I understand now why this wasn't working. I now have
if (user1.length <= 6 || pass1.length <= 6) {
document.getElementById('verified').innerHTML="Error: Username or password too short!";
setTimeout(function(){location.reload()},1000);
}
if (user1.length >= 7 && pass1.length >= 7) {
document.getElementById('verified').innerHTML="You've been verified!";
}
which is working fine. Thanks :)

Run a function as far as a variable reaches specific values

I have a canvas game which calls a function incScore every time an action is performed in the game to increase the score.
Inside incScore I have a few if statements to draw a particular image to represent a level number on the canvas.
I also want to have a sound play once per level up. The way I've gone about things the lvlup sound will play every time the score matches the if statement.
Can anyone please help me get this so that the sound will only play once when the level changes and not again until the next level change? I'm also mention I'm using jQuery incase it has anything that could help me.
incScore(); //everytime an action in the game causes the score to increase
function incScore(){
if (scoreTotal < 500){
lvlimg = "L01";
drawLevel(lvlimg);
lvlupSound();
}
else if (scoreTotal > 500 && scoreTotal < 1000){
lvlimg = "L02";
drawLevel(lvlimg);
lvlupSound();
}
else{
lvlimg = "L03";
drawLevel(lvlimg);
lvlupSound();
}
}
You could shorten your function and use a semi static property to save the state. Using that, you can compare the current level to the previous and play a sound if they differ.
function incScore(){
incScore.level = incScore.level || 'L0'; //< initialize property
lvlimg = "L0" + scoreTotal < 500 ? 1 : scoreTotal < 1000 ? 2 : 3;
drawLevel(lvlimg);
if (incScore.level!=='L0' &&
incScore.level !== lvlimg) { lvlupSound(); };
// ^compare local level to current
incScore.level = lvlimg;
// ^ update local level
}
[edit, based on comment] The third line is a so called ternary, or conditional operator. See MDN. You can use more conditions.
To avoid playing a sound before the score has reached a first level, you could use
if (incScore.level!=='L0' && incScore.level !== lvlimg).
I've created a mockup jsFiddle
A simple solution could be comparing the current level to the old one, to detect when the level changed:
function scoreToLevel(score)
if(score < 500){
return 1
}else if (score < 1000){
return 2
}else{
return 3
}
}
function incScore()
var next_level = scoreToLevel(scoreTotal)
if(next_level !== current_level){
lvlimg = "L0" + next_level;
drawLevel(lvlimg)
lvlupSound()
}
}
The easiest solution is to factor the sound out of those if statements. If the levels are nice and regular like that(every 500 points) and the points always increase in a way that you will always land exactly on an even multiple of 500 when you level up, something like this should do:
if(scoreTotal % 500 === 0 && scoreTotal < 1001)
{
lvlupSound();
}
If you won't always land directly on the gate to the next level(maybe the player can earn anywhere between 1 and 15 points at a time) then you should be able to get by using something along the lines of this before you increment the player's score:
if( (scoreTotal % 500) > ((scoreTotal + increment) % 500)
{
lvlupSound();
}
if your level boundries are not regular like that obviously it gets a little bit more complex, but that should get you started.
That is because you have the in every statement for every score (which means from 0 to infinite).
You will need to write inner if statements such as;
if (scoreTotal < 500){
lvlimg = "L01";
drawLevel(lvlimg);
if(scoreTotal x times of each the level) // That means for each level completed
{
lvlupSound();
}
}
If your score increment is only 1, then only play the tone when the score equals the threshold for a new level.
If they can increase their score by more than 1, then you could pass the number of points in and check the score before and after to see if the numbers fall on each side of the threshold.
If that still doesn't work, some more info on the "level" and points would be appreciated.
Try something like this (demo):
var scoreTotal,
lastLevel = 0,
levels = [500, 1000, 2500, 5000, 10000, 25000, 50000, 75000],
currentLevel = 0,
lvlImg;
function incScore() {
while (scoreTotal > levels[currentLevel]) {
currentLevel++;
}
if (lastLevel !== currentLevel) {
lastLevel = currentLevel;
// gives a two digit number with a leading zero
lvlImg = ('0' + currentLevel).slice(-2);
drawLevel("L" + lvlimg);
lvlupSound();
}
}
Then you can easily add additional levels by adding the score cutoff to the levels variable.

Categories