Advertisement
Generalpokey

Tic Tac Toe

Jul 24th, 2014
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10. import java.util.Scanner;
  11.  
  12.  
  13.  
  14.  
  15. public class Tictactoe
  16. {
  17. public static char [][] theBoard = new char[3][3];
  18. public static int c,r;
  19. public static Scanner scan = new Scanner(System.in);
  20. public static char turn = 'X';
  21.  
  22. public static void main(String agr[])
  23. {
  24. for(int i = 0; i < 3; i++)
  25. {
  26. for(int j = 0; j < 3; j++)
  27. {
  28. theBoard[i][j] = '*';
  29. }
  30. }
  31. System.out.println(" TIC TAC TOE!");
  32. System.out.print("-------------");
  33. play();
  34.  
  35. }
  36.  
  37.  
  38.  
  39. public static void play()
  40. {
  41. boolean playing = true;
  42. printBoard();
  43. while(playing)
  44. {
  45. System.out.println("Enter a row (1|2|3)");
  46. r = scan.nextInt() - 1;
  47. System.out.println("Enter a column (1|2|3)");
  48. c = scan.nextInt() - 1;
  49. theBoard[r][c] = turn;
  50.  
  51.    
  52.  
  53.  
  54.  
  55.  
  56. if(gameOver(r,c))
  57. {
  58. playing = false;
  59. System.out.println("Game Over!");
  60. System.out.print("Player " + turn + " wins!");
  61. }
  62.  
  63.  
  64. printBoard();
  65. if(turn == 'X')
  66. {
  67. turn = 'O';
  68. }
  69. else
  70. {
  71. turn = 'X';
  72. }
  73.  
  74. }
  75. }
  76. public static void printBoard() {
  77.   for (int i = 0; i < 3; i++) {
  78.       System.out.println();
  79.       for (int j = 0; j < 3; j++){
  80.         if (j == 0)
  81.           System.out.print("| ");
  82.         System.out.print(theBoard[i][j] + " | ");
  83.       }
  84.       }
  85.     System.out.println();
  86.   }
  87.  
  88. public static boolean gameOver(int r,int c)
  89. {
  90. //Check for | or - victory
  91. if(theBoard[0][c] == theBoard[1][c] && theBoard[0][c] == theBoard[2][c])
  92. {
  93. return true;
  94. }
  95. if(theBoard[r][0] == theBoard[r][1] && theBoard[r][0] == theBoard[r][2])
  96. {
  97. return true;
  98. }
  99. //check for \ or / victory
  100. if(theBoard[0][0] == theBoard[1][1] && theBoard[0][0] == theBoard[2][2] && theBoard[1][1] != '*')
  101. {
  102. return true;
  103. }
  104. if(theBoard[0][2] == theBoard[1][1] && theBoard[0][2] == theBoard[2][0] && theBoard[1][1] != '*')
  105. {
  106. return true;
  107. }
  108.  
  109. return false;
  110. }
  111.  
  112.  
  113.  
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement