gpt4 book ai didi

java - 如何在贪吃蛇游戏中,在没有被蛇或障碍物占据的 field 上生成食物?

转载 作者:太空宇宙 更新时间:2023-11-04 09:34:45 24 4
gpt4 key购买 nike

如何扩展 SnakeGame 中的 spawnFood() 方法,以在未被 Snake 或 Barrier 占据的字段上创建新的 Food 对象。

private void spawnFood() {
int x = (int) (Math.random() * numRows + 1);
int y = (int) (Math.random() * numColumns +1);

food = new Food(x , y);
}

最佳答案

你想要的是计算一个随机的自由字段,而不是计算任何随机字段然后检查它是否是自由的。你可以这样做,但最终当字段被填满时,它会表现得很糟糕。虽然您的代码很便宜,因此这不会是一个严重的问题,但它并不理想,最好的方法(您可能无论如何都需要计算胜利条件)是计算空闲字段,然后找到第一个空闲字段:

public Food spawnFood() {
int width = numColumns - 2; // assuming borders on both ends.
int height = numRows - 2; // assuming borders on both ends.
int numFields = width * height;
int freeSpaces = numField - getSnakeLength(); // I assume this method, because I don't know how your code works in regards to the Snake object.

int freeFieldIndex = (int) Math.round(Math.random() * freeSpaces);
for (int row = 0; freeFieldIndex >= 0; ++row) {
int snakeFieldsInRow = getNumSnakeFieldsInRow(row); // The number of fields the snake takes up in that row.
int unoccupiedInRow = width - snakeFieldsInRow;
if (freeFieldIndex < unoccupiedInRow ) {
int column = 0;
while(; freeFieldIndex > 0; ++column) {
if (!isSnakeField(row, column + 1)) { // This method must decide, whether a field is occupied by the snake.
--freeFieldIndex;
}
}

return new Food(row, column);
}
freeFieldIndex -= unoccupiedInRow;
}
return null;
}

我没有运行这个,因为我缺少其余的代码,所以它可能需要一些调整。

我知道我假设了很多方法,但由于我们了解得不够,所以我不得不假设很多。希望这会有所帮助。

关于java - 如何在贪吃蛇游戏中,在没有被蛇或障碍物占据的 field 上生成食物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56642561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com