Advertisement
Guest User

Untitled

a guest
Nov 14th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.75 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class TicTacToe{
  4. public static int row, col;
  5. public static Scanner scan = new Scanner(System.in);
  6. public static char[][] board = new char [3][3];
  7. public static char turn ='X';
  8.  
  9. public static void main(String[] args) {
  10. for (int i=0; i<3; i++){
  11. for (int j=0; j<3; j++){
  12. board[i][j] = '_';
  13. }
  14. }
  15. PLAY();
  16. }
  17.  
  18. public static void PLAY(){
  19. boolean playing = true;
  20. PRINTBOARD();
  21. while (playing){
  22. System.out.println("Please enter a row and column (Between 1 and 3): ");
  23. row = scan.nextInt() -1;
  24. col = scan.nextInt() -1;
  25. if (row >= 3) {
  26. System.out.println("Please Enter a Number between 1 and 3");
  27. }
  28. else {
  29. System.out.println("You cannot play a column higher than the number 3, PLEASE Enter a Number between 1 and 3");
  30. row = scan.nextInt() -1;
  31. }
  32.  
  33. if (col >= 3) {
  34. System.out.println("Please Enter a Number between 1 and 3");
  35. }
  36. else {
  37. System.out.println("You cannot play a row higher than the number 3, PLEASE Enter a Number between 1 and 3");
  38. row = scan.nextInt() -1;
  39. }
  40. board [row][col] = turn;
  41. if(GAMEOVER(row,col)){
  42. playing = false;
  43. System.out.print("Game over! Player " + turn+ " wins!");
  44. }
  45.  
  46. PRINTBOARD();
  47. if(turn == 'X'){
  48. turn = '0';
  49. }
  50. else{
  51. turn = 'X';
  52. }
  53. }
  54. }
  55.  
  56. public static void PRINTBOARD() {
  57. for (int i = 0; i < 3; i++) {
  58. System.out.println();
  59. for (int j = 0; j < 3; j++) {
  60. if (j==0)
  61. System.out.print("| ");
  62. System.out.print(board[i][j] + " | ");
  63.  
  64. }
  65.  
  66. }
  67. System.out.println();
  68. }
  69.  
  70. public static boolean GAMEOVER(int rMove, int cMove){
  71. if (board[0][cMove] == board [1][cMove]
  72. && board [0][cMove] == board[2][cMove]) {
  73. return true;
  74. }
  75. if (board[rMove][0] == board [rMove][1]
  76. && board [rMove][0] == board[rMove][2]) {
  77. return true;
  78. }
  79. if (board[0][0] == board [1][1]
  80. && board [0][0] == board[2][2]
  81. && board[1][1] != '_'){
  82. return true;
  83. }
  84. if (board[0][2] == board [1][1]
  85. && board [0][2] == board[2][0]
  86. && board[1][1] != '_'){
  87. return true;
  88. }
  89. return false;
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement