我一直在从事Java tic tac toe项目,无法超越我需要检查他们在水平或垂直方向上是否获胜的部分。我也想不通如何做到这一点,以便计算机和用户交替旋转直到板子装满为止。
到目前为止是我的代码:
import java.util.Scanner;
import java.util.Random;
public class TicTacToe
{
public static void main (String[] args)
{
Scanner r = new Scanner (System.in);
int rows = 3;
int col = 3;
int [][] grid = new int [rows][col];
fillGrid(grid);
computerTurn(grid);
userTurn(grid);
}//end main
public static void fillGrid(int [][] grids)
{
//int [][] grids = new int [3][3];
for (int r = 0; r < grids.length; r++)
{
for(int c = 0; c < grids[r].length; c++)
{
grids[r][c] = 0;
}
}
//printGrid(grids);
}
public static void printGrid (int [][] x)
{
for (int i = 0; i < x.length; i++)
{
for (int y = 0; y < x[0].length; y++)
{
System.out.print (x[i][y] + "\t");
}
System.out.println();
}
}
public static void computerTurn (int [][] mygrid)
{
Random rand = new Random();
int ranRow;
int ranCol;
boolean loop = true;
while(loop)
{
ranRow = rand.nextInt(2);
ranCol = rand.nextInt(2);
if(mygrid[ranRow][ranCol] == 0)
{
mygrid[ranRow][ranCol] = 1;
loop = false;
}
}
printGrid(mygrid);
}
public static void userTurn (int [][] gridy)
{
Scanner r = new Scanner (System.in);
int userRow;
int userCol;
boolean loop = true;
while(loop)
{
System.out.println("Enter a row 0-2");
userRow = r.nextInt();
System.out.println("Enter a column 0-2");
userCol = r.nextInt();
if(gridy[userRow][userCol] == 0)
{
gridy[userRow][userCol] = 2;
loop = false;
}
else//if(gridy[userRow][userCol] != 0)
{
System.out.println("This spot is already taken. Try again!");
}
}
printGrid(gridy);
}
public static Boolean checkHorizontalWin (int [][] grid)
{
// Check the rows and columns
for (int i = 0; i < grid.length; i++)
{
if(kms[i][0] == grid[i][1] && grid [i][1] == grid[i][2])
{
System.print.outln("you won!");
if(kms[i][0] == 1)
{
System.out.prinln("You won");
{
return false;
}
}
}
}