Advertisement
vencinachev

TicTacToe

Mar 18th, 2019
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class TicTacToe {
  4.  
  5.     public static void main(String[] args) {
  6.         Scanner scan = new Scanner(System.in);
  7.  
  8.         char[][] board = new char[3][3];
  9.  
  10.         for (int i = 0; i < 3; i++) {
  11.             for (int j = 0; j < 3; j++) {
  12.                 board[i][j] = ' ';
  13.             }
  14.         }
  15.  
  16.         char player = 'x';
  17.  
  18.         for (int i = 0; i < 9; i++) {
  19.             String[] command = scan.nextLine().split(",");
  20.             int x = Integer.parseInt(command[0]);
  21.             int y = Integer.parseInt(command[1]);
  22.  
  23.             if (x >= 0 && x < 3 && y >= 0 && y < 3 && board[x][y] == ' ') {
  24.                 board[x][y] = player;
  25.             } else {
  26.                 System.out.println("Invalid input!");
  27.                 i--;
  28.             }
  29.  
  30.             // change player
  31.             player = (player == 'o') ? 'x' : 'o';
  32.  
  33.             for (int k = 0; k < 3; k++) {
  34.                 for (int j = 0; j < 3; j++) {
  35.                     System.out.print(board[k][j] + "|");
  36.                 }
  37.                 System.out.println();
  38.             }
  39.  
  40.             for (int k = 0; k < 3; k++) {
  41.                 if (board[k][0] == board[k][1] && board[k][0] == board[k][2] && board[k][0] != ' ') {
  42.                     System.out.printf("Player %c win!", board[k][0]);
  43.                     return;
  44.                 }
  45.                 if (board[0][k] == board[1][k] && board[0][k] == board[2][k] && board[0][k] != ' ') {
  46.                     System.out.printf("Player %c win!", board[0][k]);
  47.                     return;
  48.                 }
  49.             }
  50.             if (board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] != ' ') {
  51.                 System.out.printf("Player %c win!", board[0][0]);
  52.                 return;
  53.             }
  54.             if (board[2][0] == board[1][1] && board[2][0] == board[0][2] && board[1][1] != ' ') {
  55.                 System.out.printf("Player %c win!", board[1][1]);
  56.                 return;
  57.             }
  58.         }
  59.         System.out.println("No winner!");
  60.  
  61.     }
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement