package com.yl.snake;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane.MoveAction;
import com.sun.glass.ui.Size;
import com.sun.javafx.geom.Rectangle;
public class Snake {
private Node headNode = null;
private Node tailNode = null;
private int size = 0;
private Node node = new Node(20, 20, Dir.L);
private Yard y;
public Snake(Yard y){
this.y = y;
headNode = node;
tailNode = node;
size = 1;
}
public void draw(Graphics g){
if(size <=0)return;
move();
for(Node n=headNode;n!=null;n = n.nextNode){
n.draw(g);
}
}
public void eat(Egg e){
if(this.getRect().intersection(e.getRect()).isEmpty() == false) {
e.reAppear();
this.addToHead();
y.setScore(y.getScore() + 5);
}
}
private Rectangle getRect(){
return new Rectangle(Yard.BLOCK_SIZE*headNode.col,Yard.BLOCK_SIZE*headNode.row,headNode.w,headNode.h);
}
private void move() {
addToHead();
deleteFromTail();
checkDead();
}
private void checkDead() {
if (headNode.row < 2 || headNode.col < 0 ||headNode.row > Yard.ROWS || headNode.col > Yard.COLS) {
y.stop();
}
for(Node node = headNode.nextNode;node != null;node = node.nextNode){
if (headNode.row == node.row && headNode.col == node.col) {
y.stop();
}
}
}
private void deleteFromTail() {
tailNode = tailNode.prevNode;
tailNode.nextNode = null;
}
public void addToTail(){
Node n = null;
switch(tailNode.dir){
case L:
n = new Node(tailNode.row, tailNode.col + 1, tailNode.dir);
break;
case R:
n = new Node(tailNode.row, tailNode.col - 1, tailNode.dir);
break;
case U:
n = new Node(tailNode.row + 1, tailNode.col , tailNode.dir);
break;
case D:
n = new Node(tailNode.row - 1, tailNode.col, tailNode.dir);
break;
}
tailNode.nextNode = n;
n.prevNode = tailNode;
tailNode = n;
size ++;
}
public void addToHead(){
Node n = null;
switch(headNode.dir){
case L:
n = new Node(headNode.row, headNode.col - 1, headNode.dir);
break;
case R:
n = new Node(headNode.row, headNode.col + 1, headNode.dir);
break;
case U:
n = new Node(headNode.row - 1, headNode.col , headNode.dir);
break;
case D:
n = new Node(headNode.row + 1, headNode.col, headNode.dir);
break;
}
n.nextNode = headNode;
headNode.prevNode = n;
headNode = n;
size ++;
}
private class Node{
int w = Yard.BLOCK_SIZE;
int h = Yard.BLOCK_SIZE;
int row ,col;
Dir dir = Dir.L;
Node nextNode = null;
Node prevNode = null;
Node(int row,int col,Dir dir) {
this.row = row;
this.col = col;
this.dir = dir;
}
void draw(Graphics g){
Color c = g.getColor();
g.setColor(Color.BLACK);
g.fillRect(w*col, h*row, w, h);
g.setColor(c);
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
switch(key){
case KeyEvent.VK_LEFT :
if (headNode.dir != Dir.R)
headNode.dir = Dir.L;
break;
case KeyEvent.VK_RIGHT :
if (headNode.dir != Dir.L)
headNode.dir = Dir.R;
break;
case KeyEvent.VK_UP :
if (headNode.dir != Dir.D)
headNode.dir = Dir.U;
break;
case KeyEvent.VK_DOWN :
if (headNode.dir != Dir.U)
headNode.dir = Dir.D;
break;
}
}
}