Using a 2D arraylist to create a chessboard and pieces - java

I'm currently trying to create a program that will spit out a chessboard like this one (it looks better in the actual program, just to editor doesn't like me using the "-" symbol so I put them in quotation marks):
-----------------
| | | | |K| | | |
-----------------
| |P| | | |P| | |
-----------------
| | | | | | | | |
-----------------
| | | | | | | | |
-----------------
| | | | | | | | |
-----------------
| | | | | | | | |
-----------------
| | | | | |N| | |
-----------------
| | | | |K| | | |
-----------------
I'm using two methods, a showBoard method and an addPiece method. I'm currently stuck with the addPiece method, and I'm trying to make it so the method takes three inputs: the row int, the column int, and the string name (just K for king, for example). However, I can't get the addPiece method to put the pieces where I want them to go, or even at all. Here's what I have so far:
public class ChessBoard {
public static String[][] board = new String[8][8];
public static int row = 0;
public static int col = 0;
public static void addPiece(int x, int y, String r){
board[x][y] = new String(r);
}
public static void showBoard(){
for (row = 0; row < board.length; row++)
{
System.out.println("");
System.out.println("---------------");
for(col = 0; col < board[row].length; col++)
{
System.out.print("| ");
}
}
System.out.println("");
System.out.println("---------------");
}
public static void main(String[] args) {
System.out.println(board.length);
showBoard();
addPiece(1,2,"R");
}
}
I know it has something to do with the way I wrote my addpiece method, but I'm still kind of confused as to how writing the method should be, and that is my best attempt (which doesn't work). Does anyone have any suggestions? Thanks!

You never print the pieces values
for(col = 0; col < board[row].length; col++)
{
if ( board[row][col] != null ) {
System.out.print("|" + board[row][col]);
}
else
System.out.print("| ");
}
And also you'll need to add the pience before you show the board:
addPiece(1,2,"R"); //before
showBoard();

Why are you using new String(r)? Your board array is already an array of Strings, just use:
board[x][y] = r;
Also you are adding the piece after the showBoard method in main, switch them around
addPiece(1,2,"R");
showBoard();

Note that addPiece is changing the state of the board. If you want to see that change, you need to redisplay the new board state.
public class ChessBoard {
public static String[][] board = new String[8][8];
public static void addPiece(int x, int y, String r){
board[x][y] = r;//no need for new String(), board is already made of Strings.
}
public static void showBoard(){
//it's generally better practice to initialize loop counters in the loop themselves
for (int row = 0; row < board.length; row++)
{
System.out.println("");
System.out.println("---------------");
for(int col = 0; col < board[row].length; col++)
{
System.out.print("|"); //you're only printing spaces in the spots
if(board[column][row] == null){
System.ot.print(" ");
}else{
System.out.print(board[column][row]);
}
}
}
System.out.println("");
System.out.println("---------------");
}
public static void main(String[] args) {
System.out.println(board.length);
showBoard(); //board does not have R in it yet.
addPiece(1,2,"R"); //board now has R in it.
showBoard(); //display the new board with R in it.
}
}

Related

While loop gets terminated before condition is met when backtracking

I'm trying to write an iterative program that will help me palce 4 queens on a 4x4 board without them hitting each other. The problem is after looping through each position and backtracking a couple of times my main while loop that keeps looping until a solution is found gets terminated and the program ends even though the condition is not yet met.
I tried the following code:
static int[] solve(char[][] board){
int[] position = new int[4];
int row = 0;
int column = 0;
while(row < 4){
for(boolean check; column < board.length; column++){
System.out.println("["+row+","+column+"]");
check = true;
for(int queen= 0; queen < row; queen++){
if (position[queen] == column || queen- position[queen] == row - column || queen + position[queen] == row + column) {
check = false;
break;
}
}
if(check){
position[row] = column;
column = 0;
row++;
}
if(column > 2){
column = position[--row];
}
}
}
return position;
}
I'm currently getting the following output:
| Q | X | X | X |
| X | X | X | Q |
| X | Q | X | X |
| Q | X | X | X |
To check when exactly the while loop is getting terminated I printed the location (row and column)
System.out.println("["+row+","+column+"]"); and got the following:
[0,0][1,0][1,1][1,2][2,0][2,1][2,2][2,3][1,3][2,0][2,1][3,0][3,1][3,2][3,3][2,2][2,3]
After backtracking to [2,3] the while loop ends even though my row count is still less than 4.
I was expecting the following output:
| X | Q | X | X |
| X | X | X | Q |
| Q | X | X | X |
| X | X | Q | X |
I tried the code in a different compiler and still got the same wrong output. Is there a logical mistake that I missed out?
I'm new to programming so I'm still trying to get the hang of the fundamentals.

Print 2D array to console in board format

I'm trying to print my 2D array to the console as if the array were co-ordinates on a chess board for example, my code looks like this:
public Piece[][] getBoardView() throws NoBoardDefinedException
{
System.out.println(Arrays.deepToString(board));
return board;
}
This currently prints the 2D array in one straight line across the console, can anyone suggest a way to change this into a board style format?
Try this.
for (Piece[] row : board)
System.out.println(Arrays.toString(row));
if this is the case then you would get likewise,
int chessboard [][] = {
{1,2,3},
{4,5,6},
{7,8,9}
};
for(int i = 0; i < chessboard.length ; i ++){
System.out.println();
for(int j = 0 ; j < chessboard[i].length ; j++){
System.out.print(" | " + chessboard[i][j] );
}
System.out.print(" |");
System.out.println();
}
OUT PUT :
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |

populating and printing a 2D array given text file containing characters

im trying to print out a text file into a grid-like format after pulling them from a text file. Similar to this method, creating a 2 level for looping going through each row and column. However im not sure the process how it differs when dealing with characters rather than numbers.
example of text file im trying to replicate, excluding the first numbers
8 10
+-+-+-+-+-+-+-+-+-+
| |
+ +-+-+-+ +-+-+-+ +
| | | |
+ + +-+-+-+-+-+ + +
| | | | | |
+ + + +-+-+-+ + + +-+
| | | | | | | S|
+ + + + +-+ + + + +-+
| | | |E| | | |
+ + + +-+ +-+ + + +
| | | | | |
+ + +-+-+-+-+-+ + +
| | | |
+ +-+-+-+-+-+-+-+ +
| |
+-+-+-+-+-+-+-+-+-+
static void readMazeFile(String mazefile) throws FileNotFoundException {
Scanner mazeIn = new Scanner (new File (mazefile));
int height = mazeIn.nextInt();
int width = mazeIn.nextInt();
System.out.print(width);
System.out.print(height);
// get array height & width
int arrayHeight = (height*2)+1;
int arrayWidth = (width*2)+1;
System.out.print(arrayHeight);
System.out.print(arrayWidth);
// create new array set variables
char mazeAsArray[][] = new char[arrayHeight][arrayWidth];
int charCount = 0;
//populate and print array
System.out.print("-------------\n");
for (int r = 0; r < 9; r++){
for (int c = 0; c < 9; c++){
System.out.print(mazeAsArray[r][c]);
}
}
}
thank you
How do i get characters in a file into a 2D array in Java?
Most of the problems are answered in that link. First of all you are not assigning anything into the array. I'll copy my answer from that link here.
for (int row = 0; row < arrayheight; row++)
{
if(!mazein.hasNextLine())
break; // if there is no more lines to read, break the loop
String line = mazein.nextLine();
Char[] chars = line.toCharArray();
for (int col = 0, i = 0; (col < arraywidth && i < chars.length); col++,i++)
{
mazeAsArray[row][col] = chars[i];
System.out.print(mazeAsArray[row][col]);
}
}
Update:
I see your file don't have a regular number of characters in each line. You'll have to count the number of lines for the height and the number of characters in the longest line for the width or you could just input them yourself.

how to print this horizontally?

Hey guys if you run this code with the given input you will get a vertical ruler
i'm trying to get a horizontal ruler using the given recursive functions any idea how to get there or hints ???
public class Ruler {
// draw a tick with no label
public static void drawOneTick(int tickLength) {
drawOneTick(tickLength, -1);
}
// draw one tick
public static void drawOneTick(int tickLength, int tickLabel) {
for (int i = 0; i < tickLength; i++)
System.out.print("-");
if (tickLabel >= 0)
System.out.print(" " + tickLabel);
System.out.print("\n");
}
public static void drawTicks(int tickLength) {
if (tickLength > 0) {
drawTicks(tickLength-1);
drawOneTick(tickLength);
drawTicks(tickLength-1);
}
}
public static void drawRuler(int nInches, int majorLength) {
drawOneTick(majorLength, 0);
for (int i = 1; i <= nInches; i++) {
drawTicks(majorLength-1);
drawOneTick(majorLength, i);
}
}
public static void main(String[] args) {
drawRuler(3,4);
}
}
Assuming u want to do Ruler like this:
0 1 2 3 4 5
| | | | | |
| | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
It will be hard to it via recursive methods, because you've limited with print/println(), and because text is 1D ^^
So you wont be able to draw whole "tickline" in 1 method, no, tickline with height N will take N+1 printlines.
But, as you see, i've achieved this ruler, only with loops:
SPOLER!
package com.company;
public class Main {
private static String drawLabels(int count, int offset) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= count; i++) {
sb.append(i);
for (int spaces = 0; spaces < offset; ++spaces) {
sb.append(' ');
}
}
return sb.toString();
}
private static String drawTicks(int count, int offset) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= count; i++) {
sb.append('|');
for (int spaces = 0; spaces < offset; ++spaces) {
sb.append(' ');
}
}
return sb.toString();
}
public static void drawRuler(int nInches, int majorLength) {
// labels part
int offset = (int) Math.pow(2, majorLength - 1) - 1;
System.out.println(drawLabels(nInches, offset));
// rest
for (int line = majorLength; line > 0; --line) {
int ticksOffset = (int) Math.pow(2, line - 1) - 1;
int ticksNumber = nInches * (int) Math.pow(2, majorLength - line);
System.out.println(drawTicks(ticksNumber, ticksOffset));
}
}
public static void main(String[] args) {
drawRuler(5,5);
}
}
Here is a solution more inline with your example. You can still do it with recursion without having to use the power function to calculate the position of the tick.
I suggest to start with a smaller problem: How to draw the minor ticks between the major ticks. We can use the recursion for this one. We also have to realize that we can not anymore print the entire tick at once (as Fen1kz correctly mentioned) because it spans across multiple lines. We will have to loop over the number of lines and in the tick function either draw a tick or an empty space based on which line we are drawing. Once we have this we can easily draw one set of minor ticks. After that it is not too hard to add the rest of the code to repeat the previous and add the major ticks.
For completeness here is the whole code:
public class Ruler {
private static void drawMinorTicks(int line, int ticks) {
if (ticks > 1) {
drawMinorTicks(line, ticks - 1);
}
if (line <= ticks) {
System.out.print('|');
} else {
System.out.print(' ');
}
if (ticks > 1) {
drawMinorTicks(line, ticks - 1);
}
}
private static void drawSingleMajorTick(int line, int ticks, int label) {
if (line <= ticks) {
System.out.print('|');
} else {
System.out.print(label);
}
}
private static void drawMajorTicks(int inches, int line, int ticks) {
drawSingleMajorTick(line, ticks, 0);
for (int i = 1; i <= inches; i++) {
drawMinorTicks(line, ticks - 1);
drawSingleMajorTick(line, ticks, i);
}
}
private static void drawRuler(int inches, int ticks) {
for (int i = 1; i <= ticks + 1; ++i) {
drawMajorTicks(inches, i, ticks);
System.out.println();
}
}
public static void main(String[] args) {
drawRuler(5, 5);
}
}
And the output is:
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | |
| | | | | |
0 1 2 3 4 5

Gambler's Ruin ASCII Plot in Java

| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
| * |
|* |
I need to print something like the above ASCII plot for a Gambler's Ruin problem. Where the stake & goal are taken as args. The left most | represents 0 dollars, the right most | represents the goal and the * represents the cash on hand. My program is below:
public class RuinPath {
public static void main(String[] args) {
// TODO - Your solution
int stake = Integer.parseInt(args[0]); // gambler's stating bankroll
int goal = Integer.parseInt(args[1]); // gambler's desired bankroll
{
int i = 0;
if (i == 0) {
System.out.print("|");
i++;
while (i < stake) {
System.out.print(" ");
i++;
if (i == stake) {
System.out.print("*");
i++;
while (i > stake && i < goal) {
System.out.print(" ");
i++;
if (i == goal) {
System.out.print("|");
i = 0;
System.out.println();
{
if (Math.random() < 0.5) {
stake++; // win $1
} else {
stake--; // lose $1
}
if (stake == 1 || stake == goal - 1);
break;
}
}
}
}
}
}
}
}
}
what this program prints though is:
| * |
* |
* |
* |
* |
* |
* |
* |
* |
* |
* |
* |
* |
* |
*
Why does my program not loop so that i can get the left most | to appear to represent 0 dollars all the way through? I have it so i = 0; at the end of the loop so that when it goes back around it should re-loop until the stake is 1 or less than the goal. Instead it re-loops from the middle of the program.
Your logic is a little too complicated. Also, your indentation will make any sort of debugging extremely difficult.
Just take it one step at a time:
public class RuinPath {
public static void main(String[] args) {
int stake = Integer.parseInt(args[0]); // Starting bankroll
int goal = Integer.parseInt(args[1]); // Desired bankroll
while (stake > 0 && stake < goal) {
System.out.print("|");
// Print out the spaces. Using a for loop and
// printing a "*" if the counter variable
// is equal to stake is good way to do it.
// Flip a coin and increment/decrement the stake
System.out.print("|\n");
}
}
}
Here is a broken out solution that might be easier to reason about:
import java.io.PrintStream;
public class SO {
private static int gambleWithCaution(int stake) {
if (Math.random() < 0.5) {
return stake+1; // win $1
} else {
return stake-1; // lose $1
}
}
private static void renderStanding(int stake, int goal) {
System.out.print('|');
for(int dollar = 1; dollar< goal; dollar++) {
if(dollar == stake) {
System.out.print('*');
} else {
System.out.print(' ');
}
}
System.out.println('|');
}
public static void main(String ... args) {
int stake = Integer.parseInt(args[0]); // gambler's stating bankroll
int goal = Integer.parseInt(args[1]); // gambler's desired bankroll
while(stake > 0 && stake < goal) {
renderStanding(stake, goal);
stake = gambleWithCaution(stake);
}
System.out.println((stake > goal) ? "You Won!" : "You Lost");
}
}
With the values 3 and 5 you get this output:
| * |
| * |
|* |
| * |
| * |
| *|
| * |
| *|
You Won!
Now that this is seperated out you can have some fun with it like creating a gamble function like this:
private static int gambleWithReclessAbandon(int stake, int goal, double abandon) {
int onTheLine = (int)(Math.random() * (int)(stake * abandon));
if(stake < (0.5)*goal) {
//If you are at less than 50% of your goal then just put it all on the line
//and let it ride :)
onTheLine = stake;
}
if (Math.random() < 0.5) {
return stake+onTheLine; // win $
} else {
return stake-onTheLine; // lose $
}
}
Which can be invoked like this:
//Gamble up to 80% of your current stake
stake = gambleWithReclessAbandon(stake, goal, 0.80);
With the same two values this is what I saw on my first pass (I was sooo close :)):
| * |
| * |
| *|
| * |
| *|
You Lost

Categories

Resources