Java Applet Help - Making "Snake" Game
I am required to design a Java applet resembling the classic game "Snake" for a computer science project. We are required to use arrays to conjunct with the position of the "snake" on the grid. Right now, we are the stage where we are trying to tell the program to disallow the snake to move down (using the arrows on the keyboard and a KeyListener) if it is moving up, and disallow the snake to move right if it is moving left (and vice versa). Could anyone help me figure out what is the best way to approach this? I've tried booleans, but to no avail. I also tried using a single integer, that would change to four different values depending on the direction, and I made some progress, but to no avail. If someone could shed some light upon this, I would really appreciate it. I will copy the code, and explain any part of it if necessary.
//Coded by: Ademiwalore Mojiminiyi
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class SnakeGame extends Applet implements KeyListener{
int field[][] = new int[25][25];
int xpos, ypos;
int direction;
boolean end;
boolean stop = false;
int stopmove = 0;
int gameOver = 0;
public void init(){
addKeyListener(this);
for (int x = 0; x < 25; x++){
for (int y = 0; y < 25; y++){
field[x][y] = 0;
}
}
field[7][7] = 1;
setSize(350,350);
}
public void paint(Graphics g) {
g.drawRect(0, 0, 250, 250);
for (int x = 0; x < 25; x++){
for (int y = 0; y < 25; y++){
if (field[x][y] == 1){
if (stopmove == 0){
g.setColor(Color.black);
g.fillRect(x*10, y*10, 10, 10);
}
else{
g.setColor(Color.red);
g.fillRect(x*10, y*10, 10, 10);
}}}
if (gameOver == 1){
g.setColor(Color.black);
g.drawString("GAME OVER", 50, 50);
}}}
public void keyPressed(KeyEvent e) {
// if (e.getKeyCode() == 37 || e.getKeyCode() == 38){
// direction = 1;
//}
// if (e.getKeyCode() == 39 || e.getKeyCode() == 40){
// direction = 2;
// }
for (int x = 0; x < 25; x++){
for (int y = 0; y < 25; y++){
if (field[x][y] == 1 && stop == false){
xpos = x;
ypos = y;
}
else{
end = true;
}}}
if (e.getKeyCode() == 38 && stopmove == 0){ //up/
direction = 1;
if (ypos > 0){
field[xpos][ypos-1] = 1;
field[xpos][ypos] = 0;
repaint();
}
else{
end = false;
}}
if (e.getKeyCode() == 40 && stopmove == 0){ //down//
direction = 2;
if (ypos < 24){
field[xpos][ypos+1] = 1;
field[xpos][ypos] = 0;
repaint();
}
else{
end = false;
}}
if (e.getKeyCode() == 37 && stopmove == 0){ //left//
direction = 3;
if (xpos > 0){
field[xpos-1][ypos] = 1;
field[xpos][ypos] = 0;
repaint();
}
else{
end = false;
}}
if (e.getKeyCode() == 39 && stopmove == 0){ //right//
direction = 4;
if (xpos < 24){
field[xpos+1][ypos] = 1;
field[xpos][ypos] = 0;
repaint();
}
else{
end = false;
}}
if (end == false){
stop = true;
gameOver = 1;
stopmove = 1;
repaint();
}}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}}