gpt4 book ai didi

Java:为什么这个列表落后于我的游戏 “Out of Memory”

转载 作者:行者123 更新时间:2023-12-01 07:57:25 24 4
gpt4 key购买 nike

你好,我正在尝试在玩家后面添加一条尾部,就像贪吃蛇游戏一样。但由于某种原因,这使我的游戏持续滞后并耗尽内存。为什么会发生这种情况以及如何解决这个问题?

我像这样创建列表:

List<Snake> snake = new CopyOnWriteArrayList<Snake>();

这是我创建新对象并在 forloop 中删除它们的地方:

public void snake() {
snake.add(new Snake(ball.getX(), ball.getY()));
currentTime++;
for(Snake currentSnake: snake) {
if(currentSnake.creationDate < SnakeLength){
currentSnake.Update();
} else {
Gdx.app.log("SnakeLength" + SnakeLength, "CreationDate" + currentSnake.creationDate);
snake.remove(currentSnake);
}
}
}

这就是我的蛇类的样子:

public class Snake
{
float width = Gdx.graphics.getWidth();
float height = Gdx.graphics.getHeight();
float screenwidth = width/270;
float screenheight = height/480;

public float x;
public float y;
public int creationDate;
ShapeRenderer shapeRenderer;
SpriteBatch batch;

public boolean active = false;

public Snake(float x, float y) {
shapeRenderer = new ShapeRenderer();
batch = new SpriteBatch();
this.x = x;
this.y = y;
}

public void Update() {
batch.begin();
shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(new Color(1, 1, 1, 0.2f));
shapeRenderer.circle(x + 8*screenwidth, y + 8*screenheight, 6*screenheight);
shapeRenderer.end();
batch.end();
creationDate++;
}
}

最佳答案

如javadoc所述CopyOnWriteArrayList :

A thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.

因此,这是一个成本高昂的操作,并且该类专为并发读取而设计,修改率较小。看起来这不是你的情况。

如果您选择此类来解决在修改列表时读取列表的问题,请考虑将迭代器与专为该用途而设计的 ArrayList 一起使用:

synchronized(snake) { // Protect the snake list against concurrent access. Do it whenever you access the snake list
for(Iterator<Snake> it = snake.iterator();; it.hasNext()) {
Snake currentSnake = it.next();
if(currentSnake.creationDate < SnakeLength) {
currentSnake.Update();
} else {
Gdx.app.log("SnakeLength" + SnakeLength, "CreationDate" + currentSnake.creationDate);
it.remove();
}
}
}

请注意,ArrayList 没有针对并发访问的保护。如果多个线程能够读取和写入您的列表,您必须使用同步块(synchronized block)来保护它。

但是阅读你的代码,我想带有 PriorityQueue 的设计似乎更合适。

关于Java:为什么这个列表落后于我的游戏 “Out of Memory”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28232914/

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