所以我成功地实现了一个机器人比赛,其中用户输入表示NxN网格的大小,目标是机器人到达网格的右上角,采取从1到N的随机步数,足够聪明,可以在面对墙壁时改变方向。
但是我现在必须使用相同的类来实现多个机器人比赛(至少2个机器人)。 Robot类有一个名为move()的方法,它接受两个int参数:(steps,gridSize)并移动机器人。我的第一个想法是创建嵌套循环,每个回合一个,每个机器人一个,但我遇到了麻烦。我很感激能得到的任何帮助,谢谢!
基本上,这是一个示例输出:
移动数字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.");
答案 0 :(得分:0)
在robo
数组的while循环中使用循环。
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++;