作者的代码一看就懂,非常好理解.
污渍类,即贪食蛇吞噬的物体
package com.badlogic.androidgames.mrnom; public class Stain { public static final int TYPE_1 = 0; public static final int TYPE_2 = 1; public static final int TYPE_3 = 2; public int x, y; public int type; public Stain(int x, int y, int type) { this.x = x; this.y = y; this.type = type; } }非常简单,有坐标,和类型(暂时不知道这个类型有什么用)
贪食蛇定义了两个类,一个是蛇类,一个是蛇身体元素(构成蛇的最小单位)
先看简单的身体元素类
package com.badlogic.androidgames.mrnom; public class SnakePart { public int x, y; public SnakePart(int x, int y) { this.x = x; this.y = y; } }
蛇类就要复杂的多,有一系列的逻辑判断
package com.badlogic.androidgames.mrnom; import java.util.ArrayList; import java.util.List; public class Snake { //逆时针,按上,左,下,右定义四个方向 public static final int UP = 0; public static final int LEFT = 1; public static final int DOWN = 2; public static final int RIGHT = 3; //用一个集合来保存蛇的身体 public List<SnakePart> parts = new ArrayList<SnakePart>(); public int direction; //初始化贪食蛇对象,移动方向为向上移动,身体长度为三节,同时定义了它们的坐标 public Snake() { direction = UP; parts.add(new SnakePart(5, 6)); parts.add(new SnakePart(5, 7)); parts.add(new SnakePart(5, 8)); } //向左转,实际就是逆时针转动 public void turnLeft() { direction += 1; if(direction > RIGHT) direction = UP; } //向右转,实际就是顺时针转动 public void turnRight() { direction -= 1; if(direction < UP) direction = RIGHT; } //吃掉一个目标,身体长度增加 public void eat() { SnakePart end = parts.get(parts.size()-1); parts.add(new SnakePart(end.x, end.y)); } public void advance() { SnakePart head = parts.get(0); //无论往哪个方向移动,身体的部分一定会移到头部先前的位置,所以要把之前身体部分的坐标赋值给后面的部分 int len = parts.size() - 1; for(int i = len; i > 0; i--) { SnakePart before = parts.get(i-1); SnakePart part = parts.get(i); part.x = before.x; part.y = before.y; } //按方向增减头部坐标 if(direction == UP) head.y -= 1; if(direction == LEFT) head.x -= 1; if(direction == DOWN) head.y += 1; if(direction == RIGHT) head.x += 1; //头部坐标超过屏幕边界就重置坐标 if(head.x < 0) head.x = 9; if(head.x > 9) head.x = 0; if(head.y < 0) head.y = 12; if(head.y > 12) head.y = 0; } //遍历贪食蛇的每个部分,如果是头部碰到自己的身体就判断咬到自己,游戏就要结束 public boolean checkBitten() { int len = parts.size(); SnakePart head = parts.get(0); for(int i = 1; i < len; i++) { SnakePart part = parts.get(i); if(part.x == head.x && part.y == head.y) return true; } return false; } }