I am an in-school amateur making a snake game in java, it is not complete and i have run into a problem that i cant seem to fix. the first and second parts of the body show up just fine after eating the target, but after that they do not.
code that adds a body part:
public void addBody(int x, int y) {
snekBody.add(new JPanel());
snekBody.get(snekBody.size() - 1).setBackground(new Color(new Random().nextInt(255), new Random().nextInt(255), new Random().nextInt(255)));
snekBody.get(snekBody.size() - 1).setVisible(true);
snekBody.get(snekBody.size() - 1).setBounds(x*score, y*score, BODY_WIDTH, BODY_HEIGHT);
game.add(snekBody.get(this.snekBody.size() - 1));
revalidate();
}
}
code that moves the body parts(moveUp, moveDown, etc.:
public synchronized void moveRight(int x, int y) {
timer++;
while (!this.right) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
head.setBounds(x, y, 20, 20);
xCoords.add(x);
yCoords.add(y);
//snekBody is an ArrayList of type JPanel
for(int i = 0; i < snekBody.size(); i++) {
if (i > 0) {
snekBody.get(i).setBounds(xCoords.get(timer-(10*score)), yCoords.get(timer-(10*score))+5, BODY_WIDTH, BODY_HEIGHT);
} else {
snekBody.get(i).setBounds(xCoords.get(timer-10), yCoords.get(timer-10)+5, BODY_WIDTH, BODY_HEIGHT);
}
}
repaint();
notifyAll();
revalidate();
}
code that calls addBody:
if (snek.up) {
snek.addBody(snek.xCoords.get(snek.timer-20), snek.yCoords.get(snek.timer-20));
the second picture is the snake when more than two targets have been eaten. the panels for the body just stop showing up. The first picture is the snake when two targets have been eaten
Turns out that the panels were showing up on top of each other, thus why i could not see them.