import java.awt.Color; import java.awt.Font; 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.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class SnakeGame extends JPanel implements KeyListener, ActionListener { public static int WIDTH=800; public static int HEIGHT=600; public static int SIZE=30; private Font titleFont, regularFont; private int x,y; private Timer timer; private Snake snake; public SnakeGame() { snake = new Snake(WIDTH/2, HEIGHT/2, SIZE); titleFont = new Font("Roman", Font.BOLD, 18); regularFont = new Font("Helvetica", Font.PLAIN, 12); y=0; x=200; timer = new Timer(10, this); //1000=1 seconds timer.start(); } public static void main(String[] args) { SnakeGame app= new SnakeGame(); JFrame window = new JFrame("Snake Version 0.1"); window.setSize(WIDTH, HEIGHT); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.getContentPane().add(app); window.addKeyListener(app); //window.pack(); window.setVisible(true); } public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Color.WHITE); g.fillRect(0, 0, getWidth(),getHeight()); g.setColor(Color.BLUE); g.setFont(titleFont); g.drawString("SnakeGame Example", 20, 20); g.setColor(Color.BLACK); g.setFont(regularFont); snake.draw(g); } // These 3 methods need to be declares to implement the KeyListener Interface @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) { int code=e.getKeyCode(); if (code ==39) // right snake.changeDirection(Turn.EAST); else if (code == 37 ) //left snake.changeDirection(Turn.WEST); else if (code == 38 ) //up snake.changeDirection(Turn.NORTH); else if (code == 40 ) //down snake.changeDirection(Turn.SOUTH); repaint(); } @Override public void keyReleased(KeyEvent e) {} @Override public void actionPerformed(ActionEvent e) { if (e.getSource()==timer){ snake.move(); } repaint(); } }