Advertisement
Guest User

Untitled

a guest
Jan 31st, 2013
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. /**
  2. A 3 x 3 tic-tac-toe board.
  3. */
  4. public class TicTacToe
  5. {
  6. /**
  7. Constructs an empty board.
  8. */
  9. public TicTacToe()
  10. {
  11. board = new String[ROWS][COLUMNS];
  12. // Fill with spaces
  13. for (int i = 0; i < ROWS; i++)
  14. for (int j = 0; j < COLUMNS; j++)
  15. board[i][j] = " ";
  16. }
  17.  
  18. /**
  19. Sets a field in the board. The field must be unoccupied.
  20. @param i the row index
  21. @param j the column index
  22. @param player the player ("x" or "o")
  23. */
  24. public void set(int i, int j, String player)
  25. {
  26. if (board[i][j].equals(" "))
  27. board[i][j] = player;
  28. }
  29.  
  30. /**
  31. Creates a string representation of the board, such as
  32. |x o|
  33. | x |
  34. | o|
  35. @return the string representation
  36. */
  37. public String toString()
  38. {
  39. String r = "";
  40. for (int i = 0; i < ROWS; i++)
  41. {
  42. r = r + "|";
  43. for (int j = 0; j < COLUMNS; j++)
  44. r = r + board[i][j];
  45. r = r + "|\n";
  46. }
  47. return r;
  48. }
  49.  
  50. public String getWinner()
  51. {
  52. int a = 0;
  53. int b = 0;
  54. String win = "";
  55.  
  56. for (int i = 0; i < 3; i++)
  57. {
  58. for (int j = 0; j < 3; j++)
  59. {
  60. if (board[i][j].equals(" "))
  61. return null;
  62. else if (board[i][j].equals("x"))
  63. a++;
  64. else if (board[i][j].equals("o"))
  65. b++;
  66. }
  67. }
  68.  
  69. if (a == 3)
  70. {
  71. win = "Player x is the winner.";
  72. }
  73. else if (b == 3)
  74. {
  75. win = "Player o is the winner.";
  76. }
  77.  
  78. return win;
  79. }
  80.  
  81. private String[][] board;
  82. private static final int ROWS = 3;
  83. private static final int COLUMNS = 3;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement