Hi I am attempting to develop a Snake game, I am a complete beginner to 2D graphics, and I was wondering how to get my snake ( a rectangle) to move. I have tried Key event but it does not work. What did I do wrong and where can I improve. Thank you for your time.
import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.Timer; import javax.swing.WindowConstants; public class Snake extends JComponent implements ActionListener, KeyListener { public static void main(String[] args) { JFrame window = new JFrame ("Snake Game By Sakon"); Snake game = new Snake(); window.add(game); window.pack(); window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); window.setVisible(true); Timer t= new Timer (100, game); t.start(); } private int snakeX=400; private int snakeY=400; public Dimension getPreferredSize() { return new Dimension (800,600); } public void paint(Graphics g) { //Set Back Round black g.setColor(Color.BLACK); g.fillRect(0, 0, 800, 600); //Draw dot. g.setColor(Color.WHITE); g.fillOval(0, 0, 10, 10); //Draw Snake g.setColor(Color.LIGHT_GRAY); g.fillRect(snakeX, snakeY, 5, 100); } @Override public void keyPressed(KeyEvent e) { switch(e.getKeyCode()){ case KeyEvent.VK_UP:{ if(snakeY>600) snakeY=1; snakeY=snakeY+1; repaint(); } case KeyEvent.VK_DOWN:{ if(snakeY<0) snakeY=600; snakeY=snakeY-1; repaint(); } case KeyEvent.VK_LEFT:{ if(snakeX<0) snakeY=800; snakeY=snakeY-1; repaint(); } case KeyEvent.VK_RIGHT:{ if(snakeX>800) snakeY=1; snakeY=snakeY+1; repaint(); } } } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub }