Edenvdv
Edenvdv

Reputation: 31

JavaScript code doesn't work with a certain condition

I'm building a website with math games in which you can earn points. The scores are being calculated after finishing a game. So score1 for game1 starts at 0 but if you do it correctly, you'll get 10 point, same goes for the other games (game2 = score2, game3 = score3 etc.)

To calculate the total score I use:

var totalscore = parseInt(score1) + parseInt(score2) + parseInt(score3) ... and so on

I've got a function to check the total score every once in a while:

function totaalscoreshow() {
    var totaalscore = parseInt(score1) + parseInt(score2) + parseInt(score3) + 
    parseInt(staat.scoreM1) + parseInt(M_score2) + parseInt(M_score3) + 
    parseInt(H_staat.scoreH1) + parseInt(H2_staat.scoreH2) + parseInt(verlies_winst);

    document.getElementById("totaalscore").innerText = totaalscore;
    document.getElementById("totaalBet").innerText = totaalscore;
}

totaalscoreshow();
setInterval(totaalscoreshow, 100);'

The total score is also defined as a global variable.

This all works fine. But I'm trying to put the total score in a condition. I tried it in multiple ways. Among which:

function CheckInzet() {
        setInterval(totaalscoreshow, 100)
        if (totaalscore < parseInt(inzet.value) || totaalscore <= 0) {
            inzet_leeg.innerText = "Je hebt niet genoeg punten om in te zetten";
            return;
        } else {
            inzetCorrect = true;
        }
    }
setInterval(CheckInzet, 11);

if (inzetCorrect == true) {
    ... more code ...
}
... more code ...

also this way:

totaalscoreshow();
    if (totaalscore < parseInt(inzet.value) || totaalscore <= 0){
        inzet_leeg.innerText = "Je hebt niet genoeg punten om in te zetten";
        return;
    } else if (inzet.value == "0" || inzet.value == 0) {
        inzet_leeg.innerText = "Je moet punten inzetten."
        return;
    } else if (inzet.value == "") {
        inzet_leeg.innerText = "Zet eerst een aantal punten in.";
        return;
    } else if (newClicked == true && inzet.value !== "") {
        inzet_leeg.innerText = "Start eerst een nieuwe ronde";
        return;
    } else if (clicked == true) {
        inzet_leeg.innertext = "Maak eerst deze ronde af";
        return;
    } 

... more code ...

I tried playing with it in more ways, but the problems keeps existing.

When the total score is indeed less than or equal to 0, or less than inzet.value, it does what it should do.

But then when the total score is greater than 0 or greater than inzet.value, it still acts like it isn't. All the other code works when I leave the condition of totaalscore out. But I need it to work with this condition.

Upvotes: 0

Views: 73

Answers (3)

I didn't entirely understand your problem but there are few things you can improve in your code:

Instead of doing

var totalscore = parseInt(score1) + parseInt(score2) + parseInt(score3) ...

you should try storing these variables as int so you dont have to convert them each time, also consider storing them together (in an array for exemple) so that you can add them faster using:

scores=[100,0,31,28] // array of score1, score2, etc...
var totaalscore=scores.reduce((a, b) => a + b);

If you can't store your scores as int you can try this before adding them together:

var totaalscore=scores.map((a)=>parseInt(a))

Keep also in mind that in JS any number different from 0 considered as true.

true==1 //true
true==5 //true
true== -1 // true
true== 0 //false

if (inzetCorrect == true) {}
//is the same as 
if (inzetCorrect){}

var condition=(5>1) //value "true" is stored in "condition"
if(condition){
    //it will do something
}

Your last piece of code could be more optimized if you use the switch statement, it works faster: https://www.w3schools.com/js/js_switch.asp

Glad you've already solved your problem :) I recommend you drawing a scheme of your program so that you don't get confused the next time

Upvotes: 1

Edenvdv
Edenvdv

Reputation: 31

Turned out that there was indeed something wrong with the count of totalscore in this specific function. But the totalscore was being updated as the innertext of a p-element. I fixed it by just reading the number in innertext and checking that value in the condition instead of the totalscore. Instead of fixing the problem I found a other solution. I know as a coder you should fix it, but I'm running out of time for my assignment and now this works, so I'm happy :D

Upvotes: 0

Ahmed Hekal
Ahmed Hekal

Reputation: 478

I think you need to optimze your game logic , for example the OPP of js can help you to make it dynamicly

This is a simple js class that can help you to make your code more clean

For example you can remove the interval of calcolting total by manging change event

class ScoreManager {
    plyers = {
        'player_1':{
            scores:{
                game_one:10
            },
            totalScore:0
        }
    }
    _onScoreChange = ()=>{}

    constructor() {

    }

    onScoreChange(cb){
        this._onScoreChange = cb

    }


    addPlayer(plyerName){
        if(this.plyers[plyerName]) throw new Error("Player already exists!")
        this.plyers[plyerName] = {
            scores:{}
        }
    }
    addScoreForPlyer(plyerName,gameName,score){
        if(!this.plyers[plyerName]) throw new Error("Player dosn't exists!");
        this.plyers[plyerName].scores[gameName] = score
        this.calcolateScore(plyerName)
    }

    removeScoreForPlyer(plyerName,gameName){
        if(!this.plyers[plyerName]) throw new Error("Player dosn't exists!");
        delete this.plyers[plyerName].scores[gameName]
        this.calcolateScore(plyerName)
    }

    removePlyer(plyerName){
        delete this.plyers[plyerName]
    }
    calcolateScore(plyerName){
        let totalScore = 0

        Object.keys(this.plyers[plyerName].scores).forEach(r=>{
            totalScore+=this.plyers[plyerName].scores[r]
        })
        this.plyers[plyerName].totalScore = totalScore
        this._onScoreChange(plyerName,totalScore,this.plyers)
        return totalScore
    }

  }
  
  
  //Home to use it 

  const scoreManger = new ScoreManager()
  scoreManger.onScoreChange((plyerName,totalScore,plyers)=>{


    console.log(`The plyer ${plyerName} has score ${totalScore}`)
    console.log(`totalPlyerObject`,plyers)
  })
  scoreManger.addPlayer("max");
  scoreManger.addScoreForPlyer("max",'step_one',10)

Upvotes: 0

Related Questions