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

2013/1/16

Score Counter increment each time mouse clicked

danbyization danbyization

2013/1/16

#
Hey guys I have a score counter in my greenfoot game and i need to make it increment by one each time the mouse is clicked i have tried adding in an if statement for each time the mouse is clicked but that is not working.
danpost danpost

2013/1/16

#
Please supply the code you are attempting to use. Also, would be good to know if counter is just a variable or a class object.
danbyization danbyization

2013/1/16

#
Here is the code for the counter
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
/**
 * Write a description of class Counter here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Counter extends Actor
{
    private int score;
    
    public Counter()
    {
        score = 0;
        setImage (new GreenfootImage(200, 30));
        update();
    }
    
    public void addScore()
    {
        score++;
        update();
    }
    
    public void update()
    {
        GreenfootImage img = getImage();
        img.clear();
        img.setColor(Color.WHITE);
        img.drawString("Coloured Balls: " + score, 4, 20);
    }
}
danpost danpost

2013/1/16

#
That is fine, but we need code you are trying to use to catch the mouse click and increment the counter, also.
danbyization danbyization

2013/1/16

#
All i have been trying to do is add the following if statement into the code above ive tried everywhere i can think of.
if(Greenfoot.mouseClicked(null))
        {
            score++;
        }
danpost danpost

2013/1/16

#
OK, incrementing the value of the field does not undate the image of the object. Instead of incrementing the value directly, just call the 'addScore()' method which will update the image also.
danbyization danbyization

2013/1/16

#
So change the if statement to the following:
if(Greenfoot.mouseClicked(null))
        {
            addScore();
        }
danpost danpost

2013/1/16

#
danbyization wrote...
So change the if statement to the following:
if(Greenfoot.mouseClicked(null))
        {
            addScore();
        }
Is that a question? Is it performing like you want, now?
danpost danpost

2013/1/16

#
Have you tried putting 'if' block within an 'act' method:
public void act()
{
    if (Greenfoot.mouseClicked(null))
    {
        addScore();
    }
}
The 'act' methods are what 'run' your scenario. Any World or Actor sub-class can have one (actually they already have one that is inherited from the World and Actor classes; but they are just empty methods, there). You can write your own code to override them.
danbyization danbyization

2013/1/16

#
Thanks danpost that works perfect now thank you so much
You need to login to post a reply.