机器人竞赛 - 我如何让多个机器人互相竞争
问题描述:
所以我成功地实现了一个机器人竞赛,用户输入的尺寸代表NxN的网格,目标是让机器人到达网格的右上角采取随机数从1到N的步骤,并且足够聪明,可以在面对墙壁时改变方向。机器人竞赛 - 我如何让多个机器人互相竞争
但是现在我必须使用相同的类来实现多机器人比赛(至少2个机器人)。 Robot类有一个名为move()的方法,它接受两个int参数:(steps,gridSize)并移动机器人。我的第一个想法是创建嵌套循环,每转一圈,每个机器人一个,但是遇到麻烦。我会很感激我能得到的任何帮助,谢谢!
本质上,这里是一个输出样本:
移动号码1:
- 机器人1采取2个步骤和在位置X,Y
- 机器人2需要3个步骤和在位置的x,y
移动号码2:
- 机器人1 ....
- 机器人2 ....
等和等等。
这是我的主要:
Random rand = new Random();
int gridSize, nRobo;
Scanner scanner = new Scanner(System.in);
// Reads user input for grid size. Must be at least 2.
do{
System.out.print("What is the size of your grid? (Must be at least 2)");
gridSize = scanner.nextInt();
}while(gridSize < 2);
// Reads user input for number of Robots. Must be at least 1.
do {
System.out.println("\nHow many Robots will race? (Must have at least one robot in the race) ");
nRobo = scanner.nextInt();
}while(nRobo < 1);
// Clears the line from the scanner before advancing(otherwise there is a bug in the loop).
scanner.nextLine();
Robot[] robo = new Robot[nRobo];
// Name of each Robot
for (int i = 0; i < robo.length; i++){
System.out.print("Name of robot " + (i+1) + ": ");
robo[i] = new Robot(scanner.nextLine());
}
编辑:这是我用于1个机器人种族的逻辑(在一个单独的主):
// Number of moves.
int nMoves = 0;
// While robot has not won, enter loop.
while (!robo.won(gridSize)){
//Steps is a random number between 1 and grid size.
int steps = rand.nextInt(gridSize) + 1;
System.out.println(" ==> Number of steps to take " + steps + ".");
robo.move(steps,gridSize);
System.out.println("\tResult: " + robo.toString());
nMoves++;
}
System.out.println("\n" + robo.getName() + " reached its final destination in " +nMoves + " moves.");
答
使用一个循环的同时内循环为robo
阵列。
for (Robot r : robo) {
int steps = rand.nextInt(gridSize) + 1;
System.out.println(r.getName() + " takes " + steps + " steps.");
r.move(steps,gridSize);
System.out.println("\tResult: " + r.toString());
}
nMoves++;
我得到一个越界异常 –