I have a snake game set up in Java and I wanted to be able to toggle between the ability to go through the sides and pop out the opposite side and the classic version where you die when you hit the border. The problem is that my snake keeps going one spot after the border; how do I fix this?
This is one of the parts of my code, that acts when the right arrow key is pressed:
if(right) {
for(int i = lengthofsnake - 1; i >= 0; i--) {
snakeylength[i+1] = snakeylength[i];
}
for(int i = lengthofsnake; i >= 0; i--) {
if(i == 0) {
snakexlength[i] = snakexlength[i] + 25;
}
else {
snakexlength[i] = snakexlength[i-1];
}
if(!borderGameplay) {
if(snakexlength[i] > 850) {
snakexlength[i] = 25;
}
}
else {
if(snakexlength[i] > 850) {
borderDead = true;
}
}
}
repaint();
}
borderGameplay
is the variable that you can toggle to have borders on and off, and borderDead
is used in this if
statement:
if(borderDead) {
if(score > highScore) {
highScore = score;
}
playing = false;
dead();
deadGraphic(g);
}
This is my deadGraphic(g)
:
public void deadGraphic(Graphics g) {
g.setColor(Color.WHITE);
g.setFont(new Font("arial", Font.BOLD, 50));
g.drawString("Game Over", 300, 300);
g.setFont(new Font("arial", Font.BOLD, 20));
g.drawString("Press \"Space\" To Restart And \"Enter\" To Toggle Borders", 160, 340);
if(borderGameplay) {
g.drawString("Borders ON", 370, 380);
}
else {
g.drawString("Borders OFF", 365, 380);
}
}
This is my dead()
:
public void dead() {
right = false;
left = false;
up = false;
down = false;
dead = true;
score = 0;
moves = 0;
}
And finally, my JFrame:
JFrame obj = new JFrame("Snake");
gameplay Gameplay = new gameplay();
obj.setBounds(10, 10, 905, 700);
obj.setBackground(Color.DARK_GRAY);
obj.setResizable(false);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.add(Gameplay);
obj.setVisible(true);
If you need to see other parts of my code, please tell me; this question is already really long, and my total code is 550 lines.
snakexlength[i] > 850
to>=
instead. \$\endgroup\$