import java.util.Vector;
import javax.microedition.lcdui.Graphics;
/**
*
* @author Jagie
* 贪吃蛇
*/
public class Snake
{
//蛇环节,每个环节为一个int[] sec
//sec[0]:环节起点x,sec[1]:
环节起点y,sec[2]:环节方向,sec[3]:
环节长度
Vector sections = new Vector();
/**
* 初始化sections
* 开始的时候,整条蛇只有一段。
*
*/
public void init()
{
int[] head =
{ 10, 10, 2, 50 };
sections.addElement(head);
}
/**
* 绘制
* @param g
*/
public synchronized
void paint(Graphics g)
{
if (sections.isEmpty())
{
return;
}
g.setColor(0, 255, 0);
for (int i = 0; i < sections.size();
i++)
{
int[] sec = (int[])
sections.elementAt(i);
//sec[0]:起点x,sec[1]:
起点y,sec[2]:方向,sec[3]:
长度
switch (sec[2]) {
case 1:
g.drawLine(sec[0], sec[1],
sec[0], sec[1] - sec[3]);
break;
case 2:
g.drawLine(sec[0], sec[1],
sec[0] + sec[3], sec[1]);
break;
case 3:
g.drawLine(sec[0], sec[1],
sec[0], sec[1] + sec[3]);
break;
case 4:
g.drawLine(sec[0], sec[1],
sec[0] - sec[3], sec[1]);
break;
}
}
}
/**
*
* @author Jagie
*
* 蛇的爬行。本质上是蛇头长度++,蛇尾长度--。
同时移动蛇尾起点。如果蛇尾长度小于0,则去掉蛇尾。
*/
public synchronized void move()
{
if (sections.isEmpty())
{
return;
}
//蛇尾
int[] tail = (int[])
sections.elementAt
(sections.size() - 1);
//蛇头
int[] head = (int[])
sections.elementAt(0);
//根据蛇尾环节的方向移动蛇尾。
switch (tail[2])
{
case 1:
tail[1]--;
break;
case 2:
tail[0]++;
break;
case 3:
tail[1]++;
break;
case 4:
tail[0]--;
break;
}
//蛇尾缩短
tail[3]--;
//蛇头增长
head[3]++;
//蛇尾<0,则去掉蛇尾
if (tail[3] <= 0)
{
sections.removeElement(tail);
}
}
/**
* 蛇分段
* @param dir 新蛇头的方向
*/
public synchronized void
breakInto(int dir)
{
if (sections.isEmpty())
{
return;
}
int[] head = (int[])
sections.elementAt(0);
//新蛇头方向和旧蛇头方向一致,
则无反应。
//TODO 可以考虑加速。
if (dir == head[2])
{
return;
}
//增加新蛇头
int[] newhead=new int[4];
//新蛇头的起始位置,
与旧蛇头的运动方向有关。
switch (head[2])
{
case 1:
newhead[0]=head[0];
newhead[1]=head[1]-head[3];
newhead[2]=dir;
newhead[3]=0;
//蛇头总是第一个元素
sections.insertElementAt(newhead, 0);
break;
case 2:
newhead[0]=head[0]+head[3];
newhead[1]=head[1];
newhead[2]=dir;
newhead[3]=0;
sections.insertElementAt(newhead, 0);
break;
case 3:
newhead[0]=head[0];
newhead[1]=head[1]+head[3];
newhead[2]=dir;
newhead[3]=0;
sections.insertElementAt(newhead, 0);
break;
case 4:
newhead[0]=head[0]-head[3];
newhead[1]=head[1];
newhead[2]=dir;
newhead[3]=0;
sections.insertElementAt(newhead, 0);
break;
}
}
} |