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

2014/10/12

My Pong score counter isn't working

jbrown401 jbrown401

2014/10/12

#
Hi I'm jerry. For my class i have to make a classic Pong game from scratch. I nearly have it all done except for my score counter. I've tried everything i know but this is the first real game I've programmed on Greenfoot. I have two seperate scores and i need to make it so if the ball misses the paddle and hits the top or bottom of the screen, a point will be added but i can't find out the correct way to do this. I've tried multiple "if" statements and everything i could think of. Please help, it would be much appreciated. Thank you
NikZ NikZ

2014/10/12

#
1
2
3
if (getX() == ?) {
    score++;
}
Should do it. And also:
1
getImage().drawString("Score " + score, ?, ?);
Make sure you have set the Color and Font, first! Or you can just do
1
getWorld().showText("Score " + score, ?, ?);
jbrown401 jbrown401

2014/10/12

#
What would you put for the score to add to one specific score counter? I have two seperate scores called "Score1" and "score2"
danpost danpost

2014/10/12

#
I would add instance reference fields in your subclass of World for both counters (not the values, but the objects that hold the values). Add methods to increment the values in each one in your World subclass also. Then you should be able to call whichever method you need depending on which edge is hit.
jbrown401 jbrown401

2014/10/12

#
Sorry i am very new to programming. So what you mean by instance reference field is "Score1 scoreObj1 = new Score1();" ? Also for adding the method to the World subclass wou it be like an "if" statement like the one you showed me? (I feel stupid but I'm new to this lol)
danpost danpost

2014/10/12

#
By instance reference field, yes. However, you do not need a 'Score1' and a 'Score2' class; you just need a 'Score' class that you create two instance objects with:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// in your subclass of World (inside class/outside methods)
private Score scoreObj1 = new Score();
private Score scoreObj2 = new Score();
// in the constructor block
addObject(scoreObj1, 100, 30);
addObject(scoreObj2, 100, getHeight()-30);
// and add get methods
public Score getScoreObj1()
{
    return scoreObj1;
}
 
public Score getScoreObj2()
{
    return scoreObj2;
}
The 'get' methods will allow objects in your world to access the score objects to get/set their values. If your world is called 'MyWorld',, then from an Actor subclass, you could do something like this within a method:
1
((MyWorld)getWorld()).getScoreObj1().add(1);
provided the actor using the code was in the world and you had an 'add' method in the 'Score' class.
You need to login to post a reply.