tic tac toe in java

http‮/:s‬/www.lautturi.com
tic tac toe in java

Tic-tac-toe (also known as noughts and crosses or Xs and Os) is a simple two-player game played on a 3x3 grid. Players take turns placing their symbol (either an "X" or an "O") on the grid, with the goal of getting three of their symbols in a row (horizontally, vertically, or diagonally) before the other player. If all of the spaces on the grid are filled and no player has won, the game is a draw.

Here's an example of how you can implement a simple tic-tac-toe game in Java using a two-dimensional array to represent the grid:

public class TicTacToe {
  public static final int X = 1, O = -1;  // constants for X and O
  public static final int EMPTY = 0;  // constant for an empty space

  private int[][] board;  // the game board
  private int currentPlayer;  // the current player (X or O)

  public TicTacToe() {
    board = new int[3][3];
    currentPlayer = X;
  }

  public void play(int row, int col) {
    if (board[row][col] != EMPTY) {
      throw new IllegalArgumentException("Space is already occupied");
    }
    board[row][col] = currentPlayer;
    currentPlayer = -currentPlayer;  // switch player
  }

  public int winner() {
    // check rows
    for (int i = 0; i < 3; i++) {
      if (board[i][0] == board[i][1] && board[i][0] == board[i][2]) {
        return board[i][0];
      }
    }

    // check columns
    for (int j = 0; j < 3; j++) {
      if (board[0][j] == board[1][j])
Created Time:2017-10-17 20:18:57  Author:lautturi