This site requires JavaScript, please enable it in your browser!
Greenfoot back
Malmotri
Malmotri wrote ...

2012/11/26

Can't get the totalscore

Malmotri Malmotri

2012/11/26

#
Hi! I am trying to have my final score images to show the total score. But i keep getting zero despite that i have earned several points. What do i do wrong?
  

private int totalScore=0;
private String score;


    public Score()
    {
        setImage(new GreenfootImage(200, 30));
        GreenfootImage img = getImage();
        img.setColor(Color.WHITE);
        img.drawString("Score:" + totalScore , 30, 30);
    }

    public Score(String score)
    {
        this.score = score;
        GreenfootImage image = new GreenfootImage(500, 500);
        image.setColor(new Color(255,255,255, 128));
        image.setColor(new Color(0, 0, 0, 128));
        image.fillRect(0, 0, 500, 500);
        image.setColor(Color.WHITE);
        if(score == "gameover"){
           Font font = image.getFont();
           font = font.deriveFont(50.0f);
           image.setFont(font);
           image.drawString("Game Over", 115, 250);
           setImage(image);
           
           //This line, I don't get the final score
          image.drawString("Final Score: "+totalScore, 90, 400);
        }
        if(score == "start")
        {
        image.drawString("Press any key to start the game", 50, 250);
            setImage(image);
        }
        }

    public void addScore(int number)
    {
        totalScore += number;
        GreenfootImage img = getImage();
        img.clear();
        img.drawString("Score " + totalScore, 30,30 );
       
    }
danpost danpost

2012/11/26

#
If you want 'totalScore' to be shared by all instances of the Score class, you must make it a 'static' variable. Change line 3 to:
private static int totalScore=0;
Otherwise, each instance of the class will have a seperate 'totalScore' variable to work with.
Malmotri Malmotri

2012/11/26

#
Thank you very much!
You need to login to post a reply.