📄 worm.java~5~
字号:
package Worm;import java.util.*;import javax.microedition.lcdui.*;import javax.microedition.midlet.MIDlet;/** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2004</p> * <p>Company: </p> * @author not attributable * @version 1.0 */public class Worm { /* 贪吃蛇可能移动的方向 */ public final static byte DOWN = 2; public final static byte LEFT = 4; public final static byte RIGHT = 6; public final static byte UP = 8;// 贪吃蛇的当前方向 private byte currentDirection;// 保存贪吃蛇每一段的列表 private Vector worm = new Vector(5, 2);// 是否需要更新状态 private boolean needUpdate;// 是否在运动中 private boolean moveOnNextUpdate;// 是否吃到食物 private boolean hasEaten;// 贪吃蛇的初始位置、长度和方向 private final static int INIT_X = 3; private final static int INIT_Y = 8; private final static int INIT_LEN = 8; private final static byte INIT_DIR =RIGHT; public Worm() { } public void setDirection(byte direction){ //这个方法用来改变贪吃蛇运动的方向,只能90度。看下面的实现代码: if ((direction != currentDirection) && !needUpdate) { // 取出列表中的最后一个元素(蛇的头部) WormLink sl = (WormLink)worm.lastElement(); int x = sl.getEndX(); int y = sl.getEndY(); // 不同的运动方向坐标的改变也不一样 switch (direction) { case UP: // 当这段向上运动的时候 if (currentDirection != DOWN) { y--; needUpdate = true; } break; case DOWN: // 当这段向下运动的时候 if (currentDirection != UP) { y++; needUpdate = true; } break; case LEFT: // 当这段向左运动的时候 if (currentDirection != RIGHT) { x--; needUpdate = true; } break; case RIGHT: // 当这段向右运动的时候 if (currentDirection != LEFT) { x++; needUpdate = true; } break; }// 当更改方向后需要更新 if (needUpdate == true) { worm.addElement(new WormLink(x, y, 0, direction)); currentDirection = direction; } } } public void update(Graphics g){ //这个函数是更新贪吃蛇状态。每次更新都把头部增加一节,尾部减少一节。如果它吃到食物尾部段就不减少一节。看起来就像整只蛇长了一节。 // 把贪吃蛇头部增加一格 head = (WormLink)worm.lastElement(); head.increaseLength();// 如果没有吃到食物则尾部减少一格if (!hasEaten) { WormLink tail; tail = (WormLink)worm.firstElement();int tailX = tail.getX();int tailY = tail.getY();// 如果尾部块长度为0就删除tail.decreaseLength();if (tail.getLength() == 0) {worm.removeElement(tail); }// 尾部减少一格g.setColor(WormPit.ERASE_COLOUR);drawLink(g, tailX, tailY, tailX, tailY, 1);} else {// 如果吃到食物就不删除尾部hasEaten = false; }needUpdate = false;// 确认是否在边界中if (!WormPit.isInBounds(head.getEndX(), head.getEndY())) {// 如果不在,就死了throw new WormException("over the edge"); }headX = (byte)head.getEndX();headY = (byte)head.getEndY();//贪吃蛇的头部增加一格g.setColor(WormPit.DRAW_COLOUR);drawLink(g, headX, headY, headX, headY, 1);// 判断是否吃到自己for (int i = 0; i < worm.size()-1; i++) {sl = (WormLink)worm.elementAt(i);if (sl.contains(headX, headY)) {throw new WormException("you ate yourself"); } } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -