package com.snake;
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 com.global.Global;
import com.listener.SnakeListener;
public class Snake {
private Set<SnakeListener> listeners=new HashSet<SnakeListener>();
private LinkedList<Point> body=new LinkedList<Point>();
public static final int UP=1;
public static final int DOWN=-1;
public static final int LEFT=2;
public static final int RIGHT=-2;
private Point newTail;
private boolean life;
private int oldDirection,newDirection;
public Snake()
{
initSnake();
}
private void initSnake() {
// TODO Auto-generated method stub
int x=Global.WIDTH/2;
int y=Global.HEIGHT/2;
for(int i=0;i<3;i++)
{
body.add(new Point(--x,y));
}
newDirection=oldDirection=RIGHT;
life=true;
}
public void move()
{
System.out.println("move");
if(newDirection+oldDirection!=0)
{
this.oldDirection=newDirection;
}
newTail=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 DOWN:
y++;
if(y>Global.HEIGHT-1)
y=0;
break;
case LEFT:
x--;
if(x<0)
{
x=Global.WIDTH-1;
}
break;
case RIGHT:
x++;
if(x>Global.WIDTH-1)
x=0;
break;
}
body.addFirst(new Point(x,y));
}
public void changeDirection(int direction)
{
newDirection=direction;
System.out.println("changeDirection");
}
public void eatFood()
{
body.addLast(newTail);
System.out.println("eat food!");
}
public boolean isEatBody()
{
System.out.println("eat body");
for(int i=1;i<body.size();i++)
{
if(body.get(i).equals(getHead()))
return true;
}
return false;
}
public Point getHead()
{
return body.getFirst();
}
public void drawMe(Graphics g)
{
g.setColor(Color.BLUE);
for(int i=0;i<body.size();i++)
{
g.fill3DRect(body.get(i).x*Global.CELL_SIZE,body.get(i).y*Global.CELL_SIZE , Global.CELL_SIZE, Global.CELL_SIZE, true);
}
System.out.println("Snake draw me!");
}
public LinkedList<Point> getBody()
{
return body;
}
private class SnakeDriver implements Runnable
{
@Override
public void run() {
// TODO Auto-generated method stub
while(life)
{
move();
for(SnakeListener l:listeners)
{
l.snakeMove(Snake.this);
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void start()
{
new Thread(new SnakeDriver()).start();
}
public void addSnakeListener(SnakeListener l)
{
if(l!=null)
{
this.listeners.add(l);
}
}
public void die() {
// TODO Auto-generated method stub
life=false;
}
}