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;
}
}
Related
In this program, a randomly generated 2D array is populated with 1's or 0's and I attempt to find a path of 1's (no diagonal movement). I have got the program to work for smaller dimensions of the 2D array, but when the dimensions are too large, the error Exception in thread "main" java.lang.StackOverflowError occurs.
import java.util.Scanner;
import java.util.Random;
public class Daft {
private int counter = 0;
public static void main(String[] args) {
Daft punk = new Daft();
punk.run();
}
public void run() {
int ans;
int[][] array;
int[][] solvedPath;
do {
counter = 1;
array = populate(defineArray(firstDimension(),secondDimension()));
solvedPath = findPath(array);
System.out.println("Times before solvable: " + counter);
print(solvedPath);
ans = continuity();
}while(ans != 0);
}
public int[][] findPath(int[][] array) {
int r = 0, c = 0;
while(true) {
array[0][0] = 7;
if(c == 0 && r == array.length-1) { //reached the bottom left, checks right
if(array[r][c+1] == 1) {
array[r][c+1] = 7;
c+=1;
} else {
array[r][c] = 7;
break;
}
} else if(c == array[0].length-1 && r == array.length-1) { //reached the bottom right, checks left
if(array[r][c-1] == 1) {
array[r][c-1] = 7;
} else {
array[r][c] = 7;
break;
}
} else if(r == array.length-1) { //reached the bottom, checks left/right
if(array[r][c+1] == 1 && array[r][c-1] == 1) {
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) { //checks right
array[r][c+1] = 7;
c+=1;
} else if(array[r][c-1] == 1) { //checks left
array[r][c-1] = 7;
c-=1;
} else { //end of path
array[r][c] = 7;
break;
}
} else if(c == 0) { //reached the left, checks right/bottom
if(array[r][c+1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) {
array[r][c+1] = 7;
c+=1;
} else if(array[r+1][c] == 1) {
array[r+1][c] = 7;
r+=1;
} else {
counter++; //path has ended, not solvable
newPath(array);
break;
}
} else if(c == array[0].length-1) { //reached the right, checks left/bottom
if(array[r+1][c] == 1 && array[r][c-1] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r+1][c] == 1) {
array[r+1][c] = 7;
r+=1;
} else if(array[r][c-1] == 1) {
array[r][c-1] = 7;
c-=1;
} else {
counter++; //path has ended, not solvable
newPath(array);
break;
}
} else if(array[r][c+1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c-1] == 1 && array[r+1][c] == 1) { //checks if path is unique
counter++;
newPath(array);
break;
} else if(array[r][c+1] == 1) { //checks right
array[r][c+1] = 7;
c+=1;
} else if(array[r+1][c] == 1) { //checks bottom
array[r+1][c] = 7;
r+=1;
} else if(array[r][c-1] == 1) { //checks left
array[r][c-1] = 7;
c-=1;
} else {
counter++;
newPath(array);
break;
}
}
return array;
}
public int firstDimension() {
Scanner in = new Scanner(System.in);
System.out.println("Size of the first dimension:");
return in.nextInt();
}
public int secondDimension() {
Scanner in = new Scanner(System.in);
System.out.println("Size of the second dimension:");
return in.nextInt();
}
public int[][] defineArray(int firstDimension, int secondDimension) {
return new int[firstDimension][secondDimension];
}
public int[][] populate(int[][] array) {
Random rand = new Random();
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[i].length; j++) {
array[i][j] = rand.nextInt(2);
}
}
return array;
}
public int continuity() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number to continue (0 to quit):");
return in.nextInt();
}
public void print(int[][] array) {
for(int[] ints : array) {
for(int anInt : ints) {
System.out.print(anInt + " ");
}
System.out.println();
}
System.out.println();
}
public void newPath(int[][] array) {
findPath(populate(array));
}
}
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.
I need help with creating a table in for my blackjack, that records all games and also shows the average score of all games.I Have my code but im stuck on what to do to fix the code. Here are all the codes that im working with. Here is an example of what the output should look like:Pic of how output should look like
import java.util.*;
class Blackjack{
public static void main (String[] arg) {
Deck d = new Deck(); d.shuffle();
Hand h = new Hand();
//Score s = new Score(); //added for bonus
System.out.println(d);
System.out.println(d.hit());
System.out.println( d.decode(d.hit()) );
h.add(5);
h.add(10);
System.out.println(h.display());
while(true) {
System.out.print("Enter (n)ew hand, (h)it, or (q)uit: ");
Scanner scan = new Scanner (System.in);
// these variables are for collecting the information for the Score
int [] line = new int [5]; //added for Bonus
int handScore = 0; //added for Bonus
char c = scan.next().charAt(0);
if (c == 'n' || c == 'N') {
System.out.println(c);
h.reset();
if (d.currentIndex < 51){
int card= d.hit(); h.add(card);
card= d.hit(); h.add(card);
h.display();
System.out.println();
} else if (d.currentIndex > 51) {
System.out.println("--- NO CARDS LEFT ON DECK ---");
System.out.println();
break;
} else {
System.out.println("-- NOT ENOUGH CARDS LEFT ON DECK--");
System.out.println();
break;
}
} else if (c == 'h' || c == 'H') {
System.out.println(c);
if (d.currentIndex < 52){ //must be 52
int handValue = h.scoreInHand() ;
if (handValue > 21) { //already busted
System.out.println("--- GET A NEW HAND --- ");
System.out.println();
} else if (handValue == 21) {//already blackjack
System.out.println("--- BlackJack --- ");
System.out.println();
} else if (h.firstIndex > 4 ) {
System.out.println( "-- ALREADY 5 CARDS IN HAND ---");
h.display();
System.out.println( "--- GET A NEW HAND ---");
System.out.println();
} else if (h.firstIndex == 0) {
System.out.println("--- GET A NEW HAND FIRST ---");
System.out.println();
} else {
int card= d.hit(); h.add(card);
h.display(); System.out.println();
}
} else { // > or = 52
System.out.println("----- NO CARDS LEFT ON DECK -----");
System.out.println();
break;
}//end if (d.firstIndex < 52
} else if (c == 'q' || c == 'Q') {
System.out.println(c);
//same as the if(c == n), so it can collect the last game.
break;
}
} //while
//prints the scores of the games the user played while the game was run.
//System.out.print(s.display());System.out.println(); //added for Bonus
System.out.println("BYE!");
}//end main
}
class Hand{
private int []Hand;
public int firstIndex;
Hand(){
Hand=new int[5];
for (int i=0; i<Hand.length; i++)
Hand[i]=-1;
firstIndex=0;
}
public String display(){
String s="";
String empty="Hand is empty";
for (int i=0; i<firstIndex;i++)
s=s+" "+decode(Hand[i]);
if (s.length()==0)
s= empty;
String sih="";
int sihand= scoreInHand();
if(sihand>0&&sihand<21)
sih=""+sihand;
else if(sihand==21&&firstIndex==2)
sih="blackjack";
else if (sihand==21&&firstIndex>2)
sih=""+sihand;
else
sih="BUST";
System.out.println(s+"\n"+sih);
return s.trim();
}
public void reset(){
for (int i=0; i<Hand.length;i++)
Hand[i]=-1;
firstIndex=0;
}
public void add(int card){
Hand[firstIndex]=card;
firstIndex++;
}
public String decode2(int value){
String code=""+"HCDS".charAt(value/13)
+"23456789TJQA".charAt(value%13);
return code;
}
public String decode(int value){
String[] pattern={"Heart","Clubs","Diamond","Spades"};
String[] num={"two","three","four","five","six","seven","eight","nine","ten","jack","queen","king","ace"};
return num[value%13]+ " of " + pattern[value/13];
}
public int scoreInHand(){
int[] s={2,3,4,5,6,7,8,9,10,10,10,10};
boolean firstAce=true;
int value=0;
int sum=0;
for (int i=0; i<firstIndex; i++)
{
value=Hand[i]%13;
if (value==12)
{
if (firstAce)
{
value=11;
firstAce=false;
}
else
value=1;
}
else
value=s[value];
sum=sum+value;
}
return sum;
}
public String toString{
String s="";
for (int i=0; i<5; i++)
{
if (i<firstIndex)
s=s+" | " + decode2(Hand[i])+" ";
else
s=s+" ";
}
s=s+firstIndex;
return s;
}
}//(2,3,4,5,6,7,8,9,10,10,10,10,11)
class Deck{
private int[] cards;
public int currentIndex;
Deck(){
currentIndex=0;
cards=new int[52];
for (int i=0; i<cards.length; i++)
cards[i]=i;
}
public String toString(){
String s="";
for (int i=currentIndex;i<cards.length; i++)
{
/* s=s+" "+cards[i];*/
String code=decode(cards[i]);
s=s+" "+code;
}
return s;
}
public String decode(int value)
{
String code=""+"HCDS".charAt (value/13)
+"23456789TJQKA".charAt(value%13);
return code;
}
public void shuffle(){
int j=0;
for (int i=0;i<cards.length; i++)
{
j=(int)(52*Math.random());
swap(i,j);
}
}
public void swap(int i, int j){
int temp=cards[i];
cards[i]=cards[j];
cards[j]=temp;
}
public int hit(){
int i=cards[currentIndex];
currentIndex++;
return i;
}
}
class Score extends Deck{
private String [] cuts=new String [26];
private int gfirstIndex;
Score(){
cuts=new String[26];
gfirstIndex=0;
}
public void markScore(Hand h, int score)
{
String s="";
char fi;
String hand=h.toString();
int firstIndex;
fi=hand.charAt(hand.length()-1);
firstIndex=fi-'0';
hand=hand.substring(0,hand.length()-1);
s=s+" | "+(gfirstIndex+1)+(((gfirstIndex+1)<10)?" ":" ")|;
s=s+hand+" ";
s=s+"(score="+score+")";
if (score>21)
s=s+"(BUSTS)";
else if (score==21&&firstIndex==2)
s=s+"(BLACKJACK)";
cuts[gfirstIndex]=s;
gfirstIndex++;
}
}
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.
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.