Results 1 to 16 of 16
  1. #1
    Alphimeda is offline Member
    Join Date
    Apr 2010
    Posts
    9
    Rep Power
    0

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

    }}

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Alphimeda View Post
    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.

    Hello and welcome to the forum!
    When you say that you've "tried booleans", etc, can you show us this and any other attempts? It's the best way to know what you may be doing wrong, what if anything needs to be corrected.

    Also please read the link in my signature on using code tags. Much luck!

  3. #3
    Alphimeda is offline Member
    Join Date
    Apr 2010
    Posts
    9
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Hello and welcome to the forum!
    When you say that you've "tried booleans", etc, can you show us this and any other attempts? It's the best way to know what you may be doing wrong, what if anything needs to be corrected.

    Also please read the link in my signature on using code tags. Much luck!
    Thanks a lot for the reply.

    Well, basically, the code I posted above has these main functions: a box appears on a certain point of an applet window, and is initiated by if statements and arrays.
    Java Code:
    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);
                        }
    The array is 25 x 25, and the x and y variables are used later on to find the position of the array in the program.
    Java Code:
    for (int x = 0; x < 25; x++){
                for (int y = 0; y < 25; y++){
                    field[x][y] = 0;
    The integers you can see below represent the box's position when moved with arrow keys (xpos and ypos), a "direction" integer that corresponds with what I'm trying to do with the program riht now, an "end" boolean that tells the program when the box has exceeded the parameters of the game, a "stop" boolean that allows the box to move, and "stopmove" and "gameOver" integers that tell the program to display a message and disallow any further movement of the box when the person fails the game (i.e. exceeds the parameters of the grid in the snake game).
    Java Code:
    int field[][] = new int[25][25];
        int xpos, ypos;
        int direction;
        boolean end;
        boolean stop = false;
        int stopmove = 0;
        int gameOver = 0;
    Now, below is the entire code.
    Java Code:
    //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) {
    
        }}
    As I said before, the current goal is to prevent the box from moving in the opposite direction of any direction it's moving in. I do not remember what I tried with booleans, but I can demonstrate what I've been trying with this "direction" integer. Here is the integer:
    Java Code:
    public class SnakeGame extends Applet implements KeyListener{
        int field[][] = new int[25][25];
        int xpos, ypos;
        int direction;
    And as you can see in my KeyPressed code, I tried to correlate with the direction integer. This code basically says that if the box goes up or left, the direction equals one thing, but if the box moves down or right, it equals another.
    Java Code:
           // if (e.getKeyCode() == 37 || e.getKeyCode() == 38){
              // direction = 1;
           //}
           // if (e.getKeyCode() == 39 || e.getKeyCode() == 40){
    
             // direction = 2;
          // }
    That I idea did not work out. So I started trying another idea, in which the direction variable equals four different numbers when going in the four different directions (up, down, left, right). So far I haven't really expanded on that. Shown below:
    Java Code:
            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;
                }}
    Does any of that help? I hope so.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    For starters, you need to get rid of "magic numbers" such as 37, 38, and directions 1, 2, ... The reason being is you want to be able to lay this code aside for a week or two, and when you come back and read it understand what you wrote. If you have a bunch of meaningless numbers scattered about, it will confuse you, and may confuse your instructor (even worse!). Also, I like your idea of storing the direction that the snake is using in a directions variable, but again, avoid using magic numbers here. One thing that you could use are the same constants for the key codes and for the directions.

    So instead of this:
    Java Code:
        if (e.getKeyCode() == 40 && stopmove == 0) { // down//
          direction = 2;
          //....

    try this:
    Java Code:
        if (e.getKeyCode() == KeyEvent.VK_DOWN && stopmove == 0) { // no need for comment!
          direction = KeyEvent.VK_DOWN;

    Then you could simply check direction before moving:
    Java Code:
        if (e.getKeyCode() == KeyEvent.VK_DOWN && direction != KeyEvent.VK_UP && stopmove == 0) {
          direction = KeyEvent.VK_DOWN;

    Best of luck!

  5. #5
    Alphimeda is offline Member
    Join Date
    Apr 2010
    Posts
    9
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    For starters, you need to get rid of "magic numbers" such as 37, 38, and directions 1, 2, ... The reason being is you want to be able to lay this code aside for a week or two, and when you come back and read it understand what you wrote. If you have a bunch of meaningless numbers scattered about, it will confuse you, and may confuse your instructor (even worse!). Also, I like your idea of storing the direction that the snake is using in a directions variable, but again, avoid using magic numbers here. One thing that you could use are the same constants for the key codes and for the directions.

    So instead of this:
    Java Code:
        if (e.getKeyCode() == 40 && stopmove == 0) { // down//
          direction = 2;
          //....

    try this:
    Java Code:
        if (e.getKeyCode() == KeyEvent.VK_DOWN && stopmove == 0) { // no need for comment!
          direction = KeyEvent.VK_DOWN;

    Then you could simply check direction before moving:
    Java Code:
        if (e.getKeyCode() == KeyEvent.VK_DOWN && direction != KeyEvent.VK_UP && stopmove == 0) {
          direction = KeyEvent.VK_DOWN;

    Best of luck!
    I see what you did there, but the problem is that we are not allowed to use types of code that we have not learned about in class. So basically, I'm limited to using kinds of values (i.e. integers, booleans, etc.) to perform the operation. So if any advice could be given that utilizes these kinds of coding, and not ones that are beyond what I've learned in class, then that would be more helpful.

    Also, I put the comments there to remind myself what the keycodes represent, as I have not bothered to memorize them yet. I probably should though; lol.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Alphimeda View Post
    I see what you did there, but the problem is that we are not allowed to use types of code that we have not learned about in class. So basically, I'm limited to using kinds of values (i.e. integers, booleans, etc.) to perform the operation. So if any advice could be given that utilizes these kinds of coding, and not ones that are beyond what I've learned in class, then that would be more helpful.
    My suggestions actually don't use any new types. The KeyEvent.VK_XXX constants are nothing more than int constants that are defined in the Swing library. If you' rather have your program use its own constants, then by all means use them, just still it's a good idea to avoid using magic numbers.


    Also, I put the comments there to remind myself what the keycodes represent, as I have not bothered to memorize them yet. I probably should though; lol.
    My note about the "no need for comments" simply means that if you write code using variable and constant names that make sense, the code becomes self commenting. So if you use the Swing VK_XXXX constants, you know which direction the int represents, and so that's one less comment that you have to write. If you still want to add a comment, then by all means do so.

    Much luck!

    e.g.,
    Java Code:
    public class SnakeGame extends Applet implements KeyListener {
      public static final int UP = 38;
      public static final int DOWN = 40;
      //.....
    Last edited by Fubarable; 04-03-2010 at 03:48 PM.

  7. #7
    Alphimeda is offline Member
    Join Date
    Apr 2010
    Posts
    9
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    My suggestions actually don't use any new types. The KeyEvent.VK_XXX constants are nothing more than int constants that are defined in the Swing library. If you' rather have your program use its own constants, then by all means use them, just still it's a good idea to avoid using magic numbers.



    My note about the "no need for comments" simply means that if you write code using variable and constant names that make sense, the code becomes self commenting. So if you use the Swing VK_XXXX constants, you know which direction the int represents, and so that's one less comment that you have to write. If you still want to add a comment, then by all means do so.

    Much luck!

    e.g.,
    Java Code:
    public class SnakeGame extends Applet implements KeyListener {
      public static final int UP = 38;
      public static final int DOWN = 40;
      //.....
    I guess I will try and fiddle around with those int constants. Thanks a bunch.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Alphimeda View Post
    I guess I will try and fiddle around with those int constants. Thanks a bunch.
    You're quite welcome. Please let us know if after changing code you are still stuck and also how things eventually work out with this project. Much luck.

  9. #9
    Alphimeda is offline Member
    Join Date
    Apr 2010
    Posts
    9
    Rep Power
    0

    Default

    So, I tried what you suggested Fubarable, but with "magic numbers" instead, because the static integers confused me a bit, and given the level that my particular class is at as of present, it's probably better that I do use magic numbers. So I coded something similar: having the direction variable equal a specific number (that corresponds with the four different directions), and then having the program check the direction before moving. But what exactly am I missing/doing wrong?
    Java Code:
            if (e.getKeyCode() == 38 && stopmove == 0){ //up/
                direction = 1;
            if (e.getKeyCode() == 38 && direction != 2){
                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 (e.getKeyCode() == 40 && direction != 1){
                direction = 2;
            }
                if (ypos < 24){
                    field[xpos][ypos+1] = 1;
                    field[xpos][ypos] = 0;
                    repaint();
                }
                else{
                    end = false;
    Apparently, I am missing something. But what, exactly? I cannot tell the program to make the direction variable equal something else, because if I did that for all four different directions, then that would render the box immovable (the box would be adhering to four different rules that all go against each other). So... suggestions?

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Think about what your logic is doing here:

    Java Code:
            if (e.getKeyCode() == 38 && stopmove == 0){ //up/
                direction = 1;
            if (e.getKeyCode() == 38 && direction != 2){
                direction = 1;
            }
    Walk through this code with direction being any one of the four possible values, and what will happen vs what should happen. Also, what about that closing parenthesis?

  11. #11
    Alphimeda is offline Member
    Join Date
    Apr 2010
    Posts
    9
    Rep Power
    0

    Default

    Well, what that code demonstrates is that if the up key is pressed and the box does not exceed the parameters of the game, then the direction variable equals 1. And, if the direction variable does not equal 2 (which occurs when the down key is pressed), then the direction variable still equals 1. Hmm... now that I think of it, that should not really change anything - and it doesn't. Plus, the direction variable resets to a different variable every time a key is pressed, so nothing is actually happening. So I kind of see where I've gone wrong.

    I'm not exactly sure what the closing parenthesis means either, so I do not know how to comment on that.

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Alphimeda View Post
    Well, what that code demonstrates is that if the up key is pressed and the box does not exceed the parameters of the game, then the direction variable equals 1. And, if the direction variable does not equal 2 (which occurs when the down key is pressed), then the direction variable still equals 1. Hmm... now that I think of it, that should not really change anything - and it doesn't. Plus, the direction variable resets to a different variable every time a key is pressed, so nothing is actually happening. So I kind of see where I've gone wrong.
    I knew you would. :)

    I'm not exactly sure what the closing parenthesis means either, so I do not know how to comment on that.
    The second if statement closes immediately -- has an opening parenthesis, "{" a single statement and then immediate after closes, "}". I should think that you might want to enclose much of the code below in this block rather than ending abruptly.

  13. #13
    Alphimeda is offline Member
    Join Date
    Apr 2010
    Posts
    9
    Rep Power
    0

    Default

    I see what you mean.

    Ugh; I've been at this program for quite some time now, and still to no avail.
    A question please, Fubarable: when you were saying that I should "check direction before moving", should I do that in the same if statement, or a separate one?

    >.<

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Alphimeda View Post
    I see what you mean.

    Ugh; I've been at this program for quite some time now, and still to no avail.
    A question please, Fubarable: when you were saying that I should "check direction before moving", should I do that in the same if statement, or a separate one?

    >.<
    The same as the first if statement? Yes that could work, also it could work if you nested if statements.

  15. #15
    Alphimeda is offline Member
    Join Date
    Apr 2010
    Posts
    9
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    The same as the first if statement? Yes that could work, also it could work if you nested if statements.
    "Nested" if statements?

  16. #16
    Alphimeda is offline Member
    Join Date
    Apr 2010
    Posts
    9
    Rep Power
    0

    Default

    I have attempted the following:
    Java Code:
            if (e.getKeyCode() == 38 && stopmove == 0){ //up
                direction = 1;
            if (e.getKeyCode() == 38 && direction != 2){ //up
                direction = 1;
                if (ypos > 0 && direction == 1 && direction != 2){
                    field[xpos][ypos-1] = 1;
                    field[xpos][ypos] = 0;
                    repaint();
                }
                else{
                    end = false;
                }}
            if (e.getKeyCode() == 40 && stopmove == 0){ //down
                direction = 2;
            if (e.getKeyCode() == 40 && direction != 1){
                direction = 2;
                if (ypos < 24 && direction == 2 && direction != 1){
                    field[xpos][ypos+1] = 1;
                    field[xpos][ypos] = 0;
                    repaint();
                }
                else{
                    end = false;
                }}
            if (e.getKeyCode() == 37 && stopmove == 0){ //left
                direction = 3;
            if (e.getKeyCode() == 37 && direction != 4){
                direction = 3;
                if (xpos > 0 && direction == 3  && direction != 4){
                    field[xpos-1][ypos] = 1;
                    field[xpos][ypos] = 0;
                    repaint();
                }
                else{
                    end = false;
                }}
            if (e.getKeyCode() == 39 && stopmove == 0){ //right
                direction = 4;
            if (e.getKeyCode() == 39 && direction != 3){
                direction = 4;
                if (xpos < 24 && direction == 4  && direction != 3){
                    field[xpos+1][ypos] = 1;
                    field[xpos][ypos] = 0;
                    repaint();
                }
                else{
                    end = false;
                }}
    But for some reason, when I try to run the program, the box can only move upwards. Is my idea flawed? Or is it an issue with the placement of my brackets? Or is it both of those things?
    Last edited by Alphimeda; 04-04-2010 at 07:36 PM.

Similar Threads

  1. Replies: 2
    Last Post: 08-05-2010, 04:49 AM
  2. Java, Military Format using "/" and "%" Operator!!
    By sk8rsam77 in forum New To Java
    Replies: 11
    Last Post: 02-26-2010, 03:03 AM
  3. Replies: 0
    Last Post: 12-29-2009, 03:10 PM
  4. Making A Set Of Classes "Importable"
    By JDCAce in forum Advanced Java
    Replies: 4
    Last Post: 12-05-2008, 09:11 AM
  5. Replies: 1
    Last Post: 10-20-2008, 07:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •