# How to set up borders in snake game

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) {
}
}
}

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;
}


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;
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.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.

• Try changing snakexlength[i] > 850 to >= instead. Oct 8 '17 at 15:58
• Already tried that, the problem is that they will die when they are beside the barrier and I want them to only die if they go into the barrier Oct 9 '17 at 16:17