nicatronTg

Untitled

Apr 18th, 2012
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. // a 3x3 array of characters represents the board
  2. char[][] board = new char[3][3];
  3. // how big is each box, and where did you click
  4. int boxSize, clickX, clickY;
  5. // is it X's turn (true) or O's turn (false)
  6. boolean turnX = true;
  7. int backgroundColor = 155;
  8. int strokeColor = 0;
  9.  
  10. void setup() {
  11. size(300,300);
  12. boxSize = width/3;
  13. strokeWeight(2.0);
  14. stroke(strokeColor);
  15. background(backgroundColor);
  16. resetBoard();
  17. }
  18.  
  19. // set all the squares to '?' (no player has used them)
  20. void resetBoard() {
  21. for (int i = 0; i < 3; i++) {
  22. for (int j = 0; j < 3; j++) {
  23. board[i][j] = '?';
  24. }
  25. }
  26. }
  27.  
  28. // draw an X
  29. void drawX(int x, int y) {
  30. line(x - boxSize/4, y - boxSize/4, x + boxSize/4, y + boxSize/4);
  31. line(x - boxSize/4, y + boxSize/4, x + boxSize/4, y - boxSize/4);
  32. }
  33.  
  34. // draw an O
  35. void drawO(int x, int y) {
  36. fill(155);
  37. ellipse(x, y, boxSize/2, boxSize/2);
  38. }
  39.  
  40. void drawBoard() {
  41. // draw the grid lines
  42. line(boxSize, 0, boxSize, height);
  43. line(2*boxSize, 0, 2*boxSize, height);
  44. line(0, boxSize, width, boxSize);
  45. line(0, 2*boxSize, width, 2*boxSize);
  46. // populate the board
  47. for (int i = 0; i < 3; i++) {
  48. for (int j = 0; j < 3; j++) {
  49. if (board[i][j] == 'X') {
  50. drawX(boxSize*i + boxSize/2, boxSize*j + boxSize/2);
  51. }
  52. else if (board[i][j] == 'O') {
  53. drawO(boxSize*i + boxSize/2, boxSize*j + boxSize/2);
  54. }
  55. }
  56. }
  57. }
  58.  
  59. // when a square is clicked, save the mouse coords and update
  60. void mousePressed() {
  61. clickX = mouseX;
  62. clickY = mouseY;
  63. updateBoard();
  64. }
  65.  
  66. // update the board[][] array with the clicked square
  67. void updateBoard() {
  68.  
  69. int i, j;
  70.  
  71. // which 3rd of the board did the X coord land on
  72. if (clickX < boxSize) i = 0;
  73. else if (clickX < 2*boxSize) i = 1;
  74. else if (clickX < width) i = 2;
  75. else i = -1;
  76.  
  77. // which 3rd of the board did the Y coord land on
  78. if (clickY < boxSize) j = 0;
  79. else if (clickY < 2*boxSize) j = 1;
  80. else if (clickY < width) j = 2;
  81. else j = -1;
  82.  
  83. // if the click was inside the grid and the space hasn't been used
  84. if (i >= 0 && j >= 0 & board[i][j] == '?') {
  85. // set the square based on whose turn it is
  86. if (turnX) {
  87. board[i][j] = 'X';
  88. }
  89. else {
  90. board[i][j] = 'O';
  91. }
  92. }
  93. }
  94.  
  95. void draw() {
  96. drawBoard();
  97. }
Advertisement
Add Comment
Please, Sign In to add comment