Tic-Tac-Toe display not displaying correctly - java

So I have created a simple tic-tac-toe console program. But for some reason my methods aren't displaying the board correctly.
The display of the code prints out like this:
Tic-Tac-Toe
------------
Player 'X', enter move (row [1-3] column [1-3]): 2
2
|
|
-----------
|
X
|
-----------
|
|
Player 'O', enter move (row [1-3] column [1-3]):
The code:
/**
* The grid represents the game board
*/
public class Grid {
int ROWS = 3; // Defines the amount of rows
int COLUMNS =3; // Defines the amount of columns
Box[][] board; // Represents the game board as a grid
int currentrow, currentcol; // Row and Column that was played last
public Grid()
{
board = new Box[ROWS][COLUMNS]; // Constructor initializes the game board
for(int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLUMNS; col++) {
board[row][col] = new Box(row,col);
}
}
}
public void init()
{
for (int row = 0; row < ROWS; row++) { // Re-initializes the game board
for (int col = 0; col < COLUMNS; col++) {
board[row][col].clear();
}
}
}
public boolean isDraw()
{
for (int row = 0; row < ROWS; row++) { // Returns true if the game is a draw (no more empty boxes)
for (int col = 0; col < COLUMNS; col++) {
if (board[row][col].content == Player.EMPTY) {
return false; // An empty box found, not a draw, exits
}
}
}
return true; // No empty boxes return true is then a draw
}
public boolean hasWon(Player thePlayer) {
return (board [currentrow] [0] .content == thePlayer && board [currentrow] [1].content == thePlayer && board [currentrow] [2].content == thePlayer // 3 in a row
|| board [0] [currentcol].content == thePlayer && board [1] [currentcol].content == thePlayer && board [2] [currentcol].content == thePlayer // 3 in a column
|| currentrow == currentcol
&& board[0] [0].content == thePlayer // 3 in a diagonal
&& board[1] [1].content == thePlayer
&& board[2] [2].content == thePlayer
|| currentrow + currentcol == 2
&& board[0][2].content == thePlayer // 3 in the opposite diagonal
&& board[1][1].content == thePlayer
&& board[2][0].content == thePlayer);
}
public void paint()
{
for (int row = 0; row < ROWS; row++) { // Paints (displays) the full board
for (int col = 0; col < COLUMNS; col++) {
board[row][col].paint();
if (col < COLUMNS - 1)
System.out.println("|");
}
System.out.println();
if (row < ROWS - 1) {
System.out.println("-----------");
}
}
}
}
I want the code to print out the display in the correct way. I think there must be a simple mistake I have made either in the paint() method or when I initialized the grid. Please can someone see where I have gone wrong.

You need to modify your painting methods.
for (int row = 0; row < ROWS; row++) { // Paints (displays) the full board
for (int col = 0; col < COLUMNS; col++) {
board[row][col].paint();
if (col < COLUMNS - 1)
System.out.print("|");
}
System.out.println();
if (row < ROWS - 1) {
System.out.println("-----------");
}
}
First, you need to use println only when needed, the rest of the time just use print.
And the same is for Box.paint not visible here. But it seems to be using System.out.println instead of System.out.print.
Another thing, Box.paint should return a String instead of sending message in the console. The board is responsible of the painting, not the box.
public String paint(){
return content; //return a `String` " ", "X" or "O"
}
Tested with :
public static void main(String[] args) throws ParseException {
print(new String[][]{
{"X", " ", "O"},
{" ", " ", " "},
{"O", " ", "X"}
});
}
private static void print(String[][] board){
int ROWS = board.length;
int COLUMNS = board[0].length;
for (int row = 0; row < ROWS; row++) { // Paints (displays) the full board
for (int col = 0; col < COLUMNS; col++) {
System.out.print(board[row][col]);
if (col < COLUMNS - 1)
System.out.print("|");
}
System.out.println();
if (row < ROWS - 1) {
System.out.println("-----");
}
}
}
Giving :
X| |O
-----
| |
-----
O| |X

It's hard to give you the answer with 100% certainty if you don't post all of the code. Can you add the implementation of Box and the main method?
The problem seems to be that you are doing System.out.println("|"); when you should be doing System.out.print("|");. System.out.println("|"); will also a new line causing the next thing printed to occur on the next line. You are already handling the newline for the end of the row correctly (the System.out.println(); so System.out.print("|"); should be all you need to do.
Working example with the fix: https://repl.it/repls/DimgreyOutlandishFlashdrive

Related

Method is not visible to print details on Snakes and Ladders Game

public class CA {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] numbersOnBoard = new int[6][6];
boardSetUpA(numbersOnBoard);
printTwoD(numbersOnBoard);
String[][] details = new String[6][6];
boardDetails(details);
}
public static void boardSetUpA(int[][] twoD) {
// Square with even size
// even rows
for (int row = 0; row < twoD.length; row++) {
if (row % 2 == 0) {
int num = twoD.length * (twoD.length - row);
for (int col = 0; col < twoD[row].length; col++) {
twoD[row][col] = num;
num--;
}
} //
else {
int num = twoD.length * (twoD.length - (row + 1)) + 1;
for (int col = 0; col < twoD[row].length; col++) {
twoD[row][col] = num;
num++;
}
}
} // for row
} //
public static void printTwoD(int[][] array) {
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
System.out.print(array[row][column] + "\t");
}
System.out.println();
}
}
public static void boardDetails(String[][] board) {
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
if (col + 2 == row || col + 1 == row * 2) {
board[row][col] = "Lad"; // Append value
} else if (col * 2 == row || row * 2 == col) {
board[row][col] = "Cht"; // Append value
} else {
board[row][col] = " ";
}
}
board[board.length - 1][0] = "Start";
if (board.length % 2 == 0) {
board[0][0] = "End";
} else {
board[0][board.length - 1] = "End";
}
}
}
public static void printBoard(int[][] twoD, String[][] strTwoD) {
// Printing
for (int row = 0; row < twoD.length; row++) {
for (int col = 0; col < twoD[row].length; col++) {
System.out.print(twoD[row][col] + " " + strTwoD[row][col] + "\t\t");
}
System.out.println("\n");
}
}
}
I am creating a snakes and ladders game board and the game (will be finished later).I am trying to print the chutes/snakes and ladders on the board using the method boardDetails but it is not showing up, only the board from 1-36 is shown. Am I not calling the method? Any help would be appreciated.
Thanks!

2D Array printing on first row

For some reason it prints "*" nine times on one row. Instead of a 3x3 of *.
Should also be noted that the main function simply runs the displayBoard function and would not change the output.
public class TicTacToeTwoPlayer {
static final int SIZE = 3;
/*
Here:
Declare a 2-d character array called board with SIZE rows and SIZE columns.
Be sure to use the static modifier in the declaration
*/
static char[][] board = new char [SIZE][SIZE];
static final char PLAYER1 = 'X';
static final char PLAYER2 = 'O';
static Scanner userInput = new Scanner(System.in);
public static void initializeBoard() {
/*
Here:
Initialize each position of the board array to a space character.
*/
for (int row = 0; row < board.length; row++) {
for(int col = 0; col < board.length; col++) board[row][col] = ' ';
}
}
public static void displayBoard() {
/*
Here:
Complete this method so that it displays the tic-tac-toe board
to the screen. If a board position is available, that is, if it is
a space, output an asterisk followed by a space ("* ".)
*/
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
if (board[row][col] == ' ') {
System.out.print("* ");
} else {
System.out.print(board[row][col]);
}
}
}
System.out.println("Board is: ");
}
}
Any help would be greatly appreciated!
Try printing a newline after each row:
public static void displayBoard() {
for (int row=0; row < board.length; row++) {
for (int col=0; col < board[row].length; col++) {
if (board[row][col] == ' ') {
System.out.print("* ");
}
else {
System.out.print(board[row][col]);
}
}
// print a device-independent newline here after each row
System.out.println();
}
System.out.println("Board is: ");
}

Sudoko grid conversion from 9*9 to all grid size

I have coded for Sudoku puzzle in Java. The thing is my code has limitation for giving inputs for 9*9 grid. How do I make my code adaptable for all the grids. Please have patience. I am new to java.
What changes do I need to make so that the code can run on all grid sizes?The grid is square not a rectangle.
class Solution {
public void solveSudoku(char[][] board) {
if(solveSudoku2(board)) {
return;
}
}
public boolean solveSudoku2(char[][] board) {
boolean isEmpty = true;
int row = -1;
int col = -1;
int n = board.length;
//this code is used to check if there exists any empty cell in sudoku board
//if there is any empty cell, that means we are not done yet and we need to solve it further,
// so we cannot return true at any point until all the cells are full
//by empty cell, I mean cells having '.' as the value
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(board[i][j] == '.') {
row = i;
col = j;
isEmpty = false;
break;
}
}
if(!isEmpty) {
break;
}
}
if(isEmpty) {
return true;
}
//loop for all the numbers and start placing in the empty cells
//numbers start from 1 to n
for(int num = 1; num <= n; num++) {
//convert number to char
char char_num = (char)(num + '0');
//check if the number we are adding satisfies all the sudoku rules,
// if it does, then we place that number in the cell
if(checkSafe(board,char_num,row,col)) {
board[row][col] = (char)(num + '0');
//using this number in place row,col, we check for all the other empty places and see if the board is returning true or not
// if the board is not filled that means that we need to use other number in row,col place.
//hence backtrack.
if(solveSudoku2(board)) {
return true;
} else {
board[row][col] = '.';
}
}
}
return false;
}
public boolean checkSafe(char[][] board, char num, int row, int col) {
//checkk if num is present in the row
for(int i = 0; i< board.length; i++ ) {
if(board[row][i] == num) {
return false;
}
}
for(int j = 0; j < board[0].length; j++) {
if(board[j][col] == num) {
return false;
}
}
int checknum = (int)Math.sqrt(board.length);
//check for the current grid. grid will be basically checknum*checknum matrix. where every matrix will start from startrow to startrow + checknum having checknum length.
// so, we we have row = 0, then matrix will start from 0 to 2, i.e. the first 3x3 matrix.
// however, we have row = 2, then also the matrix will start from 0 to 2 - the first 3x3 matrix.
//however, if row = 3, then we will start our matrix from 3 and cotinute upto 5.
int startrow = row - row % checknum;
int startcol = col - col % checknum;
for(int k = startrow; k < startrow + checknum; k++) {
for(int l = startcol; l < startcol + checknum; l++) {
if(board[k][l] == num) {
return false;
}
}
}
return true;
}
}

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

Having trouble getting a vertical detection of connect 4 win

Right now I have a school assignment where I have to create a connect 4 game in java without a gui using arrays. So far I have been able to get the game to detect a horizontal four in a row but I can't seem to get a vertical four in a row. Originally my array was a 6x7 but I have changed it to a 5x5 just to test the concept of swapping the arrays dementions. Just to make less clutter, I only included the part of the code with the vertical detection.
for (column = 0; column < board.length; column++) {
count_piece = 0;
max = 0;
for (row = 0; row < board.length; row++) {
if (max < count_piece) {
max = count_piece;
}
if (board[column][row] == 'X') {
count_piece++;
} else {
count_piece = 0;
}
}
}
System.out.println(max);
if (max == 4) {
System.out.println("\nYou Win!");
break;
}
If you need more information or if anything is not clear please let me know and i'll be glad to provide some more info.
EDIT:
Here is the one with the inverted loop.
for (row = 0; row < board.length; row++) {
count_piece = 0;
max = 0;
for (column = 0; column < board.length; column++) {
if (max < count_piece) {
max = count_piece;
}
if (board[column][row] == 'X') {
count_piece++;
} else {
count_piece = 0;
}
}
}
How about inverting your loop that way your inner loop changing will be the column instead of the row?
Also make your inner loop take the length of the single array you are in.
So instead of using board.length use something like board[i].length
Edit
I think your logic inside your inner loop is wrong...
Try this:
if (board[row][column] == 'X') {
count_piece++;
if(count_piece == 4) {
System.out.println("you win");
return;
}
} else {
count_piece = 0;
}
Here is both checks Horizontal and Vertical with any size array
int count_piece = 0;
//Checking Vertical Win
for (int row = 0; row < board.length; row++) {
count_piece = 0;
for (int column = 0; column < board[row].length; column++) {
if (board[row][column] == 'X') {
count_piece++;
if (count_piece == 4) {
System.out.println("you win");
return;
}
} else {
count_piece = 0;
}
}
}
//Checking Horizontal Win
for (int column = 0; column < board.length; column++) {
count_piece = 0;
for (int row = 0; row < board[column].length; row++) {
if (board[row][column] == 'X') {
count_piece++;
if (count_piece == 4) {
System.out.println("you win");
return;
}
} else {
count_piece = 0;
}
}
}
The main issue I see is assigning max before incrementing count_piece (meaning you would have to get 5 in a row).
Also as others have said length might have issue (not familiar with java so you might get away with it as length would either be 5 or 25 depending if it takes all indices or just the first columns indices. regardless when you go back to 6x7 it will break.
Also what your code is currently doing is going through each column and checking if the row has 4 in a row. What you want is to check for 4 in a row on both axis (my solution would be to have a row count variable and a column count variable (unless you need diagonal)).
adding
count_piece_Col=0; max=0;
above the first for loop and incrementing it similarly to the row count
*lazy way
for(column=0;column<board.length;column++)
{
count_piece=0; max_r=0;
for(row=0;row<board.length;row++)
{
if(max_r<count_piece)
{
max_r=count_piece;
}
if(board[column][row]=='X')
{
count_piece++;
}
else
{
count_piece=0;
}
}
}
for(row=0;row<board.length;row++)
{
count_piece=0; max_c=0;
for(column=0;column<board.length;column++)
{
if(max_c<count_piece)
{
max_c=count_piece;
}
if(board[column][row]=='X')
{
count_piece++;
}
else
{
count_piece=0;
}
}
}

Categories

Resources