测试井字胜利条件 [英] testing tic tac toe win condition
本文介绍了测试井字胜利条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在寻找最有效的的Java 的方式来测试,如果有人赢得了井字。这些数据是在一个二维数组像这样...
I'm looking for the most efficient java way to test if somebody has won at tic tac toe. The data is in a 2d array like so...
char[][] ticTacToe =
{{'X',' ','O'},
{'O','X','O'},
{'X',' ','X'},};
我知道这是不专业的方式来初始化数组,但我只是在这里测试。的
我可以现在做的最好的是一个详尽的if / else树。 这里有一个那些树的...
The best I can do for right now is an exhaustive if/else tree. Here's one of those trees...
if (ticTacToe[1][1] == 'X'){
if (ticTacToe[0][0] == 'X'){
if (ticTacToe[2][2] == 'X'){
System.out.println("X wins");
}
}
else if (ticTacToe[0][1] == 'X'){
if (ticTacToe[2][1] == 'X'){
System.out.println("X wins");
}
}
else if (ticTacToe[1][0] == 'X'){
if (ticTacToe[1][2] == 'X'){
System.out.println("X wins");
}
}
else if (ticTacToe[2][0] == 'X'){
if (ticTacToe[0][2] == 'X'){
System.out.println("X wins");
}
}
}
此只关心什么是在中间的
这是很基本的,我想提高它尽可能最小化code线去。
This is very basic and I want to improve it as far as minimizing lines of code goes.
推荐答案
这是一个有点冗长,但我认为这可能是最有效的方法来做到这一点(除非有人能想出一个聪明的办法,在检查两个对角线一次)。
It's a bit verbose, but I think this is probably the most efficient way to do it (unless someone can come up with a clever way to check both diagonals at once).
public class TicTacToe
{
char[][] ticTacToe =
{{'X',' ','O'},
{'O','X','O'},
{'X',' ','X'},};
private Character winner = null;
public Character getWinner()
{
return this.winner;
}
public boolean isSolved()
{
this.checkSolved();
return this.winner != null;
}
private void checkSolved()
{
for(int i = 0; i < ticTacToe.length; i++)
{
Character win = checkRow(i);
if(win != null || (win = checkColumn(i)) != null)
{
this.winner = win;
return;
}
}
//Check diagonal top left to bottom right
if(this.ticTacToe[0][0] != ' ')
{
if(this.ticTacToe[0][0] == this.ticTacToe[1][1] &&
this.ticTacToe[1][1] == this.ticTacToe[2][2])
{
this.winner = this.ticTacToe[0][0];
}
}
//Check diagonal top right to bottom left
else if(this.ticTacToe[0][2] != ' ')
{
if(this.ticTacToe[0][2] == this.ticTacToe[1][1] &&
this.ticTacToe[1][1] == this.ticTacToe[2][0])
{
this.winner = this.ticTacToe[0][2];
}
}
}
private Character checkRow(int row)
{
if(this.ticTacToe[row][0] == ' ')
{
return null;
}
if(this.ticTacToe[row][0] == this.ticTacToe[row][1] &&
this.ticTacToe[row][1] == this.ticTacToe[row][2])
{
return this.ticTacToe[row][0];
}
return null;
}
private Character checkColumn(int column)
{
if(this.ticTacToe[0][column] == ' ')
{
return null;
}
if(this.ticTacToe[0][column] == this.ticTacToe[1][column] &&
this.ticTacToe[1][column] == this.ticTacToe[2][column])
{
return this.ticTacToe[column][0];
}
return null;
}
public static void main(String[] args)
{
TicTacToe ttt = new TicTacToe();
if(ttt.isSolved())
{
System.out.println(ttt.getWinner()); // X
}
}
}
这篇关于测试井字胜利条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文