Java Tic Tac Toe Game Confirming Winner - java

Below is my code for a Tic Tac Toe game. There are two problems I am running into. For one, I am not sure how to return which player has won (X or O), I can just return if there is a winner. As well, when I try to run my program I can an out of bounds error. Where did I go wrong?
I have two files, one being TicTacToe and the other TTTBoard.
TicTaeToe.java
import java.util.Scanner;
import java.util.Random;
public class TicTacToe
{
public static void main(String[]args){
Scanner reader = new Scanner(System.in);
TTTBoard board = new TTTBoard();
System.out.println(board);
Random gen = new Random();
char player;
if(gen.nextInt(2)==1)
player = 'o';
else
player = 'x';
while(!board.checkWinner() && !board.full()){
System.out.println(player + " 's turn");
System.out.println("Enter the row and column [1-3, space, 1-3]: ");
int row = reader.nextInt();
int column = reader.nextInt();
boolean success = board.placeXor0(player, row, column);
if(!success)
System.out.println("Error: cell already occupied!");
else{
System.out.println(board);
if(player == 'x')
player = 'o';
else
player = 'x';
}
}
}
}
TTTBoard.java
public class TTTBoard{
private char[][] board;
public TTTBoard(){
board = new char[3][3];
reset();
}
public void reset(){
for(int row = 0; row < 3; row++)
for(int column = 0; column < 3; column++)
board[row][column] = '-';
}
public String toString(){
String result = "\n";
for(int row = 0; row <3; row++){
for (int column = 0; column < 3; column++)
result += board[row][column] + " ";
result +="\n";
}
return result;
}
public boolean placeXor0(char player, int row, int column){
if(board[row -1][column -1]=='-'){
board[row-1][column-1]= player;
return true;
}
else
return false;
}
public boolean checkWinner(){
return(checkRowsForWin()||checkColumnsForWin()||checkDiagnalsForWin());
}
public boolean full(){
boolean full = true;
for(int row = 0; row < 3; row++){
for(int column = 0; column < 3; column++){
if(board[row][column] == '-'){
full = false;
}
}
}
return full;
}
public boolean checkRowsForWin(){
for(int row = 0; row < 3; row++){
if(placeXor0(board[row][0], board[row][1], board[row][2]) == true){
return true;
}
}
return false;
}
public boolean checkColumnsForWin(){
for(int column = 0; column < 3; column++){
if(placeXor0(board[0][column], board[1][column], board[2][column]) == true){
return true;
}
}
return false;
}
public boolean checkDiagnalsForWin(){
return((placeXor0(board[0][0], board[1][1], board[2][2]) == true) || (placeXor0(board[0][2], board[1][1], board[2][0]) == true));
}
}
New Code:
public class TTTBoard{
private char[][] board;
public TTTBoard(){
board = new char[3][3];
reset();
}
public void reset(){
for(int row = 0; row < 3; row++)
for(int column = 0; column < 3; column++)
board[row][column] = '-';
}
public String toString(){
String result = "\n";
for(int row = 0; row <3; row++){
for (int column = 0; column < 3; column++)
result += board[row][column] + " ";
result +="\n";
}
return result;
}
public boolean placeXor0(char player, int row, int column){
if(board[row -1][column -1]=='-'){
board[row-1][column-1]= player;
return true;
}
else
return false;
}
public boolean checkWinner(){
return(checkRowsForWin()||checkColumnsForWin()||checkDiagnalsForWin());
}
/*public String getWinner(){
for(int row = 0; row <3; row++){
for (int column = 0; column < 3; column++)
}
}*/
public boolean full(){
boolean full = true;
for(int row = 0; row < 3; row++){
for(int column = 0; column < 3; column++){
if(board[row][column] == '-'){
full = false;
}
}
}
return full;
}
public boolean checkRowsForWin(){
for(int row = 0; row < 3; row++){
if(board[row][0]== board[row][1]&& board[row][0]== board[row][2]){
return true;
}
}
return false;
}
public boolean checkColumnsForWin(){
for(int column = 0; column < 3; column++){
if (board[0][column] == board[1][column] && board[0][column] == board[2][column]) {
return true;
}
}
return false;
}
public boolean checkDiagnalsForWin(){
return((board[0][0]== board[1][1]&& board[0][0] == board[2][2]) || (board[0][2] == board[1][1] && board[0][2]== board[2][0]));
}
}

In checkRowsForWin, you have the lines of code:
if(placeXor0(board[0][column], board[1][column], board[2][column]) == true) {
return true;
}
You want to replace this with:
if (board[0][column] == board[1][column] && board[0][column] == board[2][column]) {
return true;
}
And do a similar thing for checkColumnsForWin and checkDiagnalsForWin

Related

Why does this Java program fail to run properly? Tic-Tac-Toe Game

I am trying to make a tic tac toe game I read about in a Java book. However the code always returns an error and I cannot figure out why. I am relatively new to coding so if the answer is obvious don't rub it in my face :). Also, no errors are displayed in the code in NetBeansIDE so I do not know what is causing the program to fail to run.
import java.util.Scanner;
public class TTT{
private String[][] tttBoard;
private String player1, player2;
public TTT(){
player1 = "X";
player2 = "O";
tttBoard = new String[3][3];
for(int row = 0; row < tttBoard.length; row++){
for(int col = 0; col < tttBoard.length; col++){
tttBoard[row][col] = " ";
}
}
}
public void play(){
String currPlayer = player1;
int movesMade = 0;
do{
displayBoard();
makeMove(currPlayer);
movesMade += 1;
if (currPlayer == player1){
currPlayer = player2;
}
else{
currPlayer = player1;
}
}while (movesMade <= 9 && winner() == " ");
displayBoard();
System.out.println("Winner is "+winner());
}
public void displayBoard(){
for(int row = 0; row < tttBoard.length; row++){
for(int col = 0; col < tttBoard.length; row++){
System.out.println("["+tttBoard[row][col]+"]");
}
System.out.println();
}
}
private void makeMove (String player){
Scanner input = new Scanner(System.in);
boolean validMove = false;
int row, col;
do{
System.out.print("Enter a row number (0, 1, 2): ");
row = input.nextInt();
System.out.print("Enter a column number (0, 1, 2): ");
col = input.nextInt();
if((row >= 0 && row < tttBoard.length && col >= 0 && col <
tttBoard[0].length) && tttBoard[row][col].equals(" ")){
tttBoard[row][col] = player;
validMove = true;
}
else{
System.out.println("Invalid move. Try again.");
}
}while(!validMove);
}
private String winner(){
for(int row = 0; row < tttBoard.length; row++){
if(tttBoard[row][0].equals(tttBoard[row][1]) && tttBoard[row]
[1].equals(tttBoard[row][2]) && !(tttBoard[row][0].equals(" "))){
return(tttBoard[row][0]);
}
}
for(int col = 0; col < tttBoard[0].length; col++){
if (tttBoard[0][col].equals(tttBoard[1][col]) && tttBoard[1]
[col].equals(tttBoard[2][col]) && (!tttBoard[0][col].equals(" "))){
return(tttBoard[0][col]);
}
}
if(tttBoard[0][0].equals(tttBoard[1][1]) && tttBoard[1]
[1].equals(tttBoard[2][2]) && !(tttBoard[0][0].equals(" "))){
return(tttBoard[0][0]);
}
if(tttBoard[0][2].equals(tttBoard[1][1]) && tttBoard[1]
[1].equals(tttBoard[2][0]) && !(tttBoard[0][2].equals(" "))){
return(tttBoard[0][2]);
}
return(" ");
}
}
The file that calls and runs it is as follows:
public class TicTacToe{
public static void main (String args[]){
TTT TTTGame = new TTT();
TTTGame.play();
}
}
Your displayBoard function is wrong. Notice the line:
for(int col = 0; col < tttBoard[row].length; col++)
You need to get the current row tttBoard[row] length. Another error that you made, is that you are incrementing the row instead of the col variable on the second for.
public void displayBoard(){
for(int row = 0; row < tttBoard.length; row++){
for(int col = 0; col < tttBoard[row].length; col++){
System.out.println("["+tttBoard[row][col]+"]");
}
System.out.println();
}
}

Tic Tac Toe / Java

I've done my first aplication - Tic Tac Toe. I want to add a new function - display a winner (player X or O). How Can I do it?
public class Test extends JFrame {
int counter = 0;
public Test(){
setSize(800,800);
setTitle("Kółko i krzyżyk");
setVisible(true);
setLayout(new GridLayout(3,3));
for (int i = 1; i <= 9; i++){
JButton button = new JButton ("");
add (button);
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (counter % 2 ==0){
button.setText("X");
System.out.println("X");
} else{
button.setText("O");
System.out.println("O");
}
button.setEnabled(false);
counter++;
}
});
}
}
1.Player Class :
import java.util.Scanner;
public class Player {
private String name;
private MarkType mark;
private int row, col;
Scanner sc = new Scanner(System.in);
public Player(String name, MarkType mark) {
this.mark = mark;
this.name = name;
}
public String getName() {
return name;
}
public MarkType getMark() {
return mark;
}
public void nextMove() {
System.out.println(this.getName() + " enter position for " + this.getMark());
row = sc.nextInt();
col = sc.nextInt();
}
public int getRow() {
return row - 1;
}
public int getCol() {
return col - 1;
}
}
2.Board Class :
public class Board {
private MarkType board[][];
private int bsize;
public Board(int bsize) {
this.bsize = bsize;
board = new MarkType[bsize][bsize];
}
public int getBoardSize() {
return bsize;
}
public void updateBoard(int row, int col, MarkType mark) {
if (row > bsize || col > bsize) {
throw new ArrayIndexOutOfBoundsException();
} else if (board[row][col] == MarkType.$) {
board[row][col] = mark;
} else {
throw new InvalidPosition("Enter valid position");
}
}
public void initialize() {
for (int row = 0; row < bsize; row++)
for (int col = 0; col < bsize; col++)
board[row][col] = MarkType.$;
}
public boolean isWinner(int passedRow, int passedCol, MarkType mark) {
for (int col = 0; col < bsize; col++) {
if (board[passedRow][col] != mark)
break;
if (col == bsize - 1) {
return true;
}
}
for (int row = 0; row < bsize; row++) {
if (board[row][passedCol] != mark)
break;
if (row == bsize - 1) {
return true;
}
}
if (passedRow == passedCol) {
for (int row = 0; row < bsize; row++) {
if (board[row][row] != mark)
break;
if (row == bsize - 1) {
return true;
}
}
}
if (passedRow + passedCol == bsize - 1) {
for (int index = 0; index < bsize; index++) {
if (board[index][(bsize - 1) - index] != mark)
break;
if (index == bsize - 1) {
return true;
}
}
}
return false;
}
public void display() {
for (int row = 0; row < bsize; row++) {
for (int col = 0; col < bsize; col++) {
System.out.print(" " + board[row][col] + " ");
if (col != bsize - 1) {
System.out.print("|");
}
}
System.out.println();
if (row != bsize - 1) {
for (int col = 0; col < bsize; col++)
System.out.print("--- ");
}
System.out.println();
}
}
}
for complete answer follow the link below:
http://programmersthing.blogspot.in/2017/06/simple-game-in-java.html

Generating an unique Sudoku

I am making a Sudoku game in Java and I need some help.
I've got two classes for generating the Sudoku puzzle: SudokuSolver, SudokuGenerator`.
The SudokuSolver creates a full valid Sudoku puzzle for an empty table and the SudokuGenerator removes a random value from the table and then checks (using SudokuSolver) if the Sudoku puzzle is unique.
I found out that the Sudoku puzzle isn't unique, so I think my algorithm for checking the uniqueness of the Sudoku puzzle is bad.
For example, I have this Sudoku puzzle
497816532
132000000
000000000
910600080
086009000
000084963
021063059
743050020
600278304
And this solution:
497816532
132**745**698
568392471
914**637**285
386529147
275184963
821463759
743951826
659278314
I went to https://www.sudoku-solutions.com/ and I added the pattern of my Sudoku and they gave me another solution:
497816532
132**547**698
568392471
914**635**287
386729145
275184963
821463759
743951826
659278314
The funny think is that they're saying that This puzzle is valid and has a unique solution.
Some opinions?
SudokuSolver
public class SudokuSolver {
public static final int GRID_SIZE = 9;
public static final int SUBGRID_SIZE = 3;
private static int validRow = 0;
private static int validCol = 0;
private int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
public boolean solveSudoku(int[][] values, int forbiddenNum) {
if(!findUnassignedLocation(values)) return true;
//suffle the nums array - for having a different valid sudoku
shuffleNums();
for (int i = 0; i < GRID_SIZE; i++) {
int num = nums[i];
if(num == forbiddenNum) continue; //
if(isSafe(values,validRow, validCol, num)) {
values[validRow][validCol] = num;
if(solveSudoku(values, forbiddenNum)) return true;
if(validCol == 0) {
validRow--;
validCol = 8;
}else{
validCol--;
}
values[validRow][validCol] = 0;
}
}
return false;
}
public boolean createValidSudoku(int[][] values) {
if(!findUnassignedLocation(values)) return true;
shuffleNums();
for (int i = 0; i < GRID_SIZE; i++) {
int num = nums[i];
if(isSafe(values,validRow, validCol, num)) {
values[validRow][validCol] = num;
if(createValidSudoku(values)) return true;
if(validCol == 0) {
validRow--;
validCol = 8;
}else{
validCol--;
}
values[validRow][validCol] = 0;
}
}
return false;
}
private void shuffleNums() {
Random random = new Random();
for(int i = nums.length - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
int a = nums[index];
nums[index] = nums[i];
nums[i] = a;
}
}
private boolean findUnassignedLocation(int[][] values) {
for(int row = 0; row < GRID_SIZE; row++) {
for(int col = 0; col < GRID_SIZE; col++) {
if (values[row][col] == 0) {
validRow = row;
validCol = col;
return true;
}
}
}
return false;
}
private boolean usedInRow(int[][] values, int row, int num) {
for (int col = 0; col < GRID_SIZE; col++) {
if(values[row][col] == num) return true;
}
return false;
}
private boolean usedInCol(int[][] values, int col, int num) {
for (int row = 0; row < GRID_SIZE; row++) {
if(values[row][col] == num) return true;
}
return false;
}
private boolean usedInBox(int[][] values, int boxStartRow, int boxStartCol, int num) {
for(int row = 0; row < SUBGRID_SIZE; row++) {
for (int col = 0; col < SUBGRID_SIZE; col++) {
if (values[row + boxStartRow][col + boxStartCol] == num) return true;
}
}
return false;
}
private boolean isSafe(int[][] values,int row, int col, int num) {
return !usedInRow(values, row, num) &&
!usedInCol(values, col, num) &&
!usedInBox(values, row - row % 3, col - col % 3, num);
}
public void printGrid(int[][] values) {
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
System.out.print(values[row][col]);
}
System.out.println();
}
}
}
SudokuGenerator
public class SudokuGenerator {
private int[][] generatorValues = new int[9][9];
public void generateSudoku() {
SudokuSolver sudokuSolver = new SudokuSolver();
//generate a random valid sudoku for an empty table
sudokuSolver.createValidSudoku(generatorValues);
int count = 0;
printNums(generatorValues);
while(count < 40){
Random random = new Random();
int row = 0;
int col = 0;
if(count < 15){
row = random.nextInt(3);
col = random.nextInt(9);
} else if (count >= 15 && count < 30) {
row = random.nextInt(3) + 3;
col = random.nextInt(9);
}else {
row = random.nextInt(3) + 6;
col = random.nextInt(9);
}
int num = generatorValues[row][col];
int tempValues[][] = Arrays.copyOf(generatorValues, generatorValues.length);
//System.out.println("Row:" + row + "Col: " + col + "Num: " + num);
//Set the cell to 0;
if(generatorValues[row][col] != 0){
generatorValues[row][col] = 0;
} else{
continue;
}
//If found a solution, set cell back to original num
if(sudokuSolver.solveSudoku(tempValues, num)) {
generatorValues[row][col] = num;
continue;
}
count++;
}
System.out.println("------------------");
printNums(generatorValues);
}
private void printNums(int[][] values) {
for (int row = 0; row < 9; row++) {
for(int col = 0; col < 9; col++) {
System.out.print(values[row][col]);
}
System.out.println();
}
}
public int[][] getGeneratorValues () {
return generatorValues;
}
}

TicTacToe Problems

I am stuck on my tictactoe problem. Define a calss called TicTacToe. An object of type TicTacToe is a single game of TicTacToe. Store the game board as a single 2d array of base type char that has three rows and three columns. Include methods to add a move, display the board, to tell whose turn it is, to tell whether there is a winnner, to say who the winner is, and to restart the game to the beginning. Write a main method for the class that will allow two players to enter their moves in turn at the same keyboard.
I have some of my methods written and have been testing as I go. When I test my code I either get it to place a mark but also print out invalid entry or it will continuously loop through asking for a move and then saying the space is occupied. I can't figure out how to fix that. I'm sure it has something to do with my do while loop and the boolean methods for isEmpty and notValid. Also I'm stuck on how to implement a counter for each player's win.
Here is my code:
public void addMove()
{
checkTurn();
int row, col;
do
{
System.out.println("Enter a row (1-3): ");
row = in.nextInt() - 1; //Array index starts at 0.
System.out.println("Enter a column (1-3): ");
col = in.nextInt() - 1;
if (row>=0 && row<ROWS)
if(col>=0 && col<COLUMNS)
if (playerX)
{
gameBoard[row][col] = player1Move;
}
else
{
gameBoard[row][col] = player2Move;
}
checkForWin();
changePlayer();
}while (notValid(row,col));
System.out.println("Invaild Entry.");
//System.exit(0);
//checkForWin();
//changePlayer();
}
public boolean notValid(int row, int col)
{
if (row < 0 || row > ROWS )
return true;
if (col < 0 || col > COLUMNS)
return true;
if (!isEmpty(row,col))
return true;
return false;
}
public boolean isEmpty(int row, int col)
{
if(gameBoard[row][col]==' ')
return true;
else
{
System.out.println("Space is already occupied.");
return false;
}
}
}
Here is my testing class:
public class TicTacToe
{
public static void main(String[] args)
{
TicTacToeClass game = new TicTacToeClass();
game.addMove();
game.printBoard();
}
}
I will let you handle the multiple game part. This plays one game and exits.
import java.util.Scanner;
public class TicTacToe
{
private final static int ROWS = 3;
private final static int COLUMNS = 3;
private char[][] gameBoard;
private int player1WinCount = 0;
private int player2WinCount = 0;
private char player1Move = 'X', player2Move = 'O';
private boolean playerX = true;
Scanner in = new Scanner(System.in);
public TicTacToe()
{
gameBoard = new char [ROWS][COLUMNS];
playerX = true;
startGame();
}
//Initiate the game board with all empty spaces.
public void startGame()
{
for (int row = 0; row < ROWS; row++) //Loop through rows.
for(int col = 0; col < COLUMNS; col++) //Loop through columns.
gameBoard[row][col]= ' ';
}
public boolean checkTurn()
{
if (playerX)
{
System.out.println("Player X's turn.");
}
else
{
System.out.println("Player O's turn.");
}
return playerX;
}
public void addMove()
{
int row, col;
do
{
checkTurn();
System.out.println("Enter a row (1-3): ");
row = in.nextInt() - 1; //Array index starts at 0.
System.out.println("Enter a column (1-3): ");
col = in.nextInt() - 1;
if(notValid(row,col)){
// do not proceed
System.out.println("Invalid Entry.");
continue;
}
if (row>=0 && row<ROWS)
if(col>=0 && col<COLUMNS)
if (playerX)
{
gameBoard[row][col] = player1Move;
}
else
{
gameBoard[row][col] = player2Move;
}
boolean hasWon = checkForWin();
if(hasWon)
{
System.out.println("You won");
if(playerX)
{
player1WinCount++;
}
else
{
player2WinCount++;
}
break;
}
changePlayer();
}while (true);
}
public boolean notValid(int row, int col)
{
if (row < 0 || row > (ROWS - 1))
return true;
if (col < 0 || col > (COLUMNS - 1))
return true;
if (!isEmpty(row,col))
return true;
return false;
}
public boolean isEmpty(int row, int col)
{
if(gameBoard[row][col]==' ')
return true;
else
{
System.out.println("Space is already occupied.");
return false;
}
}
public void changePlayer()
{
if (playerX)
{
playerX = false;
}
else
{
playerX = true;
}
}
public void printBoard()
{
for (int row = 0; row < ROWS; row++){
for (int col = 0; col < COLUMNS; col++)
{
System.out.print("" + gameBoard[row][col]);
if(col == 0 || col == 1)
System.out.print("|");
}
if (row ==0 || row ==1)
System.out.print("\n-----\n");
}
}
/**
* This method checks to see if a winner.
* return true is there is a winner.
*/
public boolean checkForWin()
{
//checks rows for win
for(int row = 0; row < ROWS; row ++)
{
if (gameBoard[row][0] == gameBoard[row][1] && gameBoard[row][1]==gameBoard[row][2] && gameBoard[row][0]!= ' ')
return true;
}
//checks columns for wins.
for (int col = 0; col < COLUMNS; col++)
{
if (gameBoard[0][col] == gameBoard[1][col]&& gameBoard[1][col]==gameBoard[2][col] && gameBoard[0][col]!= ' ')
return true;
}
//check the diagonals for wins.
if (gameBoard[0][0] == gameBoard[1][1] && gameBoard[1][1] == gameBoard[2][2] && gameBoard[0][0]!= ' ')
return true;
if (gameBoard[2][0] == gameBoard[1][1] && gameBoard[1][1] == gameBoard[0][2] && gameBoard[0][2]!= ' ')
return true;
return false;
}
public static void main(String args[])
{
TicTacToe game = new TicTacToe();
game.addMove();
game.printBoard();
}
}

assistance with tic tac toe assignment

I can't get the game to call it a draw or win diagonally, I'm almost done but I can't figure it out. I've tried everything. I can win the game in straight lines but diagonally doesn't seem to finish in the loop. And I'm not sure if it ever reaches the loop for the full board or completes it even though it should.
import java.util.Scanner; //Used for player's input in game
public class TicTacToe
{
//instance variables
private char[][] board; //Tic Tac Toe Board, 2d array
private boolean xTurn; // true when X's turn, false if O's turn
private Scanner input; // Scanner for reading input from keyboard
//Constants for creation of gameboard
public final int ROWS = 3; //total rows
public final int COLS = 3; //total columns
public final int WIN = 3; //amount needed to win
public TicTacToe()
{
//creates the board
board = new char[ROWS][COLS];
for(int r = 0; r < ROWS; r++)
{
for(int c = 0; c < COLS; c++)
{
board[r][c] = ' ';
}
}
//X's turn when game starts
xTurn = true;
//creates our input object for the turn player
input = new Scanner(System.in);
}
//shows game board
public void displayBoard()
{
int colNum = 0; //number of columns
int rowNum = 0; //number of rows
//creates column labels
System.out.println(" \n");
System.out.println(" Columns ");
for (int num = 0; num < COLS; num++)
{
System.out.print(" " + colNum);
colNum++;
}
//creates vertical columns and spaces between each spot
System.out.println(" \n");
for (int row = 0; row < ROWS; row++)
{
//numbers rows
System.out.print(" " + rowNum + " ");
rowNum++;
for (int col = 0; col < COLS; ++col)
{
System.out.print(board[row][col]); // print each of the cells
if (col != COLS - 1)
{
System.out.print(" | "); // print vertical partition
}
}
System.out.println();
//creates seperation of rows
if (row != ROWS - 1)
{
System.out.println(" ------------"); // print horizontal partition
}
}
//labels row
System.out.println("Rows \n");
}
//displays turn player
public void displayTurn()
{
if (xTurn)
{
System.out.println("X's Turn");
}
else
{
System.out.println("O's Turn");
}
}
//allows you to make move
public boolean playerMove()
{
boolean invalid = true;
int row = 0;
int column = 0;
while(invalid)
{
System.out.println("Which row (first) then column (second) would you like to \n"
+ "play this turn? Enter 2 numbers between 0-2 as \n"
+ "displayed on the board, seperated by a space to \n"
+ "choose your position.");
if (input.hasNextInt())
{
row = input.nextInt();
if (row > ROWS - 1|| row < 0)
{
System.out.println("Invalid position");
playerMove();
}
else if (row >= 0 && row <= ROWS - 1 && column >= 0 && column <= COLS - 1)
{
if (board[row][column] != ' ')
{
System.out.println("Spot is taken \n");
}
else
{
invalid = false;
}
}
if(input.hasNextInt())
{
column = input.nextInt();
if (column > COLS - 1|| column < 0)
{
System.out.println("Invalid position");
playerMove();
}
//checks if spot is filled
else if (row >= 0 && row <= ROWS - 1 && column >= 0 && column <= COLS - 1)
{
if (board[row][column] != ' ')
{
System.out.println("Spot is taken \n");
}
else
{
invalid = false;
}
}
}
}
//fills spot if not taken
if (xTurn)
{
board[row][column] = 'X';
}
else
{
board[row][column] = 'O';
}
}
return displayWinner(row,column);
}
public boolean displayWinner(int lastR, int lastC)
{
boolean winner = false;
int letter = board[lastR][lastC];
//checks row for win
int spotsFilled = 0;
for (int c = 0; c < COLS; c++)
{
if(board[lastR][c] == letter)
{
spotsFilled++;
}
}
if (spotsFilled == WIN)
{
winner = true;
}
//checks columns for win
spotsFilled = 0;
for (int r = 0; r < ROWS; r++)
{
if(board[r][lastC] == letter)
{
spotsFilled++;
}
}
if (spotsFilled == WIN)
{
winner = true;
}
//checks diagonals for win
spotsFilled = 0;
for (int i = 0; i < WIN; i++)
{
if(board[i][i] == letter)
{
spotsFilled++;
}
}
if(spotsFilled == WIN)
{
winner = true;
}
//checks other diagonal
spotsFilled = 0;
for(int i = 0; i < WIN; i++)
{
if(board[i][COLS - ( i + 1)] == letter)
{
spotsFilled++;
}
}
if(spotsFilled == WIN)
{
winner = true;
}
return winner;
}
//checks if board is full
public boolean fullBoard()
{
int filledSpots = 0;
for(int r = 0; r < ROWS; r++)
{
for (int c = 0; c < COLS; c++)
{
if (board[r][c] == 'X' || board[r][c] == 'O')
{
filledSpots++;
}
}
}
return filledSpots == ROWS*COLS;
}
//plays game
public void playGame()
{
boolean finish = true;
System.out.println("Are your ready to start?");
System.out.println("1 for Yes or 0 for No? : ");
if (input.hasNextInt())
{
int choice = input.nextInt();
if(choice > 1 || choice < 0)
{
System.out.println("Invalid choice");
playGame();
}
else if (choice == 1)
{
while (finish)
{
displayBoard();
displayTurn();
if (playerMove())
{
displayBoard();
if (xTurn)
{
System.out.println("X won");
displayBoard();
}
else
{
System.out.println("O won");
displayBoard();
}
}
else if (fullBoard())
{
displayBoard();
System.out.println("Draw");
}
else
{
//no winner, switching turns
xTurn=!xTurn;
}
}
}
}
else
{
System.out.println("Input not valid");
}
}
}
and the tester
public class TicTacToeTester {
/**
* #param
* args the command line arguments
*/
public static void main(String[] args) {
TicTacToe tictactoe = new TicTacToe();
tictactoe.playGame();
}
}

Categories

Resources