I have created a simple tic tac toe game in Java. The game and code works however when someone wins it lets the other player play once more before terminating and says that particular player has won. I am trying to figure out a way to allow the game to stop when a player has won. I have looked at a few different algorithms for this type of scenario here and here. But am still getting confused.
Are there any suggestions?
edit: this code is fully working now, with invalid moves not allowed anymore.
import java.util.Scanner;
public class TicTacToe{
public static Scanner scan = new Scanner(System.in);
private static int boardSize = 3;
private static char[][] board = new char[boardSize][boardSize];
private static char turn = 'O';
private static char moveNum = 0;
public static void initiliaze(){
for(int i = 0; i<boardSize;i++){
for(int j = 0;j<boardSize;j++){
board[i][j]='-';
}
}
}
public static void printBoard(){
for(int i=0; i<boardSize;i++){
for(int j=0; j<boardSize;j++){
System.out.print(board[i][j]);
if (j != boardSize-1){
System.out.print("|");
}
}
System.out.println();
if(i!=boardSize-1){
System.out.println("-----");
}
}
System.out.println();
}
public static boolean checkWin(){
if(((board[0][0]==turn && board[0][1]==turn && board[0][2]==turn)||
(board[1][0]==turn && board[1][1]==turn && board[1][2]==turn)||
(board[2][0]==turn && board[2][2]==turn && board[2][2]==turn)||
(board[0][0]==turn && board[1][0]==turn && board[2][0]==turn)||
(board[0][1]==turn && board[1][1]==turn && board[2][1]==turn)||
(board[0][2]==turn && board[1][2]==turn && board[2][2]==turn)||
(board[0][0]==turn && board[1][1]==turn && board[2][2]==turn)||
(board[0][2]==turn && board[1][1]==turn && board[2][0]==turn)))
return true;
return false;
}
public static void makeMove(){
int row, col;
boolean validInput = false;
do{
if(turn == 'X'){
System.out.print("Player X enter your move (row:1,2,3)!");
}else{
System.out.print("Player O enter your move (row:1,2,3)!");
}
row = scan.nextInt() - 1;
if(turn == 'X'){
System.out.print("Player X enter your move (col:1,2,3)!");
}else{
System.out.print("Player O enter your move (col:1,2,3)!");
}
col = scan.nextInt() - 1;
if(row >= 0 && row < boardSize && col >=0 && col < boardSize && board[row][col] == '-'){
board[row][col] = turn;
validInput = true;
}else{
System.out.println("This move at (" + (row + 1) + "," + (col + 1)
+ ") is not valid. Try again...");
}
}while(!validInput);
}
public static void changeMove(){
if(turn == 'X'){
turn = 'O';
}else{
turn = 'X';
}
moveNum++;
}
public static void play(){
do{
changeMove();
makeMove();
printBoard();
}while(checkWin()==false && (moveNum < boardSize*boardSize));
if (turn=='X' && checkWin()==true){
System.out.println("X has won");
}
if(checkWin() == true && turn=='O'){
System.out.println("O has won");
}else{
System.out.println("This is a draw!");
}
}
}
class PlayGame {
public static void main (String[] args){
TicTacToe.initiliaze();
TicTacToe.printBoard();
TicTacToe.play();
}
}