字符串数组中的随机位置?爪哇 [英] Random position in string array? Java
问题描述
致力于构建井字游戏.我正在尝试使用尽可能简单的方法.我目前正在努力让 cpu 随机选择阵列中的一个点来放置O".我该怎么做?这是我目前所拥有的.
Working on building a tic tac toe game. I'm trying to use as simple of methods as possible. I'm currently working on getting the cpu to randomly choose a spot in the array to place the "O" at. How do I go about doing this? This is what I have so 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 = " ";
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!
}
}
}
推荐答案
您需要找出黑板上的可用位置,以便计算机进行移动.然后在可用的地点中您可以随机选择一个进行移动.
You need to find out the available spots on the board for computer to make a move. Then among the available spots you can randomly choose one to make a move.
在下面的例子中,我使用一个列表来存储棋盘上的可用点,并使用 Collections.shuffle() 来随机化列表以达到随机移动的目的.
In the below example, I use a list to store the available spots on the board and use Collections.shuffle() to randomize the list to achieve the purpose of making a 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 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);
}
}
这篇关于字符串数组中的随机位置?爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!