Basic Snake Game

Question about my lengthening the snake

Page 1 of 1

11 Replies - 6525 Views - Last Post: 18 October 2010 - 09:24 PM Rate Topic: -----

#1 blueskyjunkie  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 27-February 09

Basic Snake Game

Posted 17 October 2010 - 07:25 PM

Hey everyone,

I have a project due in class Tuesday, and I've kinda hit a wall. I'm making the classic game Snake, and I've gotten most of the basic game functions working aside from making the snake grow when it eats an apple. I keep getting an out of bounds exception for every approach I've tried. The code compiles and everything, but when I eat the first apple it freezes and gives me the exception.

Here's my grow method and my main method. If it would be helpful for me to post the rest of my code just let me know. And the DrawingPanel and Graphics are classes written by the author of the textbook my class uses.

  public static void main(String[] args) {

        DrawingPanel panel = new DrawingPanel(SCREENW, SCREENH);
        Graphics g = panel.getGraphics();

        //The main game loop variable
        boolean play = true;
        
        Point pApple = new Point();
        Point[] pSnake;
        
        //Length of sides of the square apple
        int appleSide = 10;
        
        //Length of sides of the square snake head
        int snakeSide = 10;
        
        //Number of pixels the snake head moves each time
        int velocity = 10;
        
        //Variable to slow down the snake to a playable speed
        int sleepTime = 50;

        //These points are just to test the functionality. Once I finish I'll go back and make the initial points random
        Point p1 = new Point(70, 30);
        Point p2 = new Point(60, 30);
        Point p3 = new Point(50, 30);
        Point p4 = new Point(40, 30);
        Point p5 = new Point(30, 30);
        Point p6 = new Point(20, 30);
        Point p7 = new Point(10, 30);
        
        //Sets the initial point for the apple
        pApple = appleEaten(appleSide);
        
        //Set the initial points for the snake
        pSnake = new Point[]{p1, p2, p3, p4, p5, p6, p7};

        
        //Main game loop
        while (play) {
            //Draws the background of the game screen
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, SCREENW, SCREENH);

            //Draws the apple to the screen
            drawApple(panel, g, pApple, appleSide);
            
            //Sets the direction of the snake to move depending on which arrow key is hit (I know the method name is kinda misleading. I just haven't changed it from my initial idea
            moveSnake(panel);
            //Updates the snakes coordinates depending on which flag is true and draws it to the screen
            drawSnake(panel, g, pSnake, snakeSide, velocity, sleepTime);
            //Checks to see if snake head hits the snake body or a screen boundary
            checkLose(pSnake);
            
            //If the snake head is at the same point as the apple
            if (pSnake[0].equals(pApple)) {
                //A new apple is created
                pApple = appleEaten(appleSide);
                //The snake grows by one segment
                pSnake = grow(pSnake);
                //The snake moves faster
                sleepTime -= 5;
            }

            panel.copyGraphicsToScreen();

        }

    }



    public static Point[] grow(Point[] pSnake) {
        //Create a new snake one index longer than the original snake
        Point[] newPSnake = new Point[pSnake.length + 1];

        //Sets the new snake equal to the old snake
        for(int i = 0; i < pSnake.length; i++)
        {
            newPSnake[i] = pSnake[i];
        }

        //Sets the last index of the new snake depending on which direction the snake is moving
        if (right) {
            newPSnake[4].setLocation(newPSnake[newPSnake.length - 2].getX() - 10, newPSnake[newPSnake.length - 2].getY());
        }
        if (left) {
          newPSnake[newPSnake.length - 1].setLocation(pSnake[pSnake.length - 1].getX() + 10, pSnake[pSnake.length - 1].getY());
        }
        if (up) {
          newPSnake[newPSnake.length - 1].setLocation(pSnake[pSnake.length - 1].getX(), pSnake[pSnake.length - 1].getY() + 10);
        }
        if (down) {
          newPSnake[newPSnake.length - 1].setLocation(pSnake[pSnake.length - 1].getX(), pSnake[pSnake.length - 1].getY() - 10);
        }

        return newPSnake;
  }


Thanks for any help you guys can give!!

-M@

Is This A Good Question/Topic? 0
  • +

Replies To: Basic Snake Game

#2 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2872
  • View blog
  • Posts: 11,031
  • Joined: 15-July 08

Re: Basic Snake Game

Posted 17 October 2010 - 07:29 PM

First off, this is the Java Programmers forum, not the Java Help forum.
*** Moved ***

About your problem - you are using a static array to store your points. If you add any points, the array will not grow to match, thus giving you an OutOfBounds exception. For your particular case, I suggest using a LinkedList, as it is great for doing things like adding information on to the end of itself.

If you don't know much about LinkedLists, macosxnerd101 has a great tutorial on it here:
http://www.dreaminco...-list-tutorial/
Was This Post Helpful? 0
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Basic Snake Game

Posted 17 October 2010 - 07:34 PM

Better to use JLabel in a GridLayout. A lot lot easier
http://www.dreaminco...snippet4151.htm
This code can be fine tuned to hide the fact that a GridLayout is used
Was This Post Helpful? 0
  • +
  • -

#4 blueskyjunkie  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 27-February 09

Re: Basic Snake Game

Posted 17 October 2010 - 07:42 PM

Sorry I didn't see the help forum. Thanks for the link! Always enjoy learning something new. The only thing is for this assignment I'm pretty sure I have to use Arrays. It specifically says not to use ArrayLists and since LinkedLists look pretty similar in the fact that they have variable lengths, I don't really want to risk using them. Here is the exact criteria for the assignment regarding this: "Always keep the active objects in array indices 0 through (numberOfActiveObjects-1). You'll want a method that shifts the array when something is removed. You may NOT use an ArrayList."

I see what you're saying about how line 61 doesn't work because my original pSnake array has a fixed length. Is there any solution to this that still allows me to use normal arrays? Would something like creating a new array for each time it grows work?

Point[] pSnakeNew = grow(pSnake);

EDIT: Nevermind this won't work because I would need to have a different name for each new array created. I still feel like there has to be a solution using basic arrays though.

This post has been edited by blueskyjunkie: 17 October 2010 - 07:45 PM

Was This Post Helpful? 0
  • +
  • -

#5 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Basic Snake Game

Posted 17 October 2010 - 07:51 PM

ArrayList are just easy to use resizable array.
You can mimic the behaviour quite easily with regular arrays.
Don't think/remenber if my Code Snippet uses ArrayList but would be easy to convert it for not using them
Was This Post Helpful? 0
  • +
  • -

#6 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2872
  • View blog
  • Posts: 11,031
  • Joined: 15-July 08

Re: Basic Snake Game

Posted 17 October 2010 - 07:53 PM

Well, for adding, if you are allowed to, you could make a larger array and then copy the elements over and then set that new array as the old one. But that's essentially writing your own ArrayList. So it does look like you are doing it correctly. I was merely suggesting a LinkedList as a better design choice. But, I understand school constraints. Just, in your grow() method, be very careful about which indexes that you access to make sure they all exist. Notice that in one of them, you grab array.length-2. This means your array HAS to be larger than 1 at all times.
Was This Post Helpful? 0
  • +
  • -

#7 blueskyjunkie  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 27-February 09

Re: Basic Snake Game

Posted 17 October 2010 - 08:10 PM

Yeah the resiable array idea is the route I'm trying to take. But believe me if my school didn't care I'd be all over ArrayLists or LinkedLists lol.

I feel like my issue is coming from line 61. Even though I return the newPSnake method from grow, the pSnake method length is still the same, so I can't set it equal to the newPSnake that grow returns. And I can't think of a logical way around that. Sorry if that doesn't make any sense.

And as far as the line in my grow method with "array.length-2" that is me trying to set the last value of the array to the second to last value plus a certain amount of pixels depending on which way the snake is moving. That way the new segment of the snake is at the end.
Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Basic Snake Game

Posted 17 October 2010 - 08:24 PM

Your grow() mthod seems OK to me but for that hardcoded value
newPSnake[4].
Was This Post Helpful? 1
  • +
  • -

#9 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2872
  • View blog
  • Posts: 11,031
  • Joined: 15-July 08

Re: Basic Snake Game

Posted 17 October 2010 - 08:27 PM

View Postpbl, on 17 October 2010 - 10:24 PM, said:

Your grow() mthod seems OK to me but for that hardcoded value
newPSnake[4].


I'm so blind. Nice catch there!
Was This Post Helpful? 0
  • +
  • -

#10 blueskyjunkie  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 27-February 09

Re: Basic Snake Game

Posted 17 October 2010 - 08:34 PM

View Postpbl, on 17 October 2010 - 07:24 PM, said:

Your grow() mthod seems OK to me but for that hardcoded value
newPSnake[4].


Oh shoot that was from me playing around with set values to see if I could get it to work that way.

I've changed it to newPSnake[newPSnake.length - 1] and it's still giving me the out of bounds exception :\.
Was This Post Helpful? 0
  • +
  • -

#11 blueskyjunkie  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 27-February 09

Re: Basic Snake Game

Posted 18 October 2010 - 02:37 PM

Please someone's gotta have some idea..?
Was This Post Helpful? 0
  • +
  • -

#12 Luckless  Icon User is offline

  • </luck>
  • member icon

Reputation: 292
  • View blog
  • Posts: 1,146
  • Joined: 31-August 09

Re: Basic Snake Game

Posted 18 October 2010 - 09:24 PM

your other three directional statements try to set the x and y location relative to length - 1, even though that is the exact point you are dealing with. try changing those to length - 2
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1