TicTacToe Problems - java

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();
}
}

Related

How do you move through a 2D array without for loops?

I am trying to build a treasure hunt game using test files I have been given. These texts files are of chars S,W,E,N and T which all correspond to directions except for T, which is the treasure. Everything works fine until it moves the length of the rows/columns. I suspect it has something to do with the for loops but I'm not certain. Is there a way to do this without for loops or does anyone have any advice to get this back on track?
Here is my Updated code so far:
import java.util.*;
public class NewGridGame {
public static final int FALL_OFF = -1;
public static final int GOING_IN_CIRCLES = -2;
private int row;
private int col;
private char[][] gameBoard;
NewGridGame(int conRow, int conCol, char[][] conGameBoard) {
row = conRow;
col = conCol;
gameBoard = new char[row][col];
for (int i = 0; i < gameBoard.length; i++) {
for (int j = 0; j < gameBoard[i].length; j++) {
gameBoard[i][j] = conGameBoard[i][j];
}
}
System.out.println(Arrays.deepToString(gameBoard));
}
public int playGame() {
boolean[][] beenHereBefore = new boolean[row][col];
int turns = 0;
int i = 0;
int j = 0;
while (true) {
if (beenHereBefore[i][j] == true) {
return GOING_IN_CIRCLES;
} else {
beenHereBefore[i][j] = true;
}
if (gameBoard[i][j] == 'N') {
if (i - 1 >= 0) {
i--;
turns++;
System.out.println(turns);
System.out.println(gameBoard[i][j]);
} else {
return FALL_OFF;
}
} else if (gameBoard[i][j] == 'S') {
if (i + 1 < row) {
i++;
turns++;
System.out.println(turns);
System.out.println(gameBoard[i][j]);
} else {
return FALL_OFF;
}
} else if (gameBoard[i][j] == 'E') {
if (j + 1 < col) {
j++;
turns++;
System.out.println(turns);
System.out.println(gameBoard[i][j]);
} else {
return FALL_OFF;
}
} else if (gameBoard[i][j] == 'W') {
if (j - 1 >= 0) {
j--;
turns++;
System.out.println(turns);
System.out.println(gameBoard[i][j]);
} else {
return FALL_OFF;
}
} else if (gameBoard[i][j] == 'T') {
return turns;
}
}
}
}
Here is an example of a test file as well.
ES
TW
this one should return 3, which is the number of moves (turns, in my code) but instead it gets to W (which takes 2 moves) and returns -2, which is only for when it's gone to a position more than once. Additionally, not all of the Arrays are squares, some are 1x200 or 4x5 for examples.
If you know that the board is such that, starting at (0, 0), you won't get stuck in a loop or move off the board you can just used something like this:
public int playGame()
{
int numMoves = 0;
int currentRow = 0;
int currentCol = 0;
while(gameBoard[currentRow][currentCol] != 'T')
{
switch (gameBoard[currentRow][currentCol])
{
case 'E': currentCol++; break;
case 'W': currentCol--; break;
case 'S': currentRow--; break;
case 'N': currentRow++; break;
default:
throw new IllegalStateException("Unrecognized Move");
}
numMoves++;
}
return numMoves;
}
You may want to use if-then-else instead of a switch.
If you need to check for loops or off-board moves you should be able to add these checks in.

Program doesn't work and results in an Array Out of Bounds

My checkTie method in my TicTacToe program doesn't work and results in an out of bounds array and I can't see why.
Running this code will print the board and allow the game to run until either someone wins, or there are 3 _'s left and then it will end the game.
I'm not sure why that happens though, I believe it has something to do with my checkTie for loop. Also, if a tie was to occur either nothing happens or an Array out of bounds happens.
import java.util.Scanner;
public class TicTac {
public static int row, col;
public static Scanner scan = new Scanner(System.in);
public static char[][] board = new char[3][3];
public static char turn = 'X';
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '_';
}
}
Play();
}
public static boolean Play() {
boolean playing = true;
PrintBoard();
while (playing) {
System.out.println();
System.out.print("Please enter row: ");
row = scan.nextInt() - 1;
System.out.print("Please enter column: ");
col = scan.nextInt() - 1;
board[row][col] = turn;
if (GameOver(row, col)) {
playing = false;
System.out.println("Game Over! Player " + turn + " wins!");
**I feel like this code below is where the problem is**
if (checkTie(board)) {
System.out.println("Tie Game!");
return true;
}
}
PrintBoard();
if (turn == 'X')
turn = '0';
else
turn = 'X';
}
return false;
}
public static void PrintBoard() {
for (int i = 0; i < 3; i++) {
System.out.println();
for (int j = 0; j < 3; j++) {
if (j == 0)
System.out.print("| ");
System.out.print(board[i][j] + " | ");
}
}
System.out.println();
}
public static boolean GameOver(int rMove, int cMove) {
// Check if perpendicular victory
if (board[0][cMove] == board[1][cMove] && board[0][cMove] == board[2][cMove])
return true;
if (board[rMove][0] == board[rMove][1] && board[rMove][0] == board[rMove][2])
return true;
// Check Diagonal Victory
if (board[0][2] == board[1][1] && board[0][0] == board[2][2] && board[1][1] != '_')
return true;
if (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[1][1] != '_')
return true;
return false;
}
This is where the method to see if the game result is a tie.
public static boolean checkTie(char[][] board) {
int spacesLeft = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == '_') {
spacesLeft++;
}
}
}
if (spacesLeft == 0) {
return true;
} else {
return false;
}
}
}
I think you meant to do checkTie when gameOver returns false'. As things stand,checkTieis only ever called aftergameOver' has returned `true'.

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();
}
}

Java Tic Tac Toe Game Confirming Winner

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

Java Tic-Tac-Toe, prints 3 boards

I'm having a setback in the code for a Tic Tac Toe Java program. Every time I run it, the game board prints 3 times and o the second time, the X's all fill in a line saying that player X wins. I've been trying to figure it out, but I still can't find the problem going on with it. What I'm asking is, what is the main problem of the code printing out more than it needs to and to stop filling in the lines?
I hope I format this correctly.
import java.util.Scanner;
public class TicTacToeWork {
//Variable declaration.
public static char[][] GameBoard = new char[3][3];
public static Scanner keyboard = new Scanner(System.in);
public static int column, row;
public static char PlayerTurn = 'X';
public static void main(String args[]) {
for (int i = 0; i > 3; i++) {
for (int j = 0; j < 3; j++) {
GameBoard[i][j] = '_';
}
}
System.out.println("Enter coordinates of row then column to choose your space.");
Playing();
}
public static void Playing() {
boolean PlayerPlaying = true;
while (PlayerPlaying) {
boolean playing = true;
while (playing) {
row = keyboard.nextInt() - 1;
column = keyboard.nextInt() - 1;
GameBoard[row][column] = PlayerTurn;
if (EndGame(row, column)) {
playing = false;
System.out.println("Game over player " + PlayerTurn + " wins!");
}
BoardPrint();
if (PlayerTurn == 'X') {
PlayerTurn = 'O';
} else {
PlayerTurn = 'X';
}
}
}
}
public static void BoardPrint() {
//Print out the game board.
for (int i = 0; i < GameBoard.length; i++) {
for (int n = 0; n < 3; n++) {
System.out.println();
for (int j = 0; j < 3; j++) {
if (j == 0) {
System.out.print("| ");
}
System.out.print(GameBoard[i][j] + " | ");
}
}
System.out.println();
}
System.out.println();
}
public static boolean EndGame(int RowMove, int ColumnMove) {
//Deciding factors on who wins and ties.
if (GameBoard[0][ColumnMove] == GameBoard[1][ColumnMove]
&& GameBoard[1][ColumnMove] == GameBoard[2][ColumnMove]) {
return true;
}
if (GameBoard[RowMove][0] == GameBoard[1][RowMove]
&& GameBoard[RowMove][0] == GameBoard[RowMove][2]) {
return true;
}
if (GameBoard[0][0] == GameBoard[1][1] && GameBoard[0][0] == GameBoard[2][2]
&& GameBoard[1][1] != '_') {
return true;
}
if (GameBoard[0][2] == GameBoard[1][1] && GameBoard[0][2] == GameBoard[2][0]
&& GameBoard[1][1] != '_') {
return true;
} else {
return false;
}
}
}
Your BoardPrint method is all wrong. You have to do something like this..
public static void BoardPrint() {
System.out.println("-------------");
for (int i = 0; i < 3; i++) {
System.out.print("| ");
for (int j = 0; j < 3; j++) {
System.out.print(GameBoard[i][j] + " | ");
}
System.out.println();
System.out.println("-------------");
}
You are also going to have to redo your check for a win.
A little hint.. you are not using a Boolean method correctly. This line if(EndGame(row, column)) is saying if EndGame is true stop the game. The way you have your method set up it is not doing the check correctly. You would have to say "if not true" - so it would look like this if(!EndGame(row, column)) There are a couple of other errors but this should give you a good start on completing the project.

Categories

Resources