对于一项作业,我被要求创建一个[7] x [7]矩阵,以及一个井字游戏与计算机。玩家是X,计算机是O。 [1] [1]是选择1,[1] [3]是选择2,[1] [5]是选择3,[3] [1]是选择4,依此类推,直到选择9。 除了创建两个通过播放器的布尔方法和计算机方法以检查空间是否已被占用以外,我已完成所有操作。
我似乎无法创建while循环和if语句,一旦它生成1到9之间的随机数,它就逻辑上告诉计算机,如果该数字已经被占用,则生成另一个随机数,直到该数字未采取。
public static char[][] ComputerPlays(char[][] M)
{
System.out.println("Computer selects grid position...");
// *** computer play code ***
int x = (int)((Math.random() * 9)+1);
if (x ==1)
{
while (occupied(M[1][1]) == true)
{
x = (int)((Math.random() *9)+1);
}
if (occupied(M[1][1])== false)
{
M[1][1] = 'O';
}
}
if (x ==2)
{
if (occupied(M[1][3])== true)
{
x = (int)((Math.random() *9) +1);
}
if (occupied(M[1][3])== false)
{
M[1][3] = 'O';
}
}
while (x ==3)
{
if (occupied(M[1][5])== true)
{
x = (int)((Math.random() *9) +1);
}
if (occupied(M[1][5])== false)
{
M[1][5] = 'O';
}
}
while (x ==4)
{
if (occupied(M[3][1])== true)
{
x = (int)((Math.random() *9) +1);
}
if (occupied(M[3][1])== false)
{
M[3][1] = 'O';
}
}
while (x ==5)
{
if (occupied(M[3][3])== true)
{
x = (int)((Math.random() *9) +1);
}
if (occupied(M[3][3])== false)
{
M[3][3] = 'O';
}
}
while(x ==6)
{
if (occupied(M[3][5])== true)
{
x = (int)((Math.random() *9) +1);
}
if (occupied(M[3][5])== false)
{
M[3][5] = 'O';
}
}
while(x ==7)
{
if (occupied(M[5][1])== true)
{
x = (int)((Math.random() *9) +1);
}
if (occupied(M[5][1])== false)
{
M[5][1] = 'O';
}
}
while (x ==8)
{
if (occupied(M[5][3])== true)
{
x = (int)((Math.random() *9) +1);
}
if (occupied(M[5][3])== false)
{
M[5][3] = 'O';
}
}
while (x ==9)
{
if (occupied(M[5][5])== true)
{
x = (int)((Math.random() *9) +1);
}
if (occupied(M[5][5])== false)
{
M[5][5] = 'O';
}
}
return M;
}//end Computer Play