import java.awt.*; import java.applet.*; public class Snake extends Applet implements Runnable { int x; int y; int length; int highscore=0; int place[][]= new int[1000][2]; int dot[]=new int [2]; boolean restart=false; boolean baddot=true; boolean left=false; boolean right=false; boolean up=false; boolean down=false; boolean started=false; public void init(){ setBackground(Color.white); } public void start(){ Thread t = new Thread(this); t.start(); x=200; y=200; length=20; left = false; right = false; up = false; down = false; started=false; for(int a=0; a<=999; a++){ place[a][0]=-10; place[a][1]=-10; } baddot=true; while(baddot){ baddot=false; dot[0]=((int)(Math.random()*76))*5+10; dot[1]=((int)(Math.random()*76))*5+10; for(int a=0; a<=length;a++){ if(dot[0]==place[a][0] ^ dot[1]==place[a][1]){ baddot=true; } } } } public void paint(Graphics g){ g.setColor(Color.gray); g.fillRect(dot[0],dot[1],5,5); g.setColor(Color.green); if(!started){ g.fillRoundRect(x,y,5,5,2,2); g.drawString("High Score: " + highscore,150,150); } for(int a=0;a<=length;a++){ g.fillRoundRect(place[a][0],place[a][1],5,5,2,2); } } public boolean keyDown(Event e, int key) { if ((key == Event.LEFT) &&(!right)){ left = true; up = false; down = false; if(!started)started=true; } if ((key == Event.RIGHT) && (!left)){ right = true; up = false; down = false; if(!started)started=true; } if ((key == Event.UP) && (!down)){ up = true; right = false; left = false; if(!started)started=true; } if ((key == Event.DOWN) && (!up)){ down = true; right = false; left = false; if(!started)started=true; } return true; } public void run() { while(true){ if(started){ if(left) {x-=5;} if(right) {x+=5;} if(up) {y-=5;} if(down) {y+=5;} for(int a=length;a>=1;a--){ place[a][0]=place[a-1][0]; place[a][1]=place[a-1][1]; } place[0][0]=x; place[0][1]=y; if(x==dot[0] && y==dot[1]){ baddot=true; while(baddot){ baddot=false; dot[0]=((int)(Math.random()*76))*5+10; dot[1]=((int)(Math.random()*76))*5+10; for(int a=0; a<=length;a++){ if(dot[0]==place[a][0] && dot[1]==place[a][1]){ baddot=true; } } } length+=5; } restart=false; for(int a=1;a<=length;a++){ if(place[a][0]==x && place[a][1]==y){restart=true;} } if((x==-5 ^ y==-5) ^ (x==400 ^ y==400)){restart=true;} if(restart){ if(((length-20)/5)>highscore){highscore=(length-20)/5;} for(int a=0; a<=999; a++){ place[a][0]=-10; place[a][1]=-10; } x=200; y=200; length=20; left = false; right = false; up = false; down = false; started=false; } } repaint(); try{Thread.sleep(50);} catch(InterruptedException e){} } } }