我目前正在Java上制作一个RobotArena游戏,其中一个任务是制作一个数组用于在游戏中存储每个机器人。例如,如果用户想在游戏中使用2个机器人,那么我必须将这2个机器人存储在一个阵列中(x和y坐标),或者如果用户需要更多的机器人而不仅仅是2个。如何制作一个数组来存储连续用户输入的x,y坐标?
我已经为机器人坐标制作了一个2D数组,但它只存储了机器人在阵列中的最新X/Y坐标,并且不存储之前的机器人坐标。
有没有办法做到这一点?将它分配给一个变量或将其放入一个循环?任何答案将不胜感激。
这是我到目前为止的代码,我是Java的新手,所以如果代码不太好,我很遗憾。
public static class RobotArena{
public RobotArena(int x, int y){
int Arena[][] = new int[4][4]; //Sets the 2d array
Arena[x][y] = '1'; //Puts 1 where the X/Y co ordinate is
for (int[] a : Arena) { //this prints out the grid
for (int i : a) {
System.out.print(i + " ");
}
System.out.println("\n");
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many Robots in your world?");
int numRobots = s.nextInt();
Robot[] allRobots = new Robot[numRobots];
Robot.RobotArena[] allRobots2 = new Robot.RobotArena[numRobots];
int rx, ry;
System.out.println("Now enter position of each robot in turn (as x y) >");
for (int ct = 0; ct<numRobots; ct++) {
System.out.println("Enter, x y position for " + ct + "th robot: >");
rx = s.nextInt();
ry = s.nextInt();
allRobots[ct] = new Robot(rx, ry);
allRobots2[ct] = new RobotArena(rx, ry);
allRobots[ct].printIdPosition();
}
}
}
}
这是当我添加2个机器人到游戏的输出:机器人1的
统筹(1,1);
0 0 0 0
0 49 0 0
0 0 0 0
0 0 0 0
当我第二次机器人加入到游戏中,这是输出,与共同ORD(2,2):
0 0 0 0
0 0 0 0
0 0 49 0
0 0 0 0
我想显示在最新一号机器人等级,但我不知道如何去做。
我试图复制所有相关的代码这个问题,但如果你希望所有必要的代码,那么我很乐意将它添加更多:) –
你必须使用数组来代替名单?我的意思是它没有太大的改变,但它会让一些线条更易于阅读。除此之外,RobotArena代表什么?一个机器人? 'int Arena [] [] = new int [4] [4];'一个变量的名字总是以小写字母开头 –
我也没有低估为什么你需要Robot [] allRobots和Robot.RobotArena []? ^^' 如果我是你,我会开始创建一个类来表示舞台,我们称它为Arena。这个类将存储一个数组或一个Robot列表。每个机器人将包含x和y变量。最后重写你的Arena类的toString来使用机器人列表来打印网格来放置标记 –