# Help with the Snake in a Snake Game

• September 25th, 2012, 07:01 PM
godlynom
Help with the Snake in a Snake Game
Hello all, I am in the process of making my very own Snake game. It is going quite well. I have taken Computer Math in my junior year of high school and now during my senior year I am taking AP Computer Science. I was doing fine with the game until I came across this problem. I am, for some reason, having trouble getting a "snake" onto a panel that I have. The "food" works fine and appears randomly within the frame, but I created the snake in the panel using the paint component. The snake moves, but I do not know how to work on a collide method with the "snake" and the "food" if it is created in the paint. Thus I tried creating a SnakeBody class where the snake then could be moved around, but it would not show up on the panel, just the food showed up. Can someone help me get a SnakeBody class up and running or a way to work on a collide method between and object and a paint? That is all I need, I can do the rest. Here is my code, it is a tiny bit sloppy from all the trial and errors:
Food Class:
Code :

```import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*;   public class Food { double x = 0, y = 0; private static final int FRAME = 700; private double myX; // x and y coordinates of center private double myY; private double myDiameter; private Color myColor; private double myRadius;   public Food() { myX = 200; myY = 200; myDiameter = 25; myColor = Color.RED; myRadius = myDiameter/2; } public Food(double x, double y, double d, Color c) { myX = x; myY = y; myDiameter = d; myColor = c; myRadius = d/2; } public double getX() { return myX; } public double getY() { return myY; } public double getDiameter() { return myDiameter; } public Color getColor() { return myColor; } public double getRadius() { return myRadius; } // modifier methods public void setX(double x) { myX = x; } public void setY(double y) { myY = y; } public void setColor(Color c) { myColor = c; } public void setDiameter(double d) { myDiameter = d; myRadius = d/2; } public void setRadius(double r) { myRadius = r; myDiameter = 2*r; } // instance methods public void jump(int rightEdge, int bottomEdge) { // moves location to random (x, y) within the edges myX = (Math.random()* (rightEdge-myDiameter) + myRadius); myY = (Math.random()* (bottomEdge-myDiameter) + myRadius); }   public void draw(Graphics myBuffer) { myBuffer.setColor(myColor); myBuffer.fillOval((int)(myX - myRadius), (int)(myY-myRadius), (int)myDiameter, (int)myDiameter); } }```

Snake Class:
Code :

```import javax.swing.*;   import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.image.BufferedImage;   public class Snake extends JPanel implements ActionListener, KeyListener { Timer t = new Timer(5, this); double x =350, y = 350, velx = 0, vely = 0, x1 = 0, y1 = 0; private static final int FRAME = 700; private Food food; private Snake snake; private BufferedImage myImage; private Graphics myBuffer; private static final Color BACKGROUND = new Color(204, 204, 204);     public Snake() { myImage = new BufferedImage(FRAME, FRAME, BufferedImage.TYPE_INT_RGB); myBuffer = myImage.getGraphics(); myBuffer.setColor(BACKGROUND); myBuffer.fillRect(0, 0, FRAME,FRAME);   x = 350; y = 350;   x1 = Math.random()*FRAME; y1 = Math.random() *FRAME;   food = new Food(x1,y1,15,Color.BLUE); t.start(); addKeyListener(this); setFocusable(true); setFocusTraversalKeysEnabled(false); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.RED); g2.fill(new Rectangle2D.Double(x,y,15,15));   food.draw(g); // Graphics2D g3 = (Graphics2D) g; // g3.setColor(Color.BLUE); // g3.fill(new Rectangle2D.Double(x1,y1,15,15));   } public void actionPerformed(ActionEvent e) { // myBuffer.setColor(BACKGROUND); // myBuffer.fillRect(0,0,FRAME,FRAME);   //food.draw(myBuffer); repaint(); x += velx; y += vely; } private void collide(Snake snake, Food food) { double d = distance(snake.getX(),snake.getY(),food.getX(),food.getY());   if(d <= snake.getWidth()/2 + food.getRadius()) { food.jump(FRAME,FRAME); }   }   //directions public void up() { vely = -1.5; velx = 0; } public void down() { vely = 1.5; velx = 0; } public void left() { velx = -1.5; vely = 0; } public void right() { velx = 1.5; vely = 0; } //movement keys public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); if(code == KeyEvent.VK_LEFT) { if(velx == 1.5) { up(); } else if(velx == -1.5) { down(); } else if(vely == 1.5) { right(); } else if(vely == -1.5) { left(); } else { left(); } } if(code == KeyEvent.VK_RIGHT) { if(velx == 1.5) { down(); } else if(velx == -1.5) { up(); } else if(vely == 1.5) { left(); } else if(vely == -1.5) { right(); } else { right(); } } } public void keyTyped(KeyEvent e){} public void keyReleased(KeyEvent e){}   private double distance(double x1, double y1, double x2, double y2) { return Math.sqrt(Math.pow(x2-x1,2)+Math.pow(y2-y1,2)); }     }```

Main Class:
Code :

```import javax.swing.JFrame;   public class SnakeMain { public static void main(String[] args) { JFrame f = new JFrame("Snake Game"); Snake s = new Snake(); f.add(s); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(700,700); } }```
• September 25th, 2012, 07:54 PM
Norm
Re: Help with the Snake in a Snake Game
When I execute the code I see a red shape and a blue shape at random locations.
The red shapes moves when a keyboard arrow is pressed.

Can you explain what the code is supposed to do?
• September 25th, 2012, 08:10 PM
godlynom
Re: Help with the Snake in a Snake Game
In essence, the game Snake is a game(obviously) where you control a snake(the red square) and you have to gather the food(the blue shape). When the snake runs into the food, it grows a body part and the food jumps to a new location. The goal of the game is to go as long as you can without running into your own tail, which gets longer every time you run into a food. I hope that cleared it up.
• September 25th, 2012, 08:15 PM
Norm
Re: Help with the Snake in a Snake Game
To see what the code is doing, try debugging it by adding some println statements that print out the values of variables that control execution and the location of the shapes. The print out will show you what the computer sees and help you understand why the code is doing what it does.

The red shape responds to two of the keyboard arrow keys.

Pick one of the problems with the code and work on that.
When it's fixed move to the next problem.
• September 25th, 2012, 10:28 PM
godlynom
Re: Help with the Snake in a Snake Game
I was using the debugger and I still cannot locate the problem, I created a SnakeBody class and it now appears along with the food, however I cannot control it. here is the code:
SnakeBody class:
Code :

``` import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener;   import javax.swing.JPanel;   public class SnakeBody implements ActionListener, KeyListener { private double myX; // x and y coordinates of center private double myY; private double myDiameter; private Color myColor; private double myRadius; double x =350, y = 350, velx = 0, vely = 0, x1 = 0, y1 = 0;   // constructors public SnakeBody() //default constructor { myX = 200; myY = 200; myDiameter = 25; myColor = Color.RED; myRadius = myDiameter/2;   } public SnakeBody(double x, double y, double d, Color c) { myX = x; myY = y; myDiameter = d; myColor = c; myRadius = d/2; } // accessor methods public int getX() { return (int) myX; } public int getY() { return (int) myY; } public double getDiameter() { return myDiameter; } public Color getColor() { return myColor; } public double getRadius() { return myRadius; } // modifier methods public void setX(double x) { myX = x; } public void setY(double y) { myY = y; } public void setColor(Color c) { myColor = c; } public void setDiameter(double d) { myDiameter = d; myRadius = d/2; } public void setRadius(double r) { myRadius = r; myDiameter = 2*r; } // instance methods public void draw(Graphics myBuffer) { myBuffer.setColor(myColor); myBuffer.fillOval((int)(myX - myRadius), (int)(myY-myRadius), (int)myDiameter, (int)myDiameter); } public void up() { vely = -1.5; velx = 0; } public void down() { vely = 1.5; velx = 0; } public void left() { velx = -1.5; vely = 0; } public void right() { velx = 1.5; vely = 0; } //movement keys @Override public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); if(code == KeyEvent.VK_LEFT) { if(velx == 1.5) { up(); } else if(velx == -1.5) { down(); } else if(vely == 1.5) { right(); } else if(vely == -1.5) { left(); } else { left(); } } if(code == KeyEvent.VK_RIGHT) { if(velx == 1.5) { down(); } else if(velx == -1.5) { up(); } else if(vely == 1.5) { left(); } else if(vely == -1.5) { right(); } else { right(); } } } @Override public void keyTyped(KeyEvent e){} @Override public void keyReleased(KeyEvent e){} @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub x += velx; y += vely; }```

and here is the snake panel again now with changes:
Code :

```import javax.swing.*;   import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.image.BufferedImage;   public class Snake extends JPanel implements ActionListener, KeyListener { Timer t = new Timer(5, this); double x =350, y = 350, velx = 0, vely = 0, x1 = 0, y1 = 0; private static final int FRAME = 700; private Food food; private SnakeBody snake; private BufferedImage myImage; private Graphics myBuffer; private static final Color BACKGROUND = new Color(204, 204, 204);     public Snake() { myImage = new BufferedImage(FRAME, FRAME, BufferedImage.TYPE_INT_RGB); myBuffer = myImage.getGraphics(); myBuffer.setColor(BACKGROUND); myBuffer.fillRect(0, 0, FRAME,FRAME);   x = 350; y = 350;   x1 = Math.random()*FRAME; y1 = Math.random() *FRAME;   food = new Food(x1,y1,15,Color.BLUE); snake = new SnakeBody(x,y,15,Color.RED); t.start(); addKeyListener(snake); setFocusable(true); setFocusTraversalKeysEnabled(false); } public void paintComponent(Graphics g) { //super.paintComponent(g); //Graphics2D g2 = (Graphics2D) g; //g2.setColor(Color.RED); //g2.fill(new Rectangle2D.Double(x,y,15,15));   food.draw(g); snake.draw(g); collide(snake,food); // Graphics2D g3 = (Graphics2D) g; // g3.setColor(Color.BLUE); // g3.fill(new Rectangle2D.Double(x1,y1,15,15));   } public void actionPerformed(ActionEvent e) { // myBuffer.setColor(BACKGROUND); // myBuffer.fillRect(0,0,FRAME,FRAME);   //food.draw(myBuffer); repaint(); //x += velx; //y += vely; } private void collide(SnakeBody snake, Food food) { double d = distance(snake.getX(),snake.getY(),food.getX(),food.getY());   if(d <= snake.getRadius() + food.getRadius()) { food.jump(FRAME,FRAME); }   }   //directions public void up() { vely = -1.5; velx = 0; } public void down() { vely = 1.5; velx = 0; } public void left() { velx = -1.5; vely = 0; } public void right() { velx = 1.5; vely = 0; } //movement keys public void keyPressed(KeyEvent e) { /*int code = e.getKeyCode(); if(code == KeyEvent.VK_LEFT) { if(velx == 1.5) { up(); } else if(velx == -1.5) { down(); } else if(vely == 1.5) { right(); } else if(vely == -1.5) { left(); } else { left(); } } if(code == KeyEvent.VK_RIGHT) { if(velx == 1.5) { down(); } else if(velx == -1.5) { up(); } else if(vely == 1.5) { left(); } else if(vely == -1.5) { right(); } else { right(); } }*/ } public void keyTyped(KeyEvent e){} public void keyReleased(KeyEvent e){}   private double distance(double x1, double y1, double x2, double y2) { return Math.sqrt(Math.pow(x2-x1,2)+Math.pow(y2-y1,2)); }     }```
• September 26th, 2012, 07:38 AM
Norm
Re: Help with the Snake in a Snake Game
Quote:

I still cannot locate the problem
I think there is more than one problem. Which one are you working on?
• September 26th, 2012, 09:29 AM
Norm
Re: Help with the Snake in a Snake Game
The code you posted is incomplete. It's missing the end of the source.
• September 26th, 2012, 10:14 AM
godlynom
Re: Help with the Snake in a Snake Game
yea, one of the end brackets did not copy over for some reason in the SnakeBody class, and it is not really a problem, I just cannot control the SnakeBody object that is created, like I need to. The keylistener is in the wrong place or I am missing something.
• September 26th, 2012, 10:31 AM
Norm
Re: Help with the Snake in a Snake Game
Where does the code change the location of the snake? How often is the draw() method called?
Do the x & y values for the snake's location ever change?

Why does the code call repaint() so many times when there has not been any changes to the locations of anything? The paintComponent() method only needs to be called when something has changed location.

Quote:

The keylistener is in the wrong place or I am missing something.
See post#4 re debugging
• September 26th, 2012, 10:23 PM
godlynom
Re: Help with the Snake in a Snake Game
I am having trouble with the debugging, it is not helping me. If i want to control the SnakeBody object, should i put the KeyListener in the SnakeBody class, or the Snake class?
• September 26th, 2012, 11:14 PM
jps
Re: Help with the Snake in a Snake Game
Quote:

Originally Posted by godlynom
If i want to control the SnakeBody object, should i put the KeyListener in the SnakeBody class, or the Snake class?

Which class do you control the snake movement from?
• September 27th, 2012, 06:53 AM
Norm
Re: Help with the Snake in a Snake Game
Quote:

I am having trouble with the debugging,
How are you doing the debugging?
I use calls to println statements that print out the values of variables so I can see what the computer sees. If you know what you want the code to do, then when you see what it is doing from the print outs, you should be able to change the code so it will do what you want.

1)Where does the code change the location of the snake? Add printlns there to show when the location has been changed.
2)How often is the draw() method called? Add a println there so you will know
3)Do the x & y values for the snake's location ever change? See 1)

Put println calls in the listeners so you will know if they are called.

There is a lot of unused/dead code in the classes you posted. It should be commented out or removed to keep from confusing.
• September 27th, 2012, 08:34 AM
godlynom
Re: Help with the Snake in a Snake Game
that was a dumb question, the KeyListener should be in the Snake class, still trying to figure out what is not working, it should be working, mep
• September 27th, 2012, 09:07 AM
Norm
Re: Help with the Snake in a Snake Game
Quote:

it should be working
What prints out from the printlns you should be adding?

• September 27th, 2012, 09:20 AM
godlynom
Re: Help with the Snake in a Snake Game
The timer printed out the values of the x and y coordinates, following the timer specified at the top, but it does not change the x or y coordinates

I did :

System.out.println(x + " " + y);

and got an output of:

350.0 350.0

every time
• September 27th, 2012, 09:22 AM
Norm
Re: Help with the Snake in a Snake Game
Quote:

does not change the x or y coordinates
Is that the answer for question 3) or is that just for the code in the timer?
What about the other questions in post #12?
• September 27th, 2012, 09:27 AM
godlynom
Re: Help with the Snake in a Snake Game
well a fix to my response, now the coordinates of x and y change when keys are pressed, (questions 1 and 3) and the draw method is called also, but the shapes themselves are not drawing, it is not recognizing that i designated the x and y to belong to the snake, so after contemplating this, i changed it so that after the x and y are changed, I ALSO change the snake's x and y,and now I get somethign similiar to a tron game, where there is a continuous line after the object moves, but at least the object moves now
• September 27th, 2012, 09:37 AM
Norm
Re: Help with the Snake in a Snake Game
You need to clear the graphics context before doing a new drawing by calling the super method that you have commented out.
Code :

` //super.paintComponent(g);`
• September 27th, 2012, 03:31 PM
godlynom
Re: Help with the Snake in a Snake Game
ugh dang small problems....thank you so much for your time, have now got it working and everything, thanks so much
• September 27th, 2012, 03:45 PM
newbie
Re: Help with the Snake in a Snake Game
Thanks for the update godlynom, could you kindly mark this thread as "Solved" now? (Thread tools > Mark this thread as solved).
• September 27th, 2012, 06:41 PM
godlynom
Re: Help with the Snake in a Snake Game
yea sorry, was at soccer practice