Java 制作游戏时使用ArrayList
我想知道在这种情况下如何使用ArrayList/Array: 假设我想做一个吃豆人游戏,我想有250个鬼魂。我如何存储它们的位置而不是自己编写它们(int-ghost1x、int-ghost1Y、int-ghost2x、int-ghost2y等) 也请给我看一些例子! :)Java 制作游戏时使用ArrayList,java,arrays,arraylist,Java,Arrays,Arraylist,我想知道在这种情况下如何使用ArrayList/Array: 假设我想做一个吃豆人游戏,我想有250个鬼魂。我如何存储它们的位置而不是自己编写它们(int-ghost1x、int-ghost1Y、int-ghost2x、int-ghost2y等) 也请给我看一些例子! :) 我使用java,我不是游戏开发者,但我想到的是创建一个Ghost对象,它包含两个int变量来表示它的x/y坐标 然后创建一组鬼魂,并在游戏中根据需要进行更新 这有用吗 //Create Ghost array private
我使用java,我不是游戏开发者,但我想到的是创建一个Ghost对象,它包含两个int变量来表示它的x/y坐标 然后创建一组鬼魂,并在游戏中根据需要进行更新 这有用吗
//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;}
}
//创建重影数组
私人鬼[]鬼=新鬼[250]
//填充重影阵列
对于(int i=0;i<250;i++)
{
Ghost g=新的Ghost();
g、 xCoor=0;
g、 yCoor=0;
鬼[i]=g;
}
//程序运行时更新坐标
while(programRunning==true)
{
对于(int i=0;i<250;i++)
{
鬼魂[i].xCoor=newXCoor;
鬼魂[i].yCoor=newYCoor;
}
}
//上鬼课
公共级幽灵
{
公共int xCoor{get;set;}
公共int yCoor{get;set;}
}
使重影类保持x和y位置,然后使ArrayList保持gost类的对象并在其中存储所有重影
然后用foreach或类似的东西在每个游戏更新的幽灵数组列表中循环,并执行位置更新
我相信这是一个相当正常的解决方案
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();
}
私有类重影{
公共重影(int x,int y);//向量
int x,y;
//其他重影代码
}
私有ArrayList重影=新建ArrayList();
对于(int i=0;i<250;i++)
{
添加(新重影(startX,startY));
}
//在游戏循环中:
foreach(鬼魂中的鬼魂)
{
ghost.updatePositionOrSomething();
鬼魂。drawOrSomething();
}
这可能是代码的一些想法,我已经有一段时间没有编写java了,所以语法不是100%稳定。我建议您深入研究面向对象的设计 您应该创建一个重影类:
public class Ghost {
int x;
int y;
public void update() {
}
public void render() {
}
}
现在,您可以创建一个重影对象数组(仅当重影对象的数量不同时,才应创建一个列表)
现在初始化重影数组:
for(int i = 0; i < ghosts.length(); i++) {
ghosts[i] = new Ghost();
}
for(int i=0;i
如何初始化x
和y
坐标由您决定
我希望这能有所帮助。Java,很抱歉没有具体说明这个问题太广泛了,就像问“我如何编程?”。你应该去尝试一些东西(也许读一本介绍性的书),然后当你对你所写的一段代码有一个特定的问题时,如果它不能按你所期望的方式工作,你应该回来。然后,你得到的答案会有用得多。同样,这个问题对你也没什么用处。答案几乎完全取决于这样一个事实,即您已确定
ArrayList
是编写此代码的正确方法,而实际上,在您知道这是正确的决策之前,您仍有许多体系结构问题要问。这就像盖房子,从粉刷石膏板开始。我知道,但我该怎么做,这是我的工作question@user1658294这是基本的面向对象编程,你应该读一本书,而不仅仅是几个链接。我为你添加了一些示例代码,如果你有任何疑问,.net语法,请告诉我。它们只是公共int变量。有趣的是。。。我会去试试的
for(int i = 0; i < ghosts.length(); i++) {
ghosts[i] = new Ghost();
}