import java.awt.*; import java.awt.event.*; import java.util.Random; public class Snake extends Frame implements Runnable,WindowListener,KeyListener { private static final long serialVersionUID = -3029394778317566533L; public static final int FPS = 30; public static final int GAMEAREAWIDTH = 20; public static final int GAMEAREAHEIGHT = 20; public static final int GAMEAREABGCOLOR = 0xFFFFFF; public static final int GAMEAREABORDERCOLOR = 0xFFFFFF; public static final int BLOCKSIZE = 16; public static final int NUMOFFOODS = 80; public static final int STATE_NORMAL = 0; public static final int STATE_STOPPED = 1; public static boolean cont; public static Snake inst; public boolean inProgress; public int score; public static final Random randGen = new Random(System.currentTimeMillis()); Thread drawThread; Graphics bbGraphics; Image bbImage; long lastUpdate; long lastMove; Boolean[] keys; int state; Follower snake; Food[] foods; Point direction; public static void main(String[] args) { cont = true; while(cont) { inst = new Snake(); while(inst.inProgress) { try { Thread.sleep(1000); } catch(Exception e) {} } } System.exit(0); } public Snake() { inProgress = true; // SET UP WINDOW this.setTitle("Snake : 1"); this.setResizable(false); this.setBackground(Color.white); this.setForeground(Color.black); this.addWindowListener(this); this.addKeyListener(this); this.setVisible(true); this.setSize(getInsets().left+getInsets().right+GAMEAREAWIDTH*BLOCKSIZE, getInsets().top+getInsets().bottom+GAMEAREAHEIGHT*BLOCKSIZE); Dimension dim = getToolkit().getScreenSize(); Rectangle abounds = getBounds(); this.setLocation((dim.width - abounds.width) / 2, (dim.height - abounds.height) / 2); // SET UP KEYS keys = new Boolean[256]; synchronized(keys) { for(int i=0;ilastMove+150) { snake.moveBy(direction.x, direction.y); if(snake.collidesWithSelf()) gameOver(); else { for(int i=0;iGAMEAREAWIDTH-1||y>GAMEAREAHEIGHT-1) gameOver(); } public void moveBy(int x, int y) { this.moveTo(pos.x+x,pos.y+y); } public void eat() { if(next==null) { next = new Follower(pos.x,pos.y); incrementScore(); } else { next.eat(); } } public boolean collidesWithSelf() { return (next==null)? false : next.intersects(pos.x,pos.y); } public boolean intersects(int x, int y) { if(pos.x==x && pos.y==y) return true; else return (next==null)?false:next.intersects(x, y); } } protected class Food { Point pos; public Food(int x, int y) { pos = new Point(x,y); } public boolean intersects(Follower f) { return f.intersects(pos.x,pos.y); } public void shuffle(Follower f) { this.shuffle(new Follower[]{f}); } public void shuffle(Follower[] fs) { if(fs.length<1) return; LABEL1: while(true) { pos.x = randGen.nextInt(GAMEAREAWIDTH); pos.y = randGen.nextInt(GAMEAREAHEIGHT); for(int i=0;i