我一直在用Java创建四连环游戏。最初,它是为两名人类玩家相互对抗而设计的。但是,我现在尝试对第二个播放器(现在是计算机)使用math.random()
函数,以便计算机选择一个随机列来放入计数器(不必做得好还是不好,只是随机)。
当前,math.random()
函数只是将计数器放置在人类玩家每次下棋后放置其计数器的位置的顶部。如何获得math.random()
函数以选择0到6之间的随机列?
我知道我的代码具有重复/重复/格式错误,在设法解决此AI功能后,我将重构我的代码。
play.java
public class play {
private Connect4Game connect;
public play(Connect4Game connect) {
this.connect=connect;
}
public void playGame() {
System.out.println("Welcome to Connect 4");
System.out.println("To play the game type in the number of the column you want to drop you counter in");
System.out.println("Player One = r Player 2 = y");
System.out.println("");
board boardObj = new board(connect);
boardObj.printBoard();
boolean win = false;
while(!win){
// player 1
String userInput = getUserInput();
int move = Integer.parseInt(userInput);
counter counterObj = new counter(connect);
counterObj.placeCounter('r', move);
boolean hasWon = false;
int count = 0;
// check horizontal
for(int i=0; i<connect.board.length; i++){
for(int j=0; j<connect.board[i].length; j++){
if(connect.board[i][j] == 'r'){
count = count + 1;
if(count == 4){
hasWon = true;
}
}
else{
count = 0;
}
}
}
// check vertical
count = 0;
for(int i=0; i<connect.board[0].length; i++){
for(int j=0; j<connect.board.length; j++){
if(connect.board[j][i] == 'r'){
count = count + 1;
if(count >= 4){
hasWon = true;
}
}
else{
count = 0;
}
}
}
boardObj.printBoard();
if(hasWon){
win = true;
System.out.println("You Have Won!!!");
}
else {
//Computer player
math.random();
counterObj.placeCounter('y',move);
hasWon = false;
count = 0;
// check horizontal
for(int i=0; i<connect.board.length; i++){
for(int j=0; j<connect.board[i].length; j++){
if(connect.board[i][j] == 'y'){
count = count + 1;
if(count >= 4){
hasWon = true;
}
}
else{
count = 0;
}
}
}
// check vertical
count = 0;
for(int i=0; i<connect.board[0].length; i++){
for(int j=0; j<connect.board.length; j++){
if(connect.board[j][i] == 'y'){
count = count + 1;
if(count >= 4){
hasWon = true;
}
}
else{
count = 0;
}
}
}
boardObj.printBoard();
if(hasWon){
win = true;
System.out.println("You Have Won!!!");
}
}
}
}
public String getUserInput(){
String toReturn = null;
try{
toReturn = connect.input.readLine();
}
catch(Exception e){
}
return toReturn;
}
答案 0 :(得分:1)
您可以通过执行以下操作获得随机数:
Random r = new Random();
int num = r.nextInt(7);
我将7设置为6,因为最大值是互斥的。因此,如果我输入6,它将为您提供0到5之间的数字。