我想知道在这种情况下如何使用ArrayList / Array:
让我们说我想做一个pacman游戏,我希望有250个鬼。我如何存储他们的位置而不是自己编写它们(int ghost1x,int ghost1Y,int ghost2x,int ghost2y等)?
另外请给我一些例子! :)
我正在使用java
答案 0 :(得分:3)
使ghost类保持x和y位置,然后使ArrayList保持gost类的对象并将所有ghost存储在其中。
然后通过foreach或类似的东西循环通过每个游戏更新的鬼魂ArrayList,并执行位置更新。
我认为这是一个相当正常的解决方案
private class Ghost{
public Ghost(int x, int y);//ctor
int x, y;
//other ghost code
}
private ArrayList<Ghost> ghosts = new ArrayList<Ghost>();
for(int i = 0; i < 250; i++)
{
ghosts.add(new Ghost(startX, startY));
}
//in the gameloop:
foreach(Ghost ghost in ghosts)
{
ghost.updatePositionOrSomething();
ghost.drawOrSomething();
}
这可能是代码的一些想法,我一段时间没写过java,所以语法上没有100%稳定。
答案 1 :(得分:2)
我不是游戏开发人员,但我想到的是创建一个Ghost对象,它包含两个int变量来表示它的x / y坐标。
然后创建一个Ghost数组,并在游戏中根据需要进行更新。
这有帮助吗?
//Create Ghost array
private Ghost[] ghosts = new Ghost[250]
//Fill ghost array
for (int i = 0; i < 250; i ++)
{
Ghost g = new Ghost();
g.xCoor = 0;
g.yCoor = 0;
ghosts[i] = g;
}
//Update coordinates while program running
while(programRunning == true)
{
for (int i = 0; i < 250; i ++)
{
ghosts[i].xCoor = newXCoor;
ghosts[i].yCoor = newYCoor;
}
}
//Make Ghost class
public class Ghost
{
public int xCoor {get; set;}
public int yCoor {get; set;}
}
答案 2 :(得分:0)
我建议你深入研究面向对象的设计。
你应该创建一个Ghost类:
public class Ghost {
int x;
int y;
public void update() {
}
public void render() {
}
}
现在你可以创建一个Ghost对象数组(如果Ghost对象的数量不同,你应该只创建一个List&lt;&gt;)。
Ghost[] ghosts = new Ghost[250];
现在初始化Ghosts数组:
for(int i = 0; i < ghosts.length(); i++) {
ghosts[i] = new Ghost();
}
我会告诉您如何初始化x
和y
坐标。
我希望这会有所帮助。