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

2016/12/7

Problems with counters

rn42v1r rn42v1r

2016/12/7

#
Hi there, I had the innovative and creative idea of making the game PONG... like noone else did before, you know. However I can't get my score counters to work. I hope you can help me with my code...
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class Ball extends Actor
{   
    int scoreLeft = 0;
    int scoreRight = 0;
    /**
     * Act - do whatever the Ball wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        move(4);
        scorePoint();
        endGame();
    }    
    
    /**
     * Tests if the ball hits the left edge of the world.
     */
    public boolean isAtLeftEdge()
    {
        if (getX() <= 0)
            return true;
        else 
            return false;
    }
    
    /**
     * Tests if the ball hits the right edge of the world.
     */
    public boolean isAtRightEdge()
    {
        if (getX() >= getWorld().getWidth()-1)
            return true;
        else
            return false;
    }
    
    /**
     * If the ball hits either the right or left edge of the world
     * a point is scored for the player of the opposite side.
     * A new Ball is then added to the game while the old one is being removed. 
     */
    public void scorePoint()
    {
        if (isAtLeftEdge() || isAtRightEdge())
        {   
            if (isAtLeftEdge())
            {
                scoreRight++;
            }
            if (isAtRightEdge())
            {
                scoreLeft++;
            }
            getWorld().addObject(new Ball(), 350, 200);
            getWorld().removeObject(this);
        }
    }
    
    /**
     * As one player reaches a score of 5 the game ends.
     */
    public void endGame()
    {
        if (scoreRight == 5)
        {
            Greenfoot.stop();
        }
        if (scoreLeft == 5)
        {
            Greenfoot.stop();
        }
    }
}
danpost danpost

2016/12/7

#
The problem is that each Ball object created has its own scoreLeft and scoreRight fields. Either continue to use the same ball over and over to retain the same fields or place the fields in your World subclass.
rn42v1r rn42v1r

2016/12/7

#
...well that makes sense, I simply replaced
getWorld().addObject(new Ball(), 350, 200);
getWorld().removeObject(this);
with
setLocation(350, 200); //(the center of my world)
and it works just fine, thanks alot :)
You need to login to post a reply.