Last active
November 2, 2023 21:19
-
-
Save gigamonkey/83a470721fb9f91da061b23dc5849d85 to your computer and use it in GitHub Desktop.
Code golfed tic tac toe. Doesn't allow moving in occupied squares and detects wins and ties. Didn't exactly stick to what we've covered so for. Don't try this at home.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class TicTacToe { | |
public static void printBoard(int board) { | |
System.out.print("\033[2J\033[0;0H"); | |
int pieces = board >> 4; | |
for (int i = 0; i < 9; i++) { | |
System.out.print(" " + (i + "XO").charAt((pieces >> i & 1 | pieces >> i + 8 & 2) & 3) + " "); | |
if (i % 3 < 2) { | |
System.out.print("|"); | |
} else { | |
System.out.println(i / 3 < 2 ? "\n---+---+---" : "\n"); | |
} | |
} | |
} | |
public static int getMove(int board, Scanner input) { | |
int m = input.nextInt(); | |
while (((board >> m | board >> (m + 9)) & 1) == 1) { | |
System.out.println("Square occupied. Please try again."); | |
m = input.nextInt(); | |
} | |
return m; | |
} | |
public static boolean winner(int player) { | |
for (int i = 0; i < 3; i++) { | |
if (((7 << 3 * i) & player) == (7 << 3 * i)) return true; | |
if (((73 << i) & player) == (73 << i)) return true; | |
} | |
return ((273 & player) == 273 || (84 & player) == 84); | |
} | |
public static void main(String[] args) { | |
Scanner input = new Scanner(System.in); | |
int board = 0; | |
while (!winner(board >> (4 + ((~board & 1) * 9))) && (board & 15) < 9) { | |
printBoard(board); | |
board |= 16 << getMove(board >> 4, input) + (board & 1) * 9; | |
board++; | |
} | |
printBoard(board); | |
if (winner(board >> (4 + (~board & 1) * 9))) { | |
System.out.println("\n" + "OX".charAt(board & 1) + " wins!\n"); | |
} else { | |
System.out.println("\nTie!\n"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment