Reputation: 195
So I'm making a snake game, I have the controls, and basic gui. The problem is that when trying to paint the fruit, it won't stop painting. What I want it to do is when the player collides with the fruit it adds score. To do that I need the fruit first to only paint once, how?
Basic paintComponent.
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.RED);
g.fillRect(x, y, 20, 20);
g.drawRect(fruit.getXLoc(), fruit.getYLoc(), 10, 10);
fruitCollected(); //method saying if you go into a certain range of the fruit add score;
g.drawString("Score: " + score + fruit.getXLoc() + fruit.getYLoc(), 150, 150);
if(gameover() == true) {
this.setBackground(Color.ORANGE);
}
}
In another class I have the getXLoc and getXLoc
public class FruitLocation {
int xSize = 580; //x and y boundary for placing fruit
int ySize = 350;
int xLoc;
int yLoc;
public int getXLoc() {
int xLoc = (int) (Math.random() * xSize) ;
return xLoc;
}
public int getYLoc() {
int yLoc = (int) (Math.random() * ySize);
return yLoc;
}
}
Upvotes: 0
Views: 474
Reputation: 347214
Your basic problem is you calling methods within the paint
method that will cause a repaint
event to be generated, again and again and...
Start by removing the calls to setBackground
Next, don't change the state of the fruit outside of the "main-loop", that is, don't do...
public int getXLoc() {
int xLoc = (int) (Math.random() * xSize) ;
return xLoc;
}
Because a paint cycle may be caused by any number of reasons, many of which you don't control, you want these methods to return a concrete value. They should be update as part of your "main-loop" logic and you will need to supply appropriate methods to allow this to occur.
On a side note, you shadowing your variables. What I mean is, when you can the xLoc
value in the getXLoc
method, it is not changing the xLoc
instance variable of the Fruit
class, for example...
int xLoc;
public int getXLoc() {
int xLoc = (int) (Math.random() * xSize) ;
^--- Shadowing the instance variable...
return xLoc;
}
Upvotes: 2
Reputation: 4206
The reason it's jumping is because you're drawing the rectangle using the getXLoc
and getYLoc
methods. These methods, however, generate a new random number each time. Instead, set the x and y locations to a value in the Fruitlocation
constructor, and make a new method that generates new random values. The code for getXLoc
should look as follows:
public int getXLoc(){
return xLoc;
}
Upvotes: 2