I've never done anything in java, but today I had a couple hours of free time so I decided I would learn it and make a Tic Tac Toe game. Please give me some constructive criticism on anything you would do differently.
import java.util.Scanner;
import java.util.stream.IntStream;;
public class TicTacToe {
static Scanner scan = new Scanner(System.in);
static char board[] = {'A','B','C','D','E','F','G','H','I'};
static final int scoreboard[] = {1,2,7,6,0,4,3,8,9};
static int player = 0;
static boolean gameOver = false;
static int score[][] = {{0,0,0,0,0},{0,0,0,0}};
static int turn[] = {0,0,5};
public static void main(String[] args) {
while (gameOver == false) {
askForTurn();
}
}
public static void askForTurn() {
System.out.printf("\n-------------\n| %s | %s | %s |\n-------------\n| %s | %s | %s |\n-------------\n| %s | %s | %s |\n-------------",board[0],board[1],board[2],board[3],board[4],board[5],board[6],board[7],board[8]);
boolean valid = false;
System.out.printf("\nPlayer %o's turn:", (player+1));
char input = scan.next().toUpperCase().charAt(0);
int i;
for (i = 0; i < 9; i++) {
if (input == board[i]) {
if (player == 0) {
valid = true;
board[i] = 'O';
score[0][turn[0]] = scoreboard[i];
turn[0]++;
} else {
valid = true;
board[i] = 'X';
score[1][turn[1]] = scoreboard[i];
turn[1]++;
}
}
}
if (valid == false) {
System.out.print("\nInvalid square");
askForTurn();
} else {
checkForWin();
player++;
if (player%2 == 0) {
player = 0;
}
}
}
public static void checkForWin() {
int sum1 = IntStream.of(score[0]).sum();
int sum2 = IntStream.of(score[1]).sum();
int x;
ifWin(1, 0, 3, sum1%10, 0);
ifWin(1, 0, 3, sum2%10, 1);
for (x = 0; x < turn[0]; x++) {
ifWin(1, 0, 4, (sum1 - score[0][x])%10, 0);
}
for (x = 0; x < (turn[1] - 1); x++) {
ifWin(1, 0, 4, (sum2 - score[1][x])%10, 1);
}
if (turn[0] == 5) {
for (x = 0; x < 3; x++) {
ifWin(1, 0, 5, (sum1-score[0][0]-score[0][x+1])%10, 0);
ifWin(x, 0, 5, (sum1-score[0][1]-score[0][x+1])%10, 0);
ifWin(x, 1, 5, (sum1-score[0][2]-score[0][3])%10, 0);
ifWin(x, 1, 5, 0, 2);
}
}
}
public static void endGame(int player) {
if (player == 3) {
System.out.print("\nTie!");
} else {
System.out.printf("Player %o wins!", player);
}
gameOver = true;
}
public static void ifWin(int x, int z, int turnCheck, int statement, int player) {
if (x > z && turn[player] == turnCheck && statement == 0) {
endGame(player + 1);
}
}
}
1
s and5
s and%10
s but they're just magic numbers at the moment. \$\endgroup\$