Beginning of snake game
I'm having trouble getting my snake to be drawn correctly according to keyboard events. The keyboard events fire and my program picks up on the events but the snake is not drawn correctly or really at all for that case. The keys to control the snake are the four arrow keys. My problem lies in using the Graphics object-- i'm not exactly sure what to do with it.
Thanks for the help!!
//SnakePane.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class SnakePanel extends JPanel implements KeyListener{
Snake snake;
Graphics g;
public SnakePanel(){
super();
this.setBackground(Color.yellow);
snake = new Snake(Color.black);
addKeyListener(this);
//give SnakePanel class keyboard focus
this.setFocusable(true);
}
//KeyListener interface methods
public void keyPressed(KeyEvent e){
System.out.println("keyPressed");
update(g, e);
}
public void keyReleased(KeyEvent e){
System.out.println("keyReleased");
}
public void keyTyped(KeyEvent e){
System.out.println("keyTyped");
}
public void paintComponent(Graphics graphics){
System.out.println("paint");
g = graphics;
//display snake for the first time
snake.drawSnake(g);
}
//overload update() method
public void update(Graphics g, KeyEvent e){
int keyCode = e.getKeyCode();
//get arrow key
switch(keyCode){
case KeyEvent.VK_UP:
//System.out.println("moveUp");
snake.moveUp(g);
break;
case KeyEvent.VK_DOWN:
snake.moveDown(g);
break;
case KeyEvent.VK_RIGHT:
snake.moveRight(g);
break;
case KeyEvent.VK_LEFT:
snake.moveLeft(g);
break;
}
}
public static void main(String[] args){
JFrame frame = new JFrame("Snake");
frame.getContentPane().add(new SnakePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
frame.setLocation(100,100);
frame.setVisible(true);
}
}
*****************************
And below is the Snake.java class**
*****************************
import java.awt.*;
public class Snake{
int xPos, yPos;
int size = 10;
Color color;
public Snake(Color col){
xPos = 50;
yPos = 50;
color = col;
}
public void drawSnake(Graphics g){
g.setColor(Color.black);
g.fillRect(xPos,yPos,size,size);
}
public void moveUp(Graphics g){
g.setColor(Color.red);
//decrement yPos
yPos = yPos - size;
g.fillRect(xPos, yPos, size, size);
}
public void moveRight(Graphics g){
g.setColor(Color.red);
xPos = xPos + size;
g.fillRect(xPos, yPos, size, size);
}
public void moveLeft(Graphics g){
g.setColor(Color.red);
xPos = xPos - size;
g.fillRect(xPos, yPos, size, size);
}
public void moveDown(Graphics g){
g.setColor(Color.red);
yPos = yPos + size;
g.fillRect(xPos, yPos, size, size);
}
}

