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

标签 java arrays 2d

致力于构建井字游戏。我正在尝试使用尽可能简单的方法。我目前正在努力让 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!                
            }
        }
}

最佳答案

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

在下面的示例中,我使用一个列表来存储棋盘上的可用位置,并使用 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);
    }
}

关于java - 字符串数组中的随机位置? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33446884/

相关文章:

java - junitreport : xslt fails with StackOverflowError when there are many newlines/linefeeds

java - struts中的文件上传

java - 获取日期之间的数据

php - 我怎样才能将这个字符串转换为数组?

javascript - 在javascript中按字符串长度过滤数组

java - 在 Java 中为具体类型重写 equals() 有什么好处吗?

java - 三角形路径的弯曲边?

java - 如何根据设备制造商执行不同的代码?

C++ 使用带字符串数组的 execvp

javascript - 如何找到具有与 X 相关的起点、宽度和 Angular 点坐标