package org.han.snake.entities;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import org.han.snake.SnakeListener.SnakeListener;
import org.han.snake.util.Global;
public class Snake {
public static final int UP = -1;
public static final int RIGHT = 2;
public static final int DOWN = 1;
public static final int LEFT = -2;
private int oldDirection,newDirection;
private Set<SnakeListener> listeners = new HashSet<SnakeListener>();//保存事件监听
private LinkedList<Point> body = new LinkedList<Point>();
private Point oldTail;
private boolean life;
public Snake() {
init();
}
public void init(){
int x = Global.WIDTH/2;
int y = Global.HEIGHT/2;
for(int i=0;i<5;i++){
body.addLast(new Point(x--,y));
}
oldDirection = newDirection = RIGHT;
life = true;
}
public void move(){
//System.out.println("Snake is moving...");
if(oldDirection + newDirection != 0){
oldDirection = newDirection;
}
//1.去尾
oldTail = body.removeLast();
int x = body.getFirst().x;
int y = body.getFirst().y;
switch(oldDirection){
case UP:
y--;
if(y<0){
y = Global.HEIGHT-1;
}
break;
case RIGHT:
x++;
if(x>Global.WIDTH){
x = 0;
}
break;
case DOWN:
y++;
if(y>Global.HEIGHT){
y = 0;
}
break;
case LEFT:
x--;
if(x<0){
x = Global.WIDTH-1;
}
break;
}
//2.加头
Point newHead = new Point(x,y);
body.addFirst(newHead);
}
public void eatFood(){
//System.out.println("Snake eat food.");
body.addLast(oldTail);
}
public boolean isEatBody(){
for(int i=1;i<body.size();i++){
//if(body.get(i).equals(this.getHead()))
if(body.get(i).x == body.getFirst().x && body.get(i).y == body.getFirst().y)
return true;
}
return false;
}
public void changeDirection(int direction){
//System.out.println("snake is changeDirection");
newDirection = direction;
}
public void drawMe(Graphics g){
if(Global.SCORE<180){
g.setColor(Color.LIGHT_GRAY);
}else if(Global.SCORE>=180&&Global.SCORE<360){
g.setColor(Color.PINK);
}else if(Global.SCORE>=360&&Global.SCORE<540){
g.setColor(Color.WHITE);
}else if(Global.SCORE>=540&&Global.SCORE<720){
g.setColor(Color.ORANGE);
}else if(Global.SCORE>=720){
g.setColor(Color.BLACK);
}
for(Point p : body){
g.fill3DRect(p.x*Global.CELL_SIZE, p.y*Global.CELL_SIZE,
Global.CELL_SIZE, Global.CELL_SIZE, true);
}
}
private class SnakeThread implements Runnable{
public void run() {
while(life){
move();
for(SnakeListener l : listeners){//遍历事件源
l.SnakeMoved(Snake.this);
}
try {
Thread.sleep(150-body.size()*2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void start(){
new Thread(new SnakeThread()).start();
}
public void addSnakeListener(SnakeListener l){//添加事件源
if(l!=null){
listeners.add(l);
}
}
public Point getHead() {
return body.getFirst();
}
public void die() {
life = false;
}
public LinkedList<Point> getBody() {
return body;
}
}