repl.it
@sthomason1/

tictactoe

Java

No description

fork
loading
Files
  • Main.java
  • jdt.ls-java-project
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.awt.Font; //needed to make the text bigger on line 65

class Tictactoe {
  public static void main(String[] args) {
    StdDraw.setPenRadius(.01);
    StdDraw.setScale(0, 3);
    StdDraw.line(1, 0, 1, 3); // Draws the tic-tac-toe board
    StdDraw.line(2, 0, 2, 3);
    StdDraw.line(0, 1, 3, 1);
    StdDraw.line(0, 2, 3, 2);
    StdDraw.setPenRadius(.05);
    int[][] board = new int[3][3]; // 0 is blank, 1 is X, -1 is O
    int turn = 0;
    while (turn < 9) { // after 9 turns, the game is over
      while (!StdDraw.isMousePressed()) {
      }
      int x = (int) StdDraw.mouseX();
      int y = (int) StdDraw.mouseY();
      if (board[x][y] == 0) { // checks if the square is empty
        if (turn % 2 == 0) { // checks whose turn it is
          drawX(x, y);
          board[x][y] = 1;
        } else {
          drawO(x, y);
          board[x][y] = -1;
        }
        turn++; // next turn
        if (turn > 4) { // checks for a winner
          for (int i = 0; i < 3; i++) {
            if ((board[i][0] == board[i][1] && board[i][0] == board[i][2])
                || (board[0][i] == board[1][i] && board[0][i] == board[2][i])) {
              if (board[i][i] == 1) { // board[i][i] is guaranteed to be an element in any of the rows/columns
                display("X Wins!");
                turn = 10; // so we don't trigger the draw case
              }
              if (board[i][i] == -1) {
                display("O Wins!");
                turn = 10;
              }
            }
          }
          if ((board[0][0] == board[1][1] && board[1][1] == board[2][2])
              || board[0][2] == board[1][1] && board[0][2] == board[2][0]) {
            if (board[1][1] == 1) { // similarily, board[1][1] is guaranteed to be an element of either diagonal
              display("X Wins!");
              turn = 10;
            }
            if (board[1][1] == -1) {
              display("O Wins!");
              turn = 10;
            }
          }
        }
      }
    }
    if (turn == 9) {
      display("Draw");
    }
  }

  public static void drawX(int xpos, int ypos) {
    StdDraw.line(xpos + .25, ypos + .25, xpos + .75, ypos + .75);
    StdDraw.line(xpos + .25, ypos + .75, xpos + .75, ypos + .25);
  }

  public static void drawO(int xpos, int ypos) {
    StdDraw.circle(xpos + .5, ypos + .5, .25);
  }

  public static void display(String text) {
    StdDraw.setPenColor(StdDraw.RED);
    Font f = new Font("serif", Font.PLAIN, 60);
    StdDraw.setFont(f);
    StdDraw.text(1.5, 2, text, 0);
  }
}
Fetching token
?