Random position in string array? Java -


working on building tic tac toe game. i'm trying use simple of methods possible. i'm working on getting cpu randomly choose spot in array place "o" at. how go doing this? have far.

import java.util.scanner; import java.util.random; public class player  {     string player = "x";     string cpu = "o";     //private int[][] theboard= new int [3][3] ;      private string[][] theboard=  {{" "," "," "}, {" "," "," "}, {" ", " "," "}};;     random cpuinput = new random();       private board board1;     public static scanner scan = new scanner(system.in);  public player(board board, string inboard )     {         theboard = theboard;      }      public void computermove()     {         string spacing = " ";         (int = 0; < theboard.length; i++)         {             (int j = 0; j < theboard[i].length; j++)             {                  //int random = cpuinput.nextint(theboard[i][j]);                 theboard[2][2] = (cpu); //stuck here!                             }         } } 

you need find out available spots on board computer make move. among available spots can randomly choose 1 make move.

in below example, use list store available spots on board , use collections.shuffle() randomize list achieve purpose of making random move.

class spot {     int row;     int col;      public spot(int row, int col) {         this.row = row;         this.col = col;     } }  public void computermove() {     string spacing = " ";      // firstly finding out available moves computer     list<spot> availablespots = new arraylist<>();     (int = 0; < theboard.length; ++i) {         (int j = 0; j < theboard[i].length; ++j) {             if (theboard[i][j].equals(spacing)) {                 availablespots.add(new spot(i, j));             }         }     }      // if no available moves, nothing, game has ended     if (availablespots.isempty()) {         system.out.println("no more spots available on board.");         return;     } else {         // shuffle list becomes randomly orderedd         collections.shuffle(availablespots);          // first 1 of random list         spot spot = availablespots.get(0);         theboard[spot.row][spot.col] = (cpu);     } } 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -