2017-04-16 45 views
0

所以我成功地實現了一個機器人競賽,用戶輸入的尺寸代表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."); 

回答

0

使用一個循環的同時內循環爲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++; 
+0

我得到一個越界異常 –