Java Tic Tac Toe错误

时间:2014-02-06 01:14:24

标签: java string arraylist gridworld

根据具体情况,我必须使用GridWorld制作一个正常运行的Tic Tac Toe游戏。我已经完成了大部分课程,但有一种方法可以让我坚持下去。我不确定如何检查是否有对角线或垂直方向的赢家。以下是方法。

public String getWinner()
{
    Grid<Piece> grid = getGrid();
    if(grid == null)
    {
        return "no winner";
    }

    String winner = "";
    for (int r = 0; r<grid.getNumRows(); r++)
    {
        Piece row0 = grid.get(new Location(r,0));
        Piece row1 = grid.get(new Location(r,1));
        Piece row2 = grid.get(new Location(r,2));

        if(row0 == null || row1 == null || row2 == null)
        {
            continue;
        }

        if(row0.getName().equals(row1.getName()) && row0.getName().equals(row2.getName()))
        {
            winner = row0.getName()+ " wins horizontally!";
            break;
        }
    }

    //check for vertical winner

    //check for diagonal winner


    if(isWorldFull() && winner.length() == 0)
    {
        winner =  "cat's game - no winner!\n\n";
    }
    else if(!isWorldFull() && winner.length() == 0)
    {
        winner = "no winner";
    }

    return winner;
}

非常感谢任何和所有帮助。

1 个答案:

答案 0 :(得分:0)

// vertically
for (int c = 0; r<grid.getNumCols(); c++)
{
    Piece col0 = grid.get(new Location(0,c));
    Piece col1 = grid.get(new Location(1,c));
    Piece col2 = grid.get(new Location(2,c));

    if(col0 == null || col1 == null || col2 == null)
    {
        continue;
    }

    if(col0.getName().equals(col1.getName()) && col0.getName().equals(col2.getName()))
    {
        winner = col0.getName()+ " wins vertically!";
        break;
    }
}

// diagonal 1
for (int x = 0; r<grid.getNumRows(); x++)
{
    Piece d0 = grid.get(new Location(x,x));
    Piece d1 = grid.get(new Location(x,x));
    Piece d2 = grid.get(new Location(x,x));

    if(d0 == null || d1 == null || d2 == null)
    {
        continue;
    }

    if(d0.getName().equals(d1.getName()) && d0.getName().equals(d2.getName()))
    {
        winner = d0.getName()+ " wins diagonally!";
        break;
    }
}

// diagonal 2
for (int x = 0; r<grid.getNumRows(); x++)
{
    Piece d0 = grid.get(new Location(x,2-x));
    Piece d1 = grid.get(new Location(x,2-x));
    Piece d2 = grid.get(new Location(x,2-x));

    if(d0 == null || d1 == null || d2 == null)
    {
        continue;
    }

    if(d0.getName().equals(d1.getName()) && d0.getName().equals(d2.getName()))
    {
        winner = d0.getName()+ " wins diagonally!";
        break;
    }
}

请注意,您可以提取用于将三个单元格(row0,1,2,col0,1,2,d0,1,2)比较为一个单独的方法的代码:

boolean check3Pieces(Piece p0, Piece p1, Piece p2, String caption) {
    if(p0 == null || p1 == null || p2 == null)
    {
        return false;
    }

    if(p0.getName().equals(p1.getName()) && p0.getName().equals(p2.getName()))
    {
        winner = p0.getName()+ " " + caption;
        return true;
    }
    return false;
}