需要帮助我的tic tac toe演示无效的顶级声明

时间:2015-03-23 16:39:01

标签: java arrays tic-tac-toe

    public class TicTacToe
{
  private char currentPlayer;
  private char[][] board;

  public TicTacToe()
  {
    board = new char [3][3];
    currentPlayer = 'x';
    startBoard();
  }

  public void startBoard()
  {
    for (int i = 0; i < 3; i++)
    {
      for (int j = 0; j < 3; j++)
      {
        board[i][j] = '-';
      }
    }
  }

  public void makeBoard()
  {
    System.out.println("---------------");
    for (int i = 0; i < 3; i++)
    {
      System.out.print("| ");
      for (int j = 0; j < 3; j++)
      {
        System.out.print(board[i][j] + " | ");
      }
      System.out.println();
      System.out.println("---------------");
    }
  }

  public boolean fullBoard()
  {
    boolean full = true;
    for (int i = 0; i < 3; i++)
    {
      for (int j = 0; j < 3; j++) 
      {
        if (board[i][j] == '-')
        {
          full = false;
        }
      }
    }
    return full;
  }

  public boolean win()
  {
    return (rowWin() || columnWin() || diagWin());
  }

  private boolean rowWin()
  {
    for (int i = 0; i < 3; i++)
    {
      if (rowColumn(board[i][0], board[i][1], board[i][2]) == true)
      {
        return true;
      }
    }
    return false;
  }

  private boolean columnWin()
  {
    for (int i = 0; i < 3; i++)
    {
      if (rowColumn(board[0][i], board[1][i], board[2][i]) == true)
      {
        return true;
      }
    }
    return false;
  }

  private boolean diagWin()
  {
    return ((rowColumn(board[0][0], board[1][1], board[2][2]) == true) || 
            (rowColumn(board[0][2], board[1][1], board[2][0]) == true));
  }

  private boolean rowColumn(char rc1, char rc2, char rc3)
  {
    return ((rc1 != '-') && (rc1 == rc2) && (rc2 == rc3));
  }

  public void playerChange()
  {
    if (currentPlayer == 'x')
    {
      currentPlayer = 'o';
    }
    else
    {
      currentPlayer = 'x';
    }
  }

  public boolean placeMark(int row, int column)
  {
    if ((row >= 0) && (row < 3))
    {
      if ((column >= 0) && (column < 3))
      {
        if (board[row][column] == '-')
        {
          board[row][column] = currentPlayer;
          return true;
        }
      }
    }
    return false;
  }
}

public class TicTacToedemo
{
  public static void main(String[] args)
  {
    TicTacToe demo = new TicTacToe();
    demo.makeBoard();
    if (demo.win())
    System.out.println("Winner! Hooray!");
    else if (demo.fullBoard())
      System.out.println("Cat Scratch, Draw.");
    demo.playerChange();
  }
}

我不确定如何正确地玩游戏,每当我运行它时输入数字,我都会收到错误代码。我做错了什么?代码可以编译并运行并显示板,但是当我去放置我希望x或o去的地方时,我得到错误代码“无效的顶级语句”

1 个答案:

答案 0 :(得分:1)

您必须使用Scanner类使用import java.util.Scanner进行播放器输入,然后存储输入。导入后,它将如下所示:

Scanner sc = new Scanner(System.in);
int input = sc.nextInt();

您必须管理sc.nextInt()结果,在此示例中为input变量。