字符串数组中的随机位置? Java的

时间:2015-10-31 00:48:21

标签: java arrays 2d

致力于构建一个tic tac toe游戏。我尝试使用尽可能简单的方法。我目前正致力于让cpu随机选择数组中的一个位置来放置" O"在。我该怎么做呢?这是我到目前为止所做的。

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 = " ";
        for (int i = 0; i < theBoard.length; i++)
        {
            for (int j = 0; j < theBoard[i].length; j++)
            {

                //int random = cpuInput.nextInt(theBoard[i][j]);
                theBoard[2][2] = (cpu); //STUCK HERE!                
            }
        }
}

2 个答案:

答案 0 :(得分:3)

您需要找出电路板上可用的位置,以便计算机移动。然后在可用的点中,您可以随机选择一个点进行移动。

在下面的例子中,我使用一个列表来存储棋盘上的可用位置,并使用Collections.shuffle()随机化列表以达到随机移动的目的。

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 the available moves for the computer
    List<Spot> availableSpots = new ArrayList<>();
    for (int i = 0; i < theBoard.length; ++i) {
        for (int j = 0; j < theBoard[i].length; ++j) {
            if (theBoard[i][j].equals(spacing)) {
                availableSpots.add(new Spot(i, j));
            }
        }
    }

    // if no available moves, do nothing, game has ended
    if (availableSpots.isEmpty()) {
        System.out.println("No more spots available on the board.");
        return;
    } else {
        // shuffle the list so that it becomes randomly orderedd
        Collections.shuffle(availableSpots);

        // get the first one of the random list
        Spot spot = availableSpots.get(0);
        theBoard[spot.row][spot.col] = (cpu);
    }
}

答案 1 :(得分:2)

你可以这样做,在0-2之间生成两个数字,如果不采取地点,将它放在索引[x] [y]

Random generator = new Random(); 
import java.util.*;
int x = generator.nextInt(3);
int y = generator.nextInt(3);
if place is not taken:
theBoard[x][y];
if place is taken generate again:
int x = generator.nextInt(3);
int y = generator.nextInt(3);