/*
* 这个是贪虼蛇的窗体部分
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Map extends JFrame implements KeyListener,Runnable{
//小蛇
Snake snake;
//食物的坐标
int foodx,foody;
//初始窗口的大小
private final int window_width=500;
private final int window_height=400;
//食物的存在性
public boolean food=true;
public static void main(String[] args){
new Map();
}
public Map(){
//小蛇进入到窗体里面
snake=new Snake();
this.addKeyListener(this);
//为进入窗体的小蛇开启一个线程
new Thread(this).start();
this.setVisible(true);
this.setSize(this.window_width, this.window_height);
this.validate();
this.setResizable(false);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
}
public void paint(Graphics g){
//设置背景
g.setColor(Color.black);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.white);
g.drawRect(50, 50, this.getWidth()-100, this.getHeight()-100);
//若食物被吃掉,产生新的食物坐标
if(food){
this.produceFood(this.snake);
}
//美味的食物
g.setColor(Color.orange);
g.fillRect(this.foodx,this.foody,10, 10);
//可爱的小蛇
g.setColor(Color.green);
for(int i=0;i
g.fillRect(this.snake.x[i], this.snake.y[i], 10, 10);
}
//你的得分
g.setColor(Color.white);
g.drawString("得分:"+(this.snake.length-3)*10, 50,40);
}
//产生食物
public void produceFood(Snake s){
//食物的产生位置是否合法
boolean foodNotOK=true;
while(foodNotOK){
//System.out.println("1111111111");
int i;
this.foodx=((int)(Math.random()*(this.getWidth()-110)/10))*10+50;
this.foody=((int)(Math.random()*(this.getHeight()-110)/10))*10+50;
for(i=0;i if(this.foodx==s.x[i]&;&;this.foody==s.y[i]){
break;
}
}
if(i==s.length){
foodNotOK=false;
}
}
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getKeyCode()==KeyEvent.VK_RIGHT&;&;this.snake.direction!=2){
this.snake.direction=1;
this.snake.speed=100;
}else if(arg0.getKeyCode()==KeyEvent.VK_LEFT&;&;this.snake.direction!=1){
this.snake.direction=2;
this.snake.speed=100;
}else if(arg0.getKeyCode()==KeyEvent.VK_DOWN&;&;this.snake.direction!=4){
this.snake.direction=3;
this.snake.speed=100;
}else if(arg0.getKeyCode()==KeyEvent.VK_UP&;&;this.snake.direction!=3){
this.snake.direction=4;
this.snake.speed=100;
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getKeyCode()==KeyEvent.VK_RIGHT||arg0.getKeyCode()==KeyEvent.VK_LEFT||arg0.getKeyCode()==KeyEvent.VK_DOWN||arg0.getKeyCode()==KeyEvent.VK_UP){
this.snake.speed=500;
}
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated meth
od stub
}
@Override
public void run() {
// TODO Auto-generated method stub
while(this.snake.isLive){
try {
Thread.sleep(this.snake.speed);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//安照小蛇的长度设定其速度,最大速度为200
if(this.snake.length>12&;&;this.snake.length<23&;&;this.snake.speed>400){
this.snake.spe