该类的功能主要有以下几个:
1.跟踪贪食蛇实例,同时生成"污渍"的实例,并保证在游戏世界中只存在一个"污渍"
2.提供一个方法,以时间轴为基准的方式来更新贪食蛇(每0.5秒移动一个单元格的距离)
3.跟踪游戏得分,为吃到"污渍"数量的十倍
4.在每吃掉一个"污渍"以后,增加贪食蛇的移动速度,以增加游戏挑战性
5.跟踪贪食蛇是否存活,用此判断游戏是否应该结束
6.在贪食蛇吃掉一个"污渍"后,再生成一个新的"污渍"
package com.badlogic.androidgames.mrnom;
import java.util.Random;
public class World {
static final int WORLD_WIDTH = 10;
static final int WORLD_HEIGHT = 13;
static final int SCORE_INCREMENT = 10;
static final float TICK_INITIAL = 0.5f;
static final float TICK_DECREMENT = 0.05f;
public Snake snake;
public Stain stain;
public boolean gameOver = false;;
public int score = 0;
//初始游戏的坐标系
boolean fields[][] = new boolean[WORLD_WIDTH][WORLD_HEIGHT];
Random random = new Random();
float tickTime = 0;
float tick = TICK_INITIAL;
//初始化蛇对象,放置污渍
public World() {
snake = new Snake();
placeStain();
}
//放置污渍
private void placeStain() {
//先把每个单元格坐标设为false
for (int x = 0; x < WORLD_WIDTH; x++) {
for (int y = 0; y < WORLD_HEIGHT; y++) {
fields[x][y] = false;
}
}
//得到蛇身长度
int len = snake.parts.size();
//然后把蛇身占据屏幕的坐标位置设成true
for (int i = 0; i < len; i++) {
SnakePart part = snake.parts.get(i);
fields[part.x][part.y] = true;
}
//随机产生目标物坐标
int stainX = random.nextInt(WORLD_WIDTH);
int stainY = random.nextInt(WORLD_HEIGHT);
//如果不是蛇身占据的位置(等于false的时候)
while (true) {
if (fields[stainX][stainY] == false)
break;
stainX += 1;
//x,y坐标如果超过屏幕边界,那么重新置为0后再递增
if (stainX >= WORLD_WIDTH) {
stainX = 0;
stainY += 1;
if (stainY >= WORLD_HEIGHT) {
stainY = 0;
}
}
}
//放置污渍并随机产生一个污渍类型
stain = new Stain(stainX, stainY, random.nextInt(3));
}
public void update(float deltaTime) {
if (gameOver)
return;
tickTime += deltaTime;
while (tickTime > tick) {
tickTime -= tick;
snake.advance();
//如果蛇咬到自身,游戏结束
if (snake.checkBitten()) {
gameOver = true;
return;
}
SnakePart head = snake.parts.get(0);
//如果吃到目标物,判断方式是污渍坐标与蛇头部坐标重合
if (head.x == stain.x && head.y == stain.y) {
//吃到一次目标物,分数累加10分
score += SCORE_INCREMENT;
//eat方法使蛇身加长一节
snake.eat();
//如果蛇身达到最长,占满整个屏幕,游戏结束
if (snake.parts.size() == WORLD_WIDTH * WORLD_HEIGHT) {
gameOver = true;
return;
} else {
placeStain();
}
//每得100分,蛇的移动速度加快0.05秒,TICK_DECREMENT就是那个增量,tick为移动的间隔时间
if (score % 100 == 0 && tick - TICK_DECREMENT > 0) {
tick -= TICK_DECREMENT;
}
}
}
}
}