Adding an array into another array (for a Java Battleship program) - java

I've been at this Battleship code for weeks on and off and I really have trouble putting multi-cell ships in it. The program works fine as is, but I want to add ships that contain 2-4 cells. I've tried all that I could to no avail, if anybody can give me help that would be really great.
Here's my code, it might be a bit confusing:
import java.util.Random;
import java.util.Scanner;
public class Battleship
{
private static int counter = 0;
private static boolean flag = true;
public static void main(String[] args)
{
int[][] boardP1 = new int[10][10];
int[][] boardP2 = new int[10][10];
int[][] shipsP1 = new int[10][2];
int[][] shipsP2 = new int[10][2];
int[] shootP1 = new int[2];
int[] shootP2 = new int[2];
int shotHitP1 = 0, shotHitP2 = 0;
Scanner userInput = new Scanner(System.in);
String p1name = null, p2name = null;
// Welcome message
System.out.println("\033[2J\033[10;28f WELCOME TO BATTLESHIPS!");
System.out.print("\033[13;31f Player 1: ");
p1name = userInput.nextLine();
System.out.print("\033[15;31f Player 2: ");
p2name = userInput.nextLine();
// Clear screen
System.out.println("\033[2J");
// Initialize boards (random)
initBoardsP1(boardP1);
initBoardsP2(boardP2);
// Initialize ships (random)
initShips(shipsP1);
initShips(shipsP2);
do
{ // Display boards
showBoardP1(boardP1);
showBoardP2(boardP2);
// P1 ask for shot
shootP1(shootP1);
counter++;
if (hit(shootP2,shipsP2))
{
shotHitP1++;
if (shotHitP1 == 5)
{ System.out.println("\n\n\n" +p1name+ " has won the game!");
System.out.println(); }
}
else
{ System.out.println("\033[48;36f Miss!"); }
changeboardP2(shootP1, shipsP1, boardP1);
System.out.print("\033[2J");
// P2 Ask for shot
showBoardP1(boardP1);
showBoardP2(boardP2);
shootP2(shootP2);
counter++;
if (hit(shootP1,shipsP1))
{
shotHitP2++;
if (shotHitP2 == 5)
{ System.out.println("\n\n\n" +p2name+ " has won the game!");
System.out.println(); }
}
else
{ System.out.println();
System.out.println("You missed!");
System.out.println(); }
changeboardP1(shootP2, shipsP2, boardP2);
System.out.print("\033[2J");
} while (shotHitP1 != 5 || shotHitP2 != 5);
}
public static void initShips(int[][] ships)
{
Random random = new Random();
for (int ship = 0; ship < 10; ship++)
{
ships[ship][0] = random.nextInt(10); // Draws row coordinate
ships[ship][1] = random.nextInt(10); // Draws column coordinate
// Check to see if already used combo
for (int last = 0; last < ship; last++)
{
if ((ships[ship][0] == ships[last][0]) && (ships[ship][1] == ships[last][1]))
do
{ ships[ship][0] = random.nextInt(10);
ships[ship][1] = random.nextInt(10); }
while((ships[ship][0] == ships[last][0])&&(ships[ship][1] == ships[last][1]));
}
}
}
public static void initBoardsP1(int[][] boardP1)
{ for (int row = 0; row < 10; row++)
for (int column = 0; column < 10; column++)
boardP1[row][column] = -1; }
public static void initBoardsP2(int[][] boardP2)
{ for (int row = 0; row < 10; row++)
for (int column = 0; column < 10; column++)
boardP2[row][column] = -1; }
public static void showBoardP1(int[][] boardP1)
{
if (flag = true)
{ System.out.println("\033[9;15f PLAYER 2");
System.out.println("\033[12;5f 1 2 3 4 5 6 7 8 9 10");
System.out.println("\033[13;4f +-++-++-++-++-++-++-++-++-++-+"); }
else
{ System.out.println("\033[9;54f PLAYER 1");
System.out.println("\033[12;45f 1 2 3 4 5 6 7 8 9 10");
System.out.println("\033[13;44f +-++-++-++-++-++-++-++-++-++-+"); }
for (int row = 0; row < 10; row++)
{
if (flag = true)
{ System.out.print("\033[1C"); }
else
{ System.out.print("\033[40C"); }
if (row <= 8)
{ System.out.print(" " +(row+1)+ " "); }
else
{ System.out.print(" 10 "); }
for (int column = 0; column < 10; column++)
{
System.out.print("|");
if (boardP1[row][column] == -1)
{ System.out.print(" "); }
else if (boardP1[row][column] == 0)
{ System.out.print("0"); }
else if (boardP1[row][column] == 1)
{ System.out.print("\033[1;31mX\033[0m"); }
System.out.print("|");
}
if (flag = true)
{ System.out.println();
System.out.println(" +-++-++-++-++-++-++-++-++-++-+"); }
else
{ System.out.println();
System.out.println("\033[40C +-++-++-++-++-++-++-++-++-++-+"); }
if ((counter % 100) == 0)
{ flag = true; }
else
{ flag = false; }
}
}
public static void showBoardP2(int[][] boardP2)
{
if (flag = true)
{ System.out.println("\033[9;54f PLAYER 1");
System.out.println("\033[12;45f 1 2 3 4 5 6 7 8 9 10");
System.out.println("\033[13;44f +-++-++-++-++-++-++-++-++-++-+"); }
else
{ System.out.println("\033[9;15f PLAYER 2");
System.out.println("\033[12;5f 1 2 3 4 5 6 7 8 9 10");
System.out.println("\033[13;4f +-++-++-++-++-++-++-++-++-++-+"); }
for (int row = 0; row < 10; row++)
{
if (flag = true)
{ System.out.print("\033[40C"); }
else
{ System.out.print("\033[1C"); }
if (row <= 8)
{ System.out.print(" " +(row+1)+ " "); }
else
{ System.out.print(" 10 "); }
for (int column = 0; column < 10; column++)
{
System.out.print("|");
if (boardP2[row][column] == -1)
{ System.out.print(" "); }
else if (boardP2[row][column] == 0)
{ System.out.print("0"); }
else if (boardP2[row][column] == 1)
{ System.out.print("\033[1;31mX\033[0m"); }
System.out.print("|");
}
if (flag = true)
{ System.out.println();
System.out.println("\033[40C +-++-++-++-++-++-++-++-++-++-+"); }
else
{ System.out.println();
System.out.println(" +-++-++-++-++-++-++-++-++-++-+"); }
if ((counter % 100) == 0)
{ flag = true; }
else
{ flag = false; }
}
}
public static void shootP1(int[] shootP1)
{
Scanner userInput = new Scanner(System.in);
System.out.println("\033[38;26f ----- PLAYER ONE'S SHOT -----");
System.out.println("\033[40;27f (Legend: 0 - Miss, \033[1;31mX\033[0m - Hit)");
System.out.println("\033[55;21f Press any non-integer character to quit.");
System.out.print("\033[44;35f Row: ");
shootP1[0] = userInput.nextInt();
shootP1[0]--;
System.out.print("\033[45;32f Column: ");
shootP1[1] = userInput.nextInt();
shootP1[1]--;
}
public static void shootP2(int[] shootP2)
{
Scanner input = new Scanner(System.in);
System.out.println("\033[38;26f ----- PLAYER TWO'S SHOT -----");
System.out.println("\033[40;27f (Legend: 0 - Miss, \033[1;31mX\033[0m - Hit)");
System.out.println("\033[55;21f Press any non-integer character to quit.");
System.out.print("\033[44;35f Row: ");
shootP2[0] = input.nextInt();
shootP2[0]--;
System.out.print("\033[45;32f Column: ");
shootP2[1] = input.nextInt();
shootP2[1]--;
}
public static boolean hit(int[] shoot, int[][] ships)
{
for (int ship = 0; ship < ships.length; ship++)
{
if (shoot[0] == ships[ship][0] && shoot[1] == ships[ship][1])
{
System.out.println("\033[48;34f KABOOM!!");
System.out.printf("\033[50;23f You hit a ship located in (%d,%d)!\n\n", shoot[0]+1, shoot[1]+1);
return true;
}
}
return false;
}
public static void changeboardP1(int[] shoot, int[][] ships, int[][] boardP1)
{
if (hit(shoot,ships))
{ boardP1[shoot[0]][shoot[1]] = 1; }
else
{ boardP1[shoot[0]][shoot[1]] = 0; }
}
public static void changeboardP2(int[] shoot, int[][] ships, int[][] boardP2)
{
if (hit(shoot,ships))
{ boardP2[shoot[0]][shoot[1]] = 1; }
else
{ boardP2[shoot[0]][shoot[1]] = 0; }
}
}

I don't understand the board/ship arrays in your code.
What are the extra arrays for ship for?
I suggest you make 1 array for each player's board filled with 0's at creation by default, and then add the boats by filling in 1's in the boats locations? and possibly later on in the game 2's for missed points and 3 for hits.
The only extra array you will need will be a 2D array containing 5 rows for the 5 ships and 2 columns specifying initial and ending coordinate of the ship that may later on be used to check if the entire ship has been destroyed or not.

Related

Battleship error connecting method shoot with hit

The issue I am having is when a user enters "A2" the program spits out it as A1. Even if someone picked "B3" it spits out A1.
There is an issue with my Shoot method connecting to my boolean hit method. I cannot seem to get the array done correctly.
Can one of you more experienced users please enlighten me on where I am going wrong.
public class Battleships {
public static void main(String[] args) {
int[][] board = new int[6][6];
int[][] ships = new int[3][2];
int[] shoot = new int[2];
int attempts=0,
shotHit=0;
initBoard(board);
initShips(ships);
System.out.println();
do{
showBoard(board);
shoot(shoot);
attempts++;
if(hit(shoot,ships)){
shotHit++;
}
else
changeboard(shoot,ships,board);
}while(shotHit!=3);
System.out.println("\n\n\nBattleship Java game finished! You hit 3 ships in "+attempts+" attempts");
showBoard(board);
}
public static void initBoard(int[][] board){
for(int row=0 ; row < 6 ; row++ )
for(int column=0 ; column < 6 ; column++ )
board[row][column]=-1;
}
public static void showBoard(int[][] board){
System.out.println("\tA \tB \tC \tD \tE \tF");
System.out.println();
for(int row=0 ; row < 6 ; row++ ){
System.out.print((row+1)+"");
for(int column=0 ; column < 6; column++ ){
if(board[row][column]==-1){
System.out.print("\t"+"~");
}else if(board[row][column]==0){
System.out.print("\t"+"*");
}else if(board[row][column]==1){
System.out.print("\t"+"X");
}
}
System.out.println();
}
}
public static void initShips(int[][] ships){
Random random = new Random();
for(int ship=0 ; ship < 3 ; ship++){
ships[ship][0]=random.nextInt(5);
ships[ship][1]=random.nextInt(5);
for(int last=0 ; last < ship ; last++){
if ((ships[ship][0] == ships[last][0])&&(ships[ship][1] == ships[last][1]))
do{
ships[ship][0]=random.nextInt(5);
ships[ship][1]=random.nextInt(5);
} while ((ships[ship][0] == ships[last][0])&&(ships[ship][1] == ships[last][1]));
}
}
}
public static void shoot(int[] shoot){
Scanner input = new Scanner(System.in);
String[] attempt = new String[2];
for(int i = 0; i < 10; i++) {
System.out.println("Enter your guess: ");
attempt[i] = input.next();
for(int j = 0; j < 2; j++) {
if (attempt[i].length() == 2 && Character.isLetter(attempt[i].charAt(0)) && Character.isDigit(attempt[i].charAt(1))) {
System.out.println("Good");
if (attempt[0].toUpperCase() == "A") {
shoot[0] = 1;
shoot[1] = Integer.valueOf(attempt[1]);
} else if (attempt[0].toUpperCase() == "B") {
shoot[0] = 2;
shoot[1] = Integer.valueOf(attempt[1]);
} else if (attempt[0].toUpperCase() == "C") {
shoot[0] = 3;
shoot[1] = Integer.valueOf(attempt[1]);
} else if (attempt[0].toUpperCase() == "D") {
shoot[0] = 4;
shoot[1] = Integer.valueOf(attempt[1]);
} else if (attempt[0].toUpperCase() == "E") {
shoot[0] = 5;
shoot[1] = Integer.valueOf(attempt[1]);
} else if (attempt[0].toUpperCase() == "F") {
shoot[0] = 6;
shoot[1] = Integer.valueOf(attempt[1]);
}
return;
} else {
System.out.println("invaid, please enter the proper format of letter then digit.");
j = 2;
}
}
}
input.close();
}
public static boolean hit(int[] shoot, int[][] ships){
for(int ship=0 ; ship<ships.length ; ship++){
if( shoot[0]==ships[ship][0] && shoot[1]==ships[ship][1]){
System.out.printf("You hit a ship located in (%d,%d)\n",shoot[0]+1,shoot[1]+1);
return true;
}
}
return false;
}
public static void changeboard(int[] shoot, int[][] ships, int[][] board){
if(hit(shoot,ships))
board[shoot[0]][shoot[1]]=1;
else
board[shoot[0]][shoot[1]]=0;
}
}

5 Card Poker Hand JAVA-Analyze and Categorize

Prompt: Write a program that reads five cards from the user, then analyzes the cards and prints out the category of hand that they represent.
Poker hands are categorized according to the following labels: Straight flush, four of a kind, full house, flush, straight, three of a kind, two pairs, pair, high card.
I currently have my program set as follows, first prompting the user for 5 cards, 2-9, then sorting the cards in ascending order. I set up my program to prompt the user and then go through several if else statements calling methods. I am having issues though where its not identifying three or four of a kind.
Example, if I enter 1, 3, 2, 1, 1, it identifies it as TWO PAIRS instead of Three of a Kind.
Same for entering 1, 1,1, 1, 4, it identifies as three of kind instead of 4.
Any suggestions to my code?
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
final int HAND_SIZE = 5;
int[] hand = new int[HAND_SIZE];
getHand(hand); //Prompt user for hand
sortHand(hand);//Sort hand in ascending order
if(containsFullHouse(hand))
{
System.out.print("FULL HOUSE!");
}
else if(containsStraight(hand))
{
System.out.print("STRAIGHT!");
}
else if(containsFourOfAKind(hand))
{
System.out.print("FOUR OF A KIND!");
}
else if(containsThreeOfAKind(hand))
{
System.out.println("THREE OF A KIND!");
}
else if(containsTwoPair(hand))
{
System.out.println("TWO PAIRS!");
}
else if(containsPair(hand))
{
System.out.println("PAIR!");
}
else
System.out.println("High Card!");
}
public static void getHand(int[] hand)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter five numeric cards, 2-9, no face cards please");
for(int index = 0; index < hand.length; index++)
{
System.out.print("Card " + (index + 1) + ": ");
hand[index] = input.nextInt();
}
}
public static void sortHand(int[] hand)
{
int startScan, index, minIndex, minValue;
for(startScan = 0; startScan < (hand.length-1); startScan++)
{
minIndex = startScan;
minValue = hand[startScan];
for(index = startScan + 1; index <hand.length; index++)
{
if(hand[index] < minValue)
{
minValue = hand[index];
minIndex = index;
}
}
hand[minIndex] = hand[startScan];
hand[startScan] = minValue;
}
}
public static boolean containsPair(int hand[])
{
boolean pairFound = false;
int pairCount = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
pairCount++;
}
startCheck = hand[index];
}
if (pairCount == 1)
{
pairFound = true;
}
else if(pairCount !=1)
{
pairFound = false;
}
return pairFound;
}
public static boolean containsTwoPair(int hand[])
{
boolean twoPairFound = false;
int twoPairCount = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
twoPairCount++;
}
startCheck = hand[index];
}
if (twoPairCount == 2)
{
twoPairFound = true;
}
else if(twoPairCount != 2)
{
twoPairFound = false;
}
return twoPairFound;
}
public static boolean containsThreeOfAKind(int hand[])
{
boolean threeFound = false;
int threeKind = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
threeKind++;
}
startCheck = hand[index];
}
if(threeKind == 3)
{
threeFound = true;
}
else if(threeKind !=3)
{
threeFound = false;
}
return threeFound;
}
public static boolean containsStraight(int hand[])
{
boolean straightFound = false;
int straight = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 1)
{
straight++;
}
startCheck = hand[index];
}
if(straight == 4)
{
straightFound = true;
}
return straightFound;
}
public static boolean containsFullHouse(int hand[])
{
boolean fullHouseFound = false;
int pairCheck = 0;
int startPairCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startPairCheck) == 0)
{
pairCheck++;
}
startPairCheck = hand[index];
}
int threeOfKindCheck = 0;
int startThreeKindCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startThreeKindCheck) == 0)
{
threeOfKindCheck++;
}
startThreeKindCheck = hand[index];
}
if(pairCheck == 1 && startThreeKindCheck == 3)
{
fullHouseFound = true;
}
return fullHouseFound;
}
public static boolean containsFourOfAKind(int hand[])
{
boolean fourFound = false;
int fourKind = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
fourKind++;
}
startCheck = hand[index];
}
if(fourKind == 1)
{
fourFound = true;
}
else if(fourKind !=4)
{
fourFound = false;
}
return fourFound;
}
}
Some hints.
Start with the highest hand. This eliminates lots of logic.
I.e if you check for pairs first, than you also have to check to make sure that your pair is the only pair, and not three of a kind.
But if you already ruled all of those out your code would be check card 1and2 23 34 and 45.

Java maze won't print

I have to make a maze for a java assignment, and I was able to finish most of it. I was provided with an outline of the code that had all the methods. Can someone help me? My issue is that the maze wont print out, and I can't figure out why.
package maze;
public class Maze {
private char direction;
private int r; // x position of the mouse
private int c; //y position of the mouse
private boolean exitFound = false;
public Maze(int[][] arrMaze) {
this.r = arrMaze.length - 1;
this.c = 0;
}
//Prints out the maze without solution
public void displayMaze(int[][] arrMaze)
{
//display the maze putting blank spaces where there are 1's in the array and putting
//another symbol where there are 0's to show the maze without the solution
for(int i=0; i<arrMaze.length; i++){
System.out.println(" ");
for(int j=0; j<arrMaze[i].length; j++){
if(arrMaze[i][j] == 0){
System.out.print("#");
} if(arrMaze[i][j] == 1) {
System.out.print(" ");
} if(arrMaze[i][j] == 2){
System.out.print("#");
} if(arrMaze[i][j] == 3){
System.out.println("~");
}
}
}
}
//displays the Maze with the path taken
public void displayPath(int[][] arrMaze)
{
//show the user how far the mouse has gone since the start.
//The path the mouse has gone will be filled in but the path ahead will not.
for (int i = 0; i < arrMaze.length; i++) {
System.out.println(" ");
for (int j = 0; j < arrMaze[i].length; j++) {
if (arrMaze[i][j] == 3) {
System.out.print("#");
} else if (arrMaze[i][j] == 2) {
System.out.print("~");
} else if (arrMaze[i][j] == 0) {
System.out.print("#");
} else {
}
}
}
}
public boolean takeStep(int[][] newMaze) {
// moveNorth(newMaze)
for (int i = 0; i < newMaze.length; i++) {
System.out.println(" ");
for (int j = 0; j < newMaze[i].length; j++) {
if (newMaze[r][c] == 3) {
moveNorth(newMaze);
System.out.print("~");
} else if (newMaze[r][c] == 2) {
System.out.print("#");
} else {
}
}
}
return isAnExit(newMaze);
}
public void moveNorth(int[][] arrMaze) {
//complete the code here
/*method will check for a 0 or a 1 in the position above the current position
* and then if not a 0 will change the current position to the row above it, but in the same column.
*/
if (arrMaze[r][c - 1] != 0) {
arrMaze[r][c - 1] = 3;
arrMaze[r][c + 1] = 2;
} else {
moveSouth(arrMaze);
}
displayPath(arrMaze);
}
public void moveSouth(int[][] arrMaze)
{
//method will check for a 0 or a 1 in the position below the current position and then if not a 0
//it will change the current position to the row below it, but in the same column.
if (arrMaze[r][c + 1] != 0) {
arrMaze[r][c + 1] = 3;
arrMaze[r][c + 1] = 2;
} else {
moveNorth(arrMaze);
}
displayPath(arrMaze);
}
public void moveEast(int[][] arrMaze) {
//method will check for a 0 or a 1 in the position to the right of  the current position and then if
//not a 0 will change the current position to the column to the right but the same row.
if (arrMaze[r + 1][c] != 0) {
arrMaze[r + 1][c] = 3;
arrMaze[r - 1][c] = 2;
} else {
moveWest(arrMaze);
}
displayPath(arrMaze);
}
public void moveWest(int[][] arrMaze) {
//method will check for a 0 or a 1 in the position to the left of  the current position and then if
//not a 0 will change the current position to the column to the left but the same row.
if (arrMaze[r - 1][c] != 0) {
arrMaze[r - 1][c] = 3;
arrMaze[r + 1][c] = 2;
} else {
}
displayPath(arrMaze);
}
private boolean isAnExit(int[][] arrMaze) {
//method will return true if the user arrives into the last column of the array because there is only one
//location in the last column that is a 1, so if the user reaches the array[i].length then that means that it found an exit.
if (arrMaze[r][c] > arrMaze.length) {
exitFound = true;
} else {
exitFound = false;
}
return exitFound;
}
//finds the path without stopping at every step
//method will show the complete path from start to finish of the maze and the suggested route to the end.
public void findExit(int[][] arrMaze) {
if (arrMaze[r][c] > arrMaze.length) {
for (int i = 0; i < arrMaze.length; i++) {
takeStep(arrMaze);
}
}
}
}
This is the test code. I was provided the test code, and I haven't changed it.
package maze;
import java.util.Scanner;
public class TestMaze
{
public static void main(String[] args)
{
int[][] mazeArray = {
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0},
{0,0,0,1,1,1,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,1,1,1},
{0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0},
{0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0},
{1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};
Maze myMaze = new Maze(mazeArray);
boolean keepAsking = true;
Scanner scan = new Scanner(System.in);
String input = "";
myMaze.displayPath(mazeArray);
System.out.println("Maze");
do {
System.out.println("T = Take a step | S = Show path | Q = Quit");
System.out.print("Enter command: ");
input = scan.nextLine();
input.trim();
input.toLowerCase();
if(input.equals("t")) {
keepAsking = !myMaze.takeStep(mazeArray);
System.out.println("Which direction would you like to go? N, S, E, W?");
String direction = scan.nextLine();
if(direction.equalsIgnoreCase("n"))
myMaze.moveNorth(mazeArray);
if(direction.equalsIgnoreCase("s"))
myMaze.moveSouth(mazeArray);
if(direction.equalsIgnoreCase("e"))
myMaze.moveEast(mazeArray);
if(direction.equalsIgnoreCase("w"))
myMaze.moveWest(mazeArray);
}
else if(input.equals("s")) {
myMaze.findExit(mazeArray);
keepAsking = false;
}
else if(input.equals("q")) {
keepAsking = false;
}
else {
System.out.println("ERR: Invalid input");
}
} while(keepAsking);
System.out.println("Quitting program...");
scan.close();
}
}
You need to call displayMaze() (in displayPath()) to print it.
Currently, you're not calling the method, meaning that your code will never print the maze as it's no being instructed to.
Also, where are you assigning values to r and c? I think you meant to use i and j in your displayPath() method ([i][j] instead of [r][c]).
I imagine you're throwing an error somewhere because your r and c values are undefined everywhere they are used. Try adding code to initialize and update these values, then you should see your maze print.

Nim game backtracking doesn't work on all row sequences - Java

I have a question. As an assignment we have to make the Nim game resolver using backtracking to predict which player is going to win based on the input on which player is going to start first (assuming that both players have a perfect decision rate).
Here is the code for the NimGame:
package Nim;
import java.util.ArrayList;
public class NimGame {
private int[] elements;
public NimGame(int[] elements) {
this.elements = new int[elements.length];
this.elements = elements;
}
public int NimSolver(boolean player) {
if (player == true && NimHelp(elements) == true) {
return 1;
} else if (player == false && NimHelp(elements) == true) {
return -1;
} else {
int score = 0;
int tmp = 0;
if (player == true) {
score = -1;
} else {
score = 1;
}
for (int i = 0; i < elements.length; i++) {
for (int j = 1; j <= elements[i]; j++) {
// Decrement element (Do thing)
elements[i] -= j;
// Backtrack
tmp = NimSolver(!player);
// SetScore
if (player == true && tmp > score) {
score = tmp;
} else if (player == false && tmp < score) {
score = tmp;
}
// Increment element (Undo thing)
elements[i] += j;
}
}
return score;
}
}
private boolean NimHelp(int[] elements) {
boolean[] isEmpty = new boolean[elements.length];
for (int i = 0; i < elements.length; i++) {
if (elements[i] == 0) {
isEmpty[i] = true;
} else {
isEmpty[i] = false;
}
}
for (boolean value : isEmpty) {
// If not all value is empty return false
if (!value)
return false;
}
return true;
}
public void NimResult(int player,int result)
{
if (player == 1) {
result = NimSolver(true);
} else if (player == 2) {
result = NimSolver(false);
}
if (result == 1) {
System.out.println("");
System.out.println("PLAYER 1 WON");
} else {
System.out.println("");
System.out.println("PLAYER 2 WON");
}
}
public void NimPrint(ArrayList<Integer> element)
{
System.out.println("");
System.out.print("MATCHES--------------------------------------");
for(int i = 0; i < element.size() ;i++)
{
System.out.println("");
for (int j = 0; j < element.get(i) ; j++) {
System.out.print("|");
}
}
}
}
Here is the code for Test Main class:
package Main;
import java.util.ArrayList;
import java.util.Scanner;
import Nim.NimGame;
public class Main {
public static void main(String[] args) {
int rows;
int elementTmp;
ArrayList<Integer> rowTmp = new ArrayList<Integer>();
int playerNo;
int result = 0;
int[] elements;
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.print("Input number of rows: ");
rows = sc.nextInt();
elements = new int[rows];
System.out.println("");
System.out.println("Input number of elements in each row");
for (int i = 0; i < rows; i++) {
System.out.print("Row number " + (i + 1) + " : ");
elementTmp = sc.nextInt();
elements[i] = elementTmp;
rowTmp.add(elementTmp);
}
NimGame nim = new NimGame(elements);
nim.NimPrint(rowTmp);
System.out.println("");
System.out.println("---------------------------------------------");
System.out.println("");
System.out.println("First player to move");
System.out.println("1) Player 1");
System.out.println("2) Player 2");
System.out.print("Input: ");
playerNo = sc.nextInt();
nim.NimResult(playerNo, result);
}
}
It works for the sequence: 3 rows , Row1 = 1, Row2 = 2, Row3 = 3 for example:
Input number of rows: 3
Input number of elements in each row
Row number 1 : 1
Row number 2 : 2
Row number 3 : 3
MATCHES--------------------------------------
|
||
|||
---------------------------------------------
First player to move
1) Player 1
2) Player 2
Input: 1
PLAYER 2 WON
But it doesn't work for all the sequences. I don't understand why.

Tic Tac Toe: All states get returned as best moves

I am working on building the game of Tic Tac Toe. Please find below the description of the classes used.
Game:: The main class. This class will initiate the multiplayer mode.
Board: This class sets the board configurations.
Computer: This class comprises of the minimax algorithm.
BoardState: This class comprises of the Board Object, along with the last x and y coordinates which were used to generate the board
configuration.
State: This class comprises of the score and the x and y coordinates that that will lead to that score in the game.
Context
Working on DFS here.
Exploring the whole tree works fine.
The game is set in such a way that the user is prompted to play first.
The user will put x and y co ordinates in the game.Coordinates are between 0 to 2. The Play of the player is marked as 1
The response from the computer is 2, which the algorithm decides. Th algorithm will determine the best possible coordinates to play and then play 2 on the position.
One of the winning configurations for Player is :
Player wins through diagonal
121
112
221
One of the winning configuration for AI is:
222
121
211
AI wins Horizontal
Problem
All the states give the max score.
Essentially, when you start the game in your system, you will find that since all states are given the max score, the computer looks to play sequentially.
As in if you put at (00), the computer plays at (01) and if you play at (02), the computer will play at (10)
I have been trying to debug it for a long time now. I believe, I may be messing up something with the scoring function. Or there could be a bug in the base recursion steps. Moreover, I don't think immutability among classes could cause problems as I have been recreating/creating new objects everywhere.
I understand, this might not be the best context I could give, but it would be a great help if you guys could help me figure out where exactly is it going wrong and what could I do to fix it. Answers through code/logic used would be highly appreciated. Thanks!
Game Class
import java.io.Console;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Game {
static int player1 = 1;
static int player2 = 2;
public static void main(String[] args) {
// TODO Auto-generated method stub
//
//PLays Game
playGame();
/* Test Use Case
ArrayList<Board> ar = new ArrayList<Board>();
Board b = new Board();
b.setVal(0,0,1);
b.setVal(0,1,1);
b.setVal(0,2,2);
b.setVal(1,0,2);
b.setVal(1,1,2);
b.setVal(2,0,1);
b.setVal(2,1,1);
b.display();
Computer comp = new Computer();
State x = comp.getMoves(b, 2);
*/
}
private static void playGame() {
// TODO Auto-generated method stub
Board b = new Board();
Computer comp = new Computer();
while(true)
{
if(b.isBoardFull())
{
System.out.println("Game Drawn");
break;
}
b.display();
int[] pmove = getPlayerMove(b);
b.setVal(pmove[0],pmove[1], player1);
if(b.isVictoriousConfig(player1))
{
System.out.println("Player 1 Wins");
break;
}
if(b.isBoardFull())
{
System.out.println("Game Drawn");
break;
}
b.display();
System.out.println("Computer Moves");
/*For Random Play
* int[] cmove = comp.computeMove(b);
*/
Computer compu = new Computer();
State s = compu.getMoves(b, 2);
int[] cmove = new int[2];
cmove[0] = s.x;
cmove[1] = s.y;
b.setVal(cmove[0],cmove[1], player2);
if(b.isVictoriousConfig(player2))
{
System.out.println("Computer Wins");
break;
}
}
System.out.println("Game Over");
}
//Gets Player Move. Basic Checks on whether the move is a valud move or not.
private static int[] getPlayerMove(Board b) {
// TODO Auto-generated method stub
int[] playerMove = new int[2];
System.out.println("You Play");
while(true)
{
#SuppressWarnings("resource")
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter X Position: ");
while(true)
{
playerMove[0] = reader.nextInt(); // Scans the next token of the input as an int.
if(playerMove[0] >2)
{
System.out.println("Incorrect Position");
}
else
{
break;
}
}
System.out.println("Enter Y Position: ");
while(true)
{
playerMove[1] = reader.nextInt(); // Scans the next token of the input as an int.
if(playerMove[1] >2)
{
System.out.println("Incorrect Position");
}
else
{
break;
}
}
System.out.println("You entered positions: X is " + playerMove[0] + " and Y is " + playerMove[1] );
if(!b.isPosOccupied(playerMove[0], playerMove[1]))
{
break;
}
System.out.println("Incorrect Move. PLease try again");
}
return playerMove;
}
}
Board Class
import java.util.Arrays;
public class Board {
// Defines Board Configuration
private final int[][] data ;
public Board()
{
data = new int[3][3];
for(int i=0;i<data.length;i++ )
{
for(int j=0;j<data.length;j++ )
{
data[i][j] = 0;
}
}
}
//Displays Current State of the board
public void display()
{
System.out.println("Board");
for(int i = 0; i< data.length;i++)
{
for(int j = 0; j< data.length;j++)
{
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
// Gets the Value on a specific board configuration
public int getVal(int i, int j)
{
return data[i][j];
}
//Sets the value to a particular board location
public void setVal(int i, int j,int val)
{
data[i][j] = val;
}
public boolean isBoardFull()
{
for(int i=0;i< data.length ; i++)
{
for(int j=0;j< data.length ;j++)
{
if(data[i][j] == 0)
return false;
}
}
return true;
}
public boolean isVictoriousConfig(int player)
{
//Noting down victory rules
//Horizontal Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [0][1]) && (data[0][1] == data [0][2]) && (data[0][2] == player)))
return true;
if ((data[1][0] != 0) && ((data[1][0] == data [1][1]) && (data[1][1] == data [1][2]) && (data[1][2] == player)))
return true;
if ((data[2][0] != 0) && ((data[2][0] == data [2][1]) && (data[2][1] == data [2][2]) && (data[2][2] == player)))
return true;
//Vertical Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [1][0]) && (data[1][0] == data [2][0]) && (data[2][0] == player)))
return true;
if ((data[0][1] != 0) && ((data[0][1] == data [1][1]) && (data[1][1] == data [2][1]) && (data[2][1] == player)))
return true;
if ((data[0][2] != 0) && ((data[0][2] == data [1][2]) && (data[1][2] == data [2][2]) && (data[2][2] == player)))
return true;
//Diagonal Victory
if ( (data[0][0] != 0) && ((data[0][0] == data [1][1]) && (data[1][1] == data [2][2]) && (data[2][2] == player)))
return true;
if ( (data[0][2] != 0) && ((data[0][2] == data [1][1]) && (data[1][1] == data [2][0]) && (data[2][0] == player)))
return true;
//If none of the victory rules are met. No one has won just yet ;)
return false;
}
public boolean isPosOccupied(int i, int j)
{
if(data[i][j] != 0)
{
return true;
}
return false;
}
public Board(int[][] x)
{
this.data = Arrays.copyOf(x, x.length);
}
}
Board State
public class BoardState {
final Board br;
final int x ;
final int y;
public BoardState(Board b, int posX, int posY)
{
br = b;
x = posX;
y = posY;
}
}
State
public class State {
final int s;
final int x;
final int y;
public State(int score, int posX, int posY)
{
s = score;
x = posX;
y = posY;
}
}
Computer
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public class Computer {
int[] pos = new int[2];
static int player2 = 2;
static int player1 = 1;
ArrayList<Board> win =new ArrayList<Board>();
ArrayList<Board> loose =new ArrayList<Board>();
ArrayList<Board> draw =new ArrayList<Board>();
public Computer()
{
}
public int[] computeMove(Board b)
{
while(true)
{
Random randX = new Random();
Random randY = new Random();
pos[0] = randX.nextInt(3);
pos[1] = randY.nextInt(3);
if(!b.isPosOccupied(pos[0], pos[1]))
{
return pos;
}
}
}
public State getMoves(Board b,int p)
{
//System.out.println("test2");
int x = 0;
int y = 0;
BoardState bs = new BoardState(b,0,0);
//System.out.println("test");
State s = computeMoveAI(bs,p);
//System.out.println("Sore : X : Y" + s.s + s.x + s.y);
return s;
}
private State computeMoveAI(BoardState b, int p) {
// TODO Auto-generated method stub
//System.out.println("Hello");
int[][]sArray = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
sArray[i1][j1] = b.br.getVal(i1, j1);
}
}
Board d = new Board(sArray);
//System.out.println("d is ");
//d.display();
//System.out.println("p is "+ p);
int xvalue= b.x;
int yvalue = b.y;
BoardState bs = new BoardState(d,xvalue,yvalue);
if(getConfigScore(d,p) == 1)
{
//System.out.println("Winning Config");
//System.out.println("X is " + b.x + " Y is " + b.y);
// b.br.display();
State s = new State(-1,bs.x,bs.y);
return s;
}
else if (getConfigScore(d,p) == -1)
{
//System.out.println("LooseConfig");
State s = new State(1,bs.x,bs.y);
//System.out.println("Coordinates are "+bs.x + bs.y+ " for " + p);
return s;
}
else if(bs.br.isBoardFull())
{
//System.out.println("Board is full");
State s = new State(0,bs.x,bs.y);
//System.out.println("score " + s.s + "x "+ s.x + "y "+ s.y);
return s;
}
else
{
//Get Turn
//System.out.println("In else condiyion");
int turn;
if(p == 2)
{
turn = 1;
}else
{
turn = 2;
}
ArrayList<BoardState> brr = new ArrayList<BoardState>();
ArrayList<State> st = new ArrayList<State>();
brr = getAllStates(d,p);
for(int k=0;k<brr.size();k++)
{
//System.out.println("Goes in " + "turn " + turn);
//brr.get(k).br.display();
int xxxxx = computeMoveAI(brr.get(k),turn).s;
State temp = new State(xxxxx,brr.get(k).x,brr.get(k).y);
st.add(temp);
}
//Find all Nodes.
//Go to First Node and proceed with recursion.
//System.out.println("Displaying boards");
for(int i=0;i<brr.size();i++)
{
//brr.get(i).br.display();
//System.out.println(brr.get(i).x + " " + brr.get(i).y);
}
//System.out.println("Board configs are");
for(int i=0;i<st.size();i++)
{
//System.out.println(st.get(i).x + " " + st.get(i).y + " and score " + st.get(i).s);
}
//System.out.println("xvalue" + xvalue);
//System.out.println("yvalue" + yvalue);
//System.out.println("Board was");
//d.display();
//System.out.println("Coming to scores");
//System.out.println(" p is "+ p);
if(p == 2)
{
//System.out.println("Size of first response" + st.size());
//System.out.println("Returns Max");
return max(st);
}
else
{
//System.out.println("The last");
return min(st);
}
}
}
private State min(ArrayList<State> st) {
// TODO Auto-generated method stub
ArrayList<State> st1= new ArrayList<State>();
st1= st;
int min = st.get(0).s;
//System.out.println("Min score is " + min);
for(int i=1;i<st1.size();i++)
{
if(min > st1.get(i).s)
{
min = st1.get(i).s;
//System.out.println("Min is");
//System.out.println(min);
//System.out.println("Min" + min);
State s = new State(min,st1.get(i).x,st1.get(i).y);
return s;
}
}
State s = new State(st1.get(0).s,st1.get(0).x,st1.get(0).y);
//System.out.println("Max" + st1.get(0).s);
//System.out.println("Exits Min");
//System.out.println("Min Score" + st1.get(0).s + " x" + st1.get(0).x + "y " + st1.get(0).y);
return s;
}
private State max(ArrayList<State> st) {
// TODO Auto-generated method stub
//System.out.println("Size of first response in funciton is " + st.size());
ArrayList<State> st1= new ArrayList<State>();
st1 = st;
int max = st1.get(0).s;
for(int i=0;i<st1.size();i++)
{
// System.out.println(i+1 + " config is: " + "X:" + st1.get(i).x + "Y:" + st1.get(i).y + " with score " + st1.get(i).s);
}
for(int i=1;i<st1.size();i++)
{
//.out.println("Next Item " + i + st.get(i).s + "Coordinates X"+ st.get(i).x +"Coordinates Y"+ st.get(i).y );
if(max < st1.get(i).s)
{
max = st1.get(i).s;
//System.out.println("Max" + max);
//System.out.println("Max is");
//System.out.println(max);
State s = new State(max,st1.get(i).x,st1.get(i).y);
//System.out.println("Max Score returned" + s.s);
//System.out.println("Returned");
return s;
}
}
State s = new State(st1.get(0).s,st1.get(0).x,st1.get(0).y);
//System.out.println("Max" + st1.get(0).s);
//System.out.println("Max is outer");
//System.out.println(st.get(0).s);
return s;
}
//Basic brain Behind Min Max algorithm
public int getConfigScore(Board b,int p)
{
int score;
int turn ;
int opponent;
if(p == player1)
{
turn = p;
opponent = player2;
}
else
{
turn = player2;
opponent = player1;
}
int[][]sArray = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
sArray[i1][j1] = b.getVal(i1, j1);
}
}
Board d = new Board(sArray);
//System.out.println("s arrasy is ");
//d.display();
//System.out.println("turn is " + turn);
if(d.isVictoriousConfig(turn))
{
score = 1;
}
else if(d.isVictoriousConfig(opponent))
{
score = -1;
}
else
{
score = 0;
}
return score;
}
public static ArrayList<BoardState> getAllStates(Board b, int player)
{
ArrayList<BoardState> arr = new ArrayList<BoardState>();
int[][]s1 = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
s1[i1][j1] = b.getVal(i1, j1);
}
}
Board d = new Board(s1);
for(int i = 0;i <3; i ++)
{
for (int j=0;j<3;j++)
{
if(!d.isPosOccupied(i, j))
{
int previousState = d.getVal(i, j);
int[][]s = new int[3][3];
for(int i1 =0;i1<3;i1++)
{
for(int j1=0;j1<3;j1++)
{
s[i1][j1] = d.getVal(i1, j1);
}
}
s[i][j] = player;
Board d1 = new Board(s);
BoardState bs = new BoardState(d1,i,j);
arr.add(bs);
}
}
}
return arr;
}
}
This is the output of the test case in the Game class:
Board
1 1 2
2 2 0
1 1 0
Score : X : Y -> 1: 1: 2
The solution here is score:1 for x:1, y:2. It looks correct.
But again, you could say since it is moving sequentially, and since position (1,2) will come before (2,2), it gets the right coordinate.
I understand that this may be huge lines of code to figure out the problem. But
computemoveAI(), getConfigScore() could be the functions to look out for. Also I do not want to bias your thoughts with where I think the problem could as sometimes, we look somewhere , but the problem lies elsewhere.!!

Categories

Resources