我正在制作蛇游戏,但我对如何在Processing中实现Snake的运动感到困惑。我已经为蛇创建了一个类,其中包括一个可以检测按键的移动功能,但我仍然坚持如何实际编码蛇的运动。任何人都可以根据下面的代码给我一个关于如何实现Snake运动的简要说明吗?
int score = 0;
int unit = 20;
PFont courierNew24, courierNew40;
ArrayList unitList;
String direction = "right";
String nextDirection = "";
int directionCount = 0;
class Snake
{
Snake() {
unitList = new ArrayList();
unitList.add(new Unit(4, 3));
unitList.add(new Unit(4, 4));
unitList.add(new Unit(4, 5));
unitList.add(new Unit(4, 6));
unitList.add(new Unit(4, 7));
unitList.add(new Unit(4, 8));
}
void drawSnake()
{
for (int i = 0; i < unitList.size (); i++)
{
Unit snakePiece = (Unit) unitList.get(i);
snakePiece.drawSnakePiece();
}
}
void moveSnake()
{
if (direction != "left" && nextDirection == "right")
{
//Move Snake
}
if (direction != "right" && nextDirection == "left")
{
}
if (direction != "up" && nextDirection == "down")
{
}
if (direction != "down" && nextDirection == "up")
{
}
}
}
class Unit
{
int row, column;
Unit (int unitRow, int unitColumn)
{
row = unitRow;
column = unitColumn;
}
void drawSnakePiece()
{
fill(0, 255, 0);
rect(column*unit, row*unit, unit, unit);
}
void drawApple()
{
fill(255, 0, 0);
ellipse(column*unit+(unit/2), row*unit+(unit/2), unit, unit);
}
void collision(int unitRow, int unitColumn)
{
if (row == unitRow && column == unitColumn)
{
}
}
}
//Functions
void scoreBoard()
{
fill(255);
textFont(courierNew24, 24);
text("Score: " + score, 20, 670);
}
void gameOver()
{
fill(255);
textFont(courierNew40, 40);
textAlign(CENTER, CENTER);
text("Game Over, Score of " + score, 500, 350);
}
void setup()
{
size(1000, 700);
background(0);
courierNew24 = loadFont("CourierNewPSMT-24.vlw");
courierNew40 = loadFont("CourierNewPSMT-40.vlw");
scoreBoard();
}
void draw()
{
smooth();
Snake snake = new Snake();
snake.drawSnake();
snake.moveSnake();
Unit apple = new Unit(10, 10);
apple.drawApple();
}
void keyPressed()
{
switch(key)
{
case 'a':
case 'A':
directionCount += 1;
if (directionCount > 1)
{
direction = nextDirection;
}
nextDirection = "left";
break;
case 'd':
case 'D':
directionCount += 1;
if (directionCount > 1)
{
direction = nextDirection;
}
nextDirection = "right";
break;
case 'w':
case 'W':
directionCount += 1;
if (directionCount > 1)
{
direction = nextDirection;
}
nextDirection = "up";
break;
case 's':
case 'S':
directionCount += 1;
if (directionCount > 1)
{
direction = nextDirection;
}
nextDirection = "down";
break;
}
}
答案 0 :(得分:3)
简要说明:
那将安排运动。如果您在头部位置找到一个苹果,请初始化增长计数器。在每个刻度线上,如果growth_counter> 0,减少它并跳过尾部单元移除。因此,只有头部会移动直到它长大。