Skip to content

Instantly share code, notes, and snippets.

@dhinojosa
Created August 8, 2024 15:47
Show Gist options
  • Save dhinojosa/e98d9600666301d54a3fb90e7b8f26d9 to your computer and use it in GitHub Desktop.
Save dhinojosa/e98d9600666301d54a3fb90e7b8f26d9 to your computer and use it in GitHub Desktop.
Made by AI, needs refactoring
import java.util.Scanner;
public class TicTacToe {
private static char[][] board = new char[3][3];
private static char currentPlayer = 'X';
public static void main(String[] args) {
initializeBoard();
playGame();
}
private static void initializeBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '-';
}
}
}
private static void playGame() {
boolean gameRunning = true;
Scanner scanner = new Scanner(System.in);
while (gameRunning) {
printBoard();
System.out.println("Player " + currentPlayer + ", enter your move (row and column): ");
int row = scanner.nextInt();
int col = scanner.nextInt();
if (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == '-') {
board[row][col] = currentPlayer;
if (checkWin()) {
gameRunning = false;
printBoard();
System.out.println("Player " + currentPlayer + " wins!");
} else if (isBoardFull()) {
gameRunning = false;
printBoard();
System.out.println("The game is a tie!");
} else {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
} else {
System.out.println("This move is not valid");
}
}
scanner.close();
}
private static void printBoard() {
System.out.println("-------------");
for (int i = 0; i < 3; i++) {
System.out.print("| ");
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j] + " | ");
}
System.out.println();
System.out.println("-------------");
}
}
private static boolean checkWin() {
// Check rows and columns
for (int i = 0; i < 3; i++) {
if ((board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer) ||
(board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i] == currentPlayer)) {
return true;
}
}
// Check diagonals
if ((board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer) ||
(board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer)) {
return true;
}
return false;
}
private static boolean isBoardFull() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == '-') {
return false;
}
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment