package project;
import java.awt.BorderLayout;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Random;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class Model extends Observable implements Runnable{
public static final int left=1;
public static final int up=2;
public static final int right=3;
public static final int down=4;
public boolean coordinate[][];//用这个来当做界面的坐标
public LinkedList<Node> node=new LinkedList(); //构建一个节点的链表
public int direction=2; //(方向)设置默认的方向为开局向上
boolean running=false;
public int maxX,maxY;
Node food;
public int sleeptime=200;
public Model(int maxX,int maxY){//起始蛇身初点位置(即蛇头的位置)
this.maxX=maxX;//80
this.maxY=maxY;//50
reset();
}
public void reset() {
direction=this.up; //设置按回车重启后(即游戏开始)默认的方向为开局向上
sleeptime=200;
coordinate=new boolean[maxX][];
for (int i = 0; i < maxX; i++) {
coordinate[i]=new boolean[maxY];
Arrays.fill(coordinate[i], false);// 将指定的 boolean 值分配给指定 boolean 型数组指定范围中的每个元素。
}
//initialize the Snake'body
int initlenght=10;
node.clear();
for (int j = 0; j < initlenght; j++) { //设置蛇身
int x=maxX/2+j;
int y=maxY/2;
node.addLast(new Node(x,y)); //将指定节点添加到此列表的结尾。
coordinate[x][y]=true;//将节点变为可显状态(即蛇身的组成部分)
}
food=createFood();//产生食物
coordinate[food.x][food.y]=true;//将食物设置为可显状态
}
public boolean move(){//判断蛇存活以及吃到食物后更新新的食物
Node n=(Node)node.getFirst(); //吃到的新点加入到蛇身
int x=n.x;
int y=n.y;
switch (direction) {
case up:
y--;
break;
case down:
y++;
break;
case left:
x--;
break;
case right:
x++;
break;
default:
break;
}
if ((x>=0&&x<maxX)&&(y>=0&&y<maxY)) {
if (coordinate[x][y]) {
if (x==food.x&&y==food.y) {
node.addFirst(food);
if (sleeptime>35) {//设置蛇的移动速度
sleeptime-=20;
}
food=createFood();//产生一个新的食物
coordinate[food.x][food.y]=true;//将新的食物加入到临界坐标中
return true;
}else {
return false;
}
}else {
node.addFirst(new Node(x,y));
coordinate[x][y]=true;
n=(Node)node.getLast();
node.removeLast();
coordinate[n.x][n.y]=false;
return true;
}
}
return false;
}
public void changeDirection(int newdir){//收集键盘的按键,发生改变时进行监听
if (direction!=newdir) {
direction=newdir;
}
}
public Node createFood() {
int x=0,y=0;
do {
Random r = new Random();
x = r.nextInt(maxX);
y = r.nextInt(maxY);
} while (coordinate[x][y]);//这是为了控制不会在蛇身上产生新出现的点
View.scoreshe++;
return new Node(x, y);
}
public void run() {
running=true;
while(running){
try {
Thread.sleep(sleeptime);//设置睡眠事件。200ms刷新一次
} catch (Exception e) {
break;
}
if (move()) {
setChanged();// 标记此 Observable 对象为已改变的对象;现在 hasChanged 方法将返回 true。
notifyObservers();//如果 hasChanged 方法指示对象已改变,则通知其所有观察者,
//并调用 clearChanged 方法来指示此对象不再改变
}else {
JOptionPane.showMessageDialog(null, "Game Over"+" 您的分数"+View.scoreshe);
break;
}
}
}
}
class Node{//创建蛇身
public int x,y;
public Node(int x,int y){
this.x=x;
this.y=y;
}
}
评论0
最新资源