I am making SOS game with "stack".No other data structures such as normal array, string etc.
Gameboard size 3*6 and I am using random for determining letters.
But I don't know is the game over or not.
How can I control is there any horizontal or vertical sos at the console
Here is my code(I am beginner)
public static void main(String[] args) {
Random rnd = new Random();
Stack S1 = new Stack(6);
Stack S2 = new Stack(6);
Stack S3 = new Stack(6);
Stack ts1 = new Stack(6);
Stack ts2 = new Stack(6);
Stack ts3 = new Stack(6);
int Round = 0;
int satir;
boolean winner = false;
// for S1
int i = 0;
while (i != 6) { // 6time
i++;
// System.out.println(i);
if (rnd.nextBoolean()) {
S1.push("S");
} else {
S1.push("O");
}
}
// for S2
i = 0;
while (i != 6) {
i++;
if (rnd.nextBoolean()) {
S2.push("S");
} else {
S2.push("O");
}
}
// for S3
i = 0;
while (i != 6) {
i++;
if (rnd.nextBoolean()) {
S3.push("S");
} else {
S3.push("O");
}
}
int a = 0, b = 0, c = 0;
int tempa = a;
int tempb = b;
int tempc = c;
while (!winner) {
System.out.println("User" + ((Round % 2) + 1) + ":"); // User1:
// User2:
satir = rnd.nextInt(3) + 1;
if (satir == 1 && a != 6) {
a++;
}
if (satir == 2 && b != 6) {
b++;
}
if (satir == 3 && c != 6) {
c++;
}
tempa = a;
tempb = b;
tempc = c;
System.out.print("S1 ");
while (a > 0) { // S1 in icini yazdir bosalt ts1e kaydet
System.out.print(S1.peek() + " ");
ts1.push(S1.pop());
a--;
}
a = tempa;
while (!ts1.isEmpty()) { // S1i tekrar doldur
S1.push(ts1.pop());
}
System.out.println();
System.out.print("S2 ");
while (b > 0) { // S2 in icini yazdir bosalt ts1e kaydet
System.out.print(S2.peek() + " ");
ts2.push(S2.pop());
b--;
}
b = tempb;
while (!ts2.isEmpty()) { // S2i tekrar doldur
S2.push(ts2.pop());
}
System.out.println();
System.out.print("S3 ");
while (c > 0) { // S3 in icini yazdir bosalt ts1e kaydet
System.out.print(S3.peek() + " ");
ts3.push(S3.pop());
c--;
}
c = tempc;
while (!ts3.isEmpty()) { // S3i tekrar doldur
S3.push(ts3.pop());
}
System.out.println();
// check if there is sos winner=true;
if (a > 2) { //check S1 Horizontal
for (int yatay1 = 0; yatay1 < a; yatay1++) {
if (S1.peek().equals("S")) {
ts1.push(S1.pop());
if (S1.peek().equals("O")) {
ts1.push(S1.pop());
if (S1.peek().equals("S")) {
System.out.println("SOS-wow");
winner = true;
} else {
while (!ts1.isEmpty()) {
S1.push(ts1.pop());
}
}
} else {
S1.push(ts1.pop());
}
}
}
}
Round++;
} // end of loop
}
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));
}
}
So, I'm very very new to Java, and I've been working on this problem for some time now. It's for a school project (which has been overdue for about 2 weeks) and I was looking for hints or some possible solutions that could guide me from this point.
The object of this program is to take in a .txt file (something like this: https://pastebin.com/hvg0P2Pe) and go through a 2D grid of letters in order to find provided words; the words can be connected horizontally, vertically, and diagonally. The catch for this program is that it cannot be done using iteration, it has to be done recursively.
Here's the output for the following code: https://pastebin.com/uXiDHjvU
I'm not completely sure what is the issue with my program; I've been scratching my head for days. Any support would be greatly appreciated.
import java.io.*;
import java.util.*;
public class wordMaze1 {
private static boolean wordCheck;
public static boolean wordSearch(char[][] letter, String words, int r, int c) {
if (letter[r][c] != words.charAt(0))
return false;
if (letter[r][c] == words.charAt(c))
return true;
if (letter[r][c] == words.charAt(0)) {
letter.toString().toLowerCase();
return wordSearch(letter, words.substring(1), r, c - 1);
} else if (letter[r][c] == words.charAt(0)) {
letter.toString().toLowerCase();
return wordSearch(letter, words.substring(1), r, c + 1);
} else if (letter[r][c] == words.charAt(0)) {
letter.toString().toLowerCase();
return wordSearch(letter, words.substring(1), r - 1, c);
} else if (letter[r][c] == words.charAt(0)) {
letter.toString().toLowerCase();
return wordSearch(letter, words.substring(1), r + 1, c);
} else if (letter[r][c] == words.charAt(0)) {
letter.toString().toLowerCase();
return wordSearch(letter, words.substring(1), r - 1, c - 1);
} else if (letter[r][c] == words.charAt(0)) {
letter.toString().toLowerCase();
return wordSearch(letter, words.substring(1), r + 1, c - 1);
} else if (letter[r][c] == words.charAt(0)) {
letter.toString().toLowerCase();
return wordSearch(letter, words.substring(1), r - 1, c + 1);
} else if (letter[r][c] == words.charAt(0)) {
letter.toString().toLowerCase();
return wordSearch(letter, words.substring(1), r + 1, c + 1);
}
return false;
}
public static void main(String[] args) {
try {
Scanner scan = new Scanner(new File("maze.txt"));
int numGrids = Integer.parseInt(scan.nextLine());
for (int i = 1; i < numGrids + 1; i++) {
System.out.println("Grid #" + i + ":");
int size = Integer.parseInt(scan.nextLine());
char[][] grid = new char[size][size];
String[] tempGrid = new String[size];
for (int t = 0; t < size; t++) {
tempGrid[t] = scan.nextLine();
System.out.println(tempGrid[t]);
}
int wordNum = Integer.parseInt(scan.nextLine());
String[] words = new String[wordNum];
for (int w = 0; w < wordNum; w++) {
words[w] = scan.nextLine();
for (int r = 0; r < size; r++) {
System.out.println();
for (int c = 0; c < size; c++) {
grid[r][c] = tempGrid[r].charAt(c);
System.out.print(grid[r][c]);
if (grid[r][c] == words[w].charAt(0))
if (wordSearch(grid, words[w], r, c)) {
wordCheck = true;
break;
}
}
//System.out.print(grid);
}
System.out.println();
if (wordCheck == true)
System.out.println(words[w] + " is found.");
else
System.out.println(words[w] + " is NOT found.");
}
System.out.println();
}
} catch (FileNotFoundException e) {
}
}
}
This line causes exception:
if (letter[r][c] == words.charAt(c))
If you replace charAt(c) with charAt(0), it should work better
This is the problem :
Input
The first line of input will contain the number of test cases, T (1 ≤ T ≤ 50). Each of the following T
lines contains a positive integer N that is no more than 80 digits in length.
Output
The output of each test case will be a single line containing the smallest palindrome that is greater
than or equal to the input number.
Sample Input
2
42
321
Sample Output
44
323
I keep having time limit exceeded when i submit to the code to online judge ( 3 seconds limit)
class Main {
static String ReadLn (int maxLg)
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
static boolean isPalandriome(String s){
String newString = "";
for(int i =s.length()-1;i >= 0; i--){
newString += s.charAt(i);
}
if(newString.equals(s))
return true;
else
return false;
}
public static void main(String[] args) {
BigInteger entredNumber;
String input;
input = Main.ReadLn(10);
int tests = Integer.parseInt(input);
List<BigInteger> numbers = new ArrayList<BigInteger>();
for (int i =0;i<tests;i++)
{
input = Main.ReadLn(100);
entredNumber = new BigInteger(input);
numbers.add(entredNumber);
}
for(int i=0;i<tests;i++){
BigInteger number = numbers.get(i);
while(!isPalandriome(String.valueOf(number))){
number = number.add(BigInteger.ONE);
}
System.out.println(number);
}
}
}
I can't find what takes too much time in my code.
At last coded Hope you find this helpful took 0.10 seconds
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
CustomReader cr = new CustomReader(1000000);
int T = cr.nextInt(), fIndex, bIndex, fStartIndex, bStartIndex;
StringBuilder output = new StringBuilder();
byte[] input;
boolean isAppend1 = false;
for (int i = 0; i < T; i++) {
input = cr.nextInput();
fStartIndex = bStartIndex = cr.getCurrInputLength() / 2;
isAppend1 = false;
if (cr.getCurrInputLength() % 2 == 0) {
bStartIndex--;
}
fIndex = fStartIndex;
bIndex = bStartIndex;
while (input[bIndex] == input[fIndex]) {
if (bIndex - 1 < 0) {
break;
} else {
bIndex--;
fIndex++;
}
}
if (input[bIndex] > input[fIndex]) {
while (bIndex >= 0) {
input[fIndex++] = input[bIndex--];
}
} else {
if (input[bStartIndex] < 57) {
input[bStartIndex] = (byte) (input[bStartIndex] + 1);
} else {
bIndex = bStartIndex;
while (bIndex >= 0 && input[bIndex] == 57) {
input[bIndex] = 48;
bIndex--;
}
if (bIndex >= 0) {
input[bIndex] = (byte) (input[bIndex] + 1);
} else {
input[0] = 49;
if (fStartIndex != bStartIndex) {
input[fStartIndex] = 48;
bStartIndex = fStartIndex;
} else {
input[fStartIndex + 1] = 48;
bStartIndex = fStartIndex = fStartIndex + 1;
}
isAppend1 = true;
}
}
while (bStartIndex > -1) {
input[fStartIndex++] = input[bStartIndex--];
}
}
for (int j = 0; j < cr.getCurrInputLength(); j++) {
output.append((char) input[j]);
}
if (isAppend1) {
output.append("1");
}
output.append("\n");
}
System.out.print(output.toString());
// genInput();
}
private static class CustomReader {
private byte[] buffer;
private byte[] currInput = new byte[1000000];
private int currInputLength;
private int currIndex;
private int validBytesInBuffer;
CustomReader(int buffSize) {
buffer = new byte[buffSize];
}
public int nextInt() throws IOException {
int value;
byte b;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
break;
}
}
value = b - 48;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
value = (value * 10) + (b - 48);
} else {
break;
}
}
return value;
}
public byte[] nextInput() throws IOException {
byte b;
this.currInputLength = 0;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
break;
}
}
currInput[currInputLength++] = b;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
currInput[currInputLength++] = b;
} else {
break;
}
}
return this.currInput;
}
public int getCurrInputLength() {
return this.currInputLength;
}
private byte getNextByte() throws IOException {
if (currIndex == buffer.length || currIndex == validBytesInBuffer) {
validBytesInBuffer = System.in.read(buffer);
currIndex = 0;
}
return buffer[currIndex++];
}
}
public static void genInput() {
for (int i = 0; i < 100; i++) {
System.out.println((int) (Math.random() * 1000000000));
}
}
}
I need help with this program because it is not compiling correctly.
The program is supposed to do this:
java PostfixToInfix
1 2 3 + *
1*(2+3)
I am getting these errors when compiling:
PostfixToInfix.java:64: error: bad operand types for binary operator '-'
s.push(o2 - o1);
^
first type: String
second type: String
PostfixToInfix.java:68: error: bad operand types for binary operator '*'
s.push(o1 * o2);
^
first type: String
second type: String
2 errors
How many I supposed to code this so that it works properly? I am unsure what is wrong with my code that it is not allowing it do the functions properly.
This is my code:
import java.util.Scanner;
import java.util.Stack;
public class PostfixToInfix
{
public static void main(String[] args)
{
String[] input = readExpr();
if(checkSyntax(input) == true)
{
int k = 0;
Stack<String> s = new Stack<>();
for(int i = 0; i < input.length; ++i)
{
if(isOperator(input[i]))
{
String o1;
String o2;
if(!(s.empty()))
{
o1 = s.pop();
}
else
{
for(int j = 0; j < i; ++j)
{
k += input[j].length() + 1;
}
System.out.println("Too few operands for " + input[i]);
writeExpr(input);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
return;
}
if(!(s.empty()))
{
o2 = s.pop();
}
else
{
for(int j = 0; j < i; ++j)
{
k += input[j].length() + 1;
}
System.out.println("Too few operands for " + input[i]);
writeExpr(input);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
return;
}
if(input[i].equals("+"))
{
s.push(o1 + o2);
}
else if(input[i].equals("-"))
{
s.push(o2 - o1);
}
else
{
s.push(o1 * o2);
}
}
else
{
s.push(input[i]);
}
}
String Result = s.pop();
if(!(s.empty()))
{
System.out.println("Too few operators to produce a single result");
}
else
{
System.out.println(Result);
}
}
} // end main
static String[] readExpr()
{
Scanner stdin = new Scanner(System.in);
String s = stdin.nextLine();
String[] sA = s.split(" ");
return sA;
}
static void writeExpr(String[] expr)
{
for(int i = 0; i < expr.length; ++i)
{
System.out.print(expr[i] + " ");
}
System.out.println();
}
static boolean isOperator(String s)
{
if(s.equals("+") || s.equals("-") || s.equals("*"))
{
return true;
}
return false;
}
static boolean checkSyntax(String[] expr)
{
int k = 0;
for(int i = 0; i < expr.length; ++i)
{
if(!(isOperator(expr[i])))
{
try
{
Double.parseDouble(expr[i]);
}
catch (Exception e)
{
for(int j = 0; j < i; ++j)
{
k += expr[j].length() + 1;
}
writeExpr(expr);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
System.out.println("Not a number or valid operator");
return false;
}
}
}
return true;
}
} // end Postfix2
class StringStack
{
int top;
String[] pancake;
StringStack() //constructor for a new empty stack
{
top = 0;
pancake = new String[1000];
} // end DoubleStack
boolean empty() //whether the stack is empty
{
return top == 0;
} // end empty
String pop() //remove and return the top element; throw an error if empty
{
if(empty())
{
throw new Error("Error");
}
top -= 1;
return pancake[top];
} // end pop
void push(String x) //add x to the top of the stack
{
if(top < 1000)
{
pancake[top] = x;
top += 1;
}
else{
throw new Error("Error");
}
} // end push
} // end StringStack
Change you code like this.
if(input[i].equals("+"))
{
s.push(o1 + "+" + o2);
}
else if(input[i].equals("-"))
{
s.push(o2 + "-" + o1);
}
else
{
s.push(o1 + "*" + o2);
}
But the result for "1 2 3 + *" is "3+2*1".
It is another problem.
I'm creating a TCP game of Battleship in Java, and as I've made some functions work, methods that used to work no longer work.
Here's what's happening when it's a users turn. A bomb being dropped on 2 diffrent char[][], where clientGrid is the actual grid where the client has his ships. It's on this grid where the dropBomb method is being printed, and tells us whether a bomb has hit or not. clientDamage is just an overview for the server to see where he has previously dropped bombs.
if (inFromServer.ready()) {
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, clientGrid));
dropBomb(x, y, clientDamage);
outToClient.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
System.out.println(printBoard(clientDamage));
}
Here's the drop bomb method. It's proved to work before, however I have made some small changes to it. However I can't see why it wouldn't work. + indicates that there is a ship, x indicates that the target already has been bombed, and the else is ~, which is water. The method always returns "Nothing was hit on this coordinate...", and I can't seem to figure out why?
public static String dropBomb(int row, int col, char[][] board) {
if (row < gridSize && col < gridSize) {
if (board[row][col] == '+') {
board[row][col] = 'x';
return "Ship has been hit!";
} else if (board[row][col] == 'x') {
return "Already bombed.";
} else {
board[row][col] = 'x';
return "Nothing was hit on this coordinate...";
}
} else {
return "No such coordinate.";
}
}
Here is the full code... can someone please point out what I'm missing?
//server = player 1
//client = player 2
public class BattleshipGame {
public static ArrayList<Ship> fleet;
public static InetAddress clientAddress;
public static BattleshipGame battleship;
private final static int gridSize = 11;
public final static int numberOfShips = 3;
public static char[][] serverGrid;
public static char[][] clientGrid;
public static char[][] serverDamage;
public static char[][] clientDamage;
private int whosTurn;
private int whoStarts;
public static int count;
public static int bombCount;
public BattleshipGame() {
whoStarts = 0;
start();
showShipList();
}
public static String printBoard(char[][] board) {
String out = "";
for (int i = 1; i < board.length; i++) {
for (int j = 1; j < board.length; j++) {
out += board[j][i];
}
out += '\n';
}
return out;
}
public void start() {
Random rand = new Random();
if (rand.nextBoolean()) {
whoStarts = 1;
whosTurn = 1;
} else {
whoStarts = 2;
whosTurn = 2;
}
whoStarts = 1;
whosTurn = 1;
System.out.println("Player " + whoStarts + " starts\n");
}
public void initializeGrid(int playerNo) {
serverGrid = new char[gridSize][gridSize];
for (int i = 0; i < serverGrid.length; i++) {
for (int j = 0; j < serverGrid.length; j++) {
serverGrid[i][j] = '~';
}
}
serverDamage = new char[gridSize][gridSize];
for (int i = 0; i < serverDamage.length; i++) {
for (int j = 0; j < serverDamage.length; j++) {
serverDamage[i][j] = '~';
}
}
clientGrid = new char[gridSize][gridSize];
for (int i = 0; i < clientGrid.length; i++) {
for (int j = 0; j < clientGrid.length; j++) {
clientGrid[i][j] = '~';
}
}
clientDamage = new char[gridSize][gridSize];
for (int i = 0; i < clientDamage.length; i++) {
for (int j = 0; j < clientDamage.length; j++) {
clientDamage[i][j] = '~';
}
}
if (playerNo == 1) {
System.out.println("\nYour grid (player 1):\n"
+ printBoard(serverGrid));
} else if (playerNo == 2) {
System.out.println("\nYour grid (player 2):\n"
+ printBoard(clientGrid));
} else {
System.out.println("No such player.");
}
}
public static void deployShip(char[][] board, Ship ship, char direction,
int x, int y) {
if (direction == 'H') {
if (x < gridSize && y < gridSize) {
for (int i = 0; i < ship.getSize(); i++) {
board[x + i][y] = '+';
}
System.out
.println("Ship has been placed horizontally on coordinates "
+ x + ", " + y + ".");
} else {
System.out.println("Unable to place ship in this coordinate.");
}
} else if (direction == 'V') {
if (x < gridSize && y < gridSize) {
for (int i = 0; i < ship.getSize(); i++) {
board[x][y + i] = '+';
}
System.out
.println("Ship has been placed vertically on coordinates "
+ x + ", " + y + ".");
} else {
System.out.println("Unable to place ship in this coordinate.");
}
}
}
public static String dropBomb(int row, int col, char[][] board) {
if (row < gridSize && col < gridSize) {
if (board[row][col] == '+') {
System.out.println(board[row][col]);
board[row][col] = 'x';
bombCount++;
return "Ship has been hit!";
}
if (board[row][col] == 'x') {
System.out.println(board[row][col]);
bombCount++;
return "Already bombed.";
}
if (board[row][col] == '~') {
System.out.println(board[row][col]);
board[row][col] = 'x';
bombCount++;
return "Nothing was hit on this coordinate...";
}
} else {
return "No such coordinate.";
}
return "";
}
public void showShipList() {
System.out
.println("Choose ships to add to your fleet from the following list ("
+ numberOfShips + " ships allowed):");
ArrayList<Ship> overview = new ArrayList<Ship>();
Ship ac = new Ship("Aircraft carrier", 5, false);
Ship bs = new Ship("Battleship", 4, false);
Ship sm = new Ship("Submarine", 3, false);
Ship ds = new Ship("Destroyer", 3, false);
Ship sp = new Ship("Patrol Boat", 2, false);
overview.add(ac);
overview.add(bs);
overview.add(sm);
overview.add(ds);
overview.add(sp);
for (int i = 0; i < overview.size(); i++) {
System.out.println(i + 1 + ". " + overview.get(i));
}
}
public static ArrayList<Ship> createFleet(ArrayList<Ship> fleet, int choice) {
if (count < numberOfShips && choice > 0 && choice < 6) {
if (choice == 1) {
Ship ac = new Ship("Aircraft carrier", 5, false);
fleet.add(ac);
count++;
System.out.println("Aircraft carrier has been added to fleet.");
} else if (choice == 2) {
Ship bs = new Ship("Battleship", 4, false);
fleet.add(bs);
count++;
System.out.println("Battleship has been added to fleet.");
} else if (choice == 3) {
Ship sm = new Ship("Submarine", 3, false);
fleet.add(sm);
count++;
System.out.println("Submarine has been added to fleet.");
} else if (choice == 4) {
Ship ds = new Ship("Destroyer", 3, false);
fleet.add(ds);
count++;
System.out.println("Destroyer has been added to fleet.");
} else if (choice == 5) {
Ship sp = new Ship("Patrol Boat", 2, false);
fleet.add(sp);
count++;
System.out.println("Patrol boat has been added to fleet.");
}
} else {
System.out.println("Not an option.");
}
System.out.println("\nYour fleet now contains:");
for (Ship s : fleet) {
System.out.println(s);
}
return fleet;
}
}
public class TCPServer extends BattleshipGame {
private static final int playerNo = 1;
public static void main(String[] args) {
System.out.println("You are player: " + playerNo);
battleship = new BattleshipGame();
try {
InetAddress.getLocalHost().getHostAddress();
ServerSocket serverSocket = new ServerSocket(6780);
Socket socket = serverSocket.accept();
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());
Scanner scan = new Scanner(System.in);
while (true) {
if (inFromServer.ready()) {
setup(scan, playerNo);
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, clientGrid));
System.out.println(printBoard(clientGrid));
dropBomb(x, y, clientDamage);
outToClient.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
printBoard(clientDamage);
}
if (inFromClient.ready()) {
System.out.println(inFromClient.readLine());
System.out.println(printBoard(serverGrid));
}
}
// socket.close();
// serverSocet.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void setup(Scanner inFromUser, int playerNo) {
fleet = new ArrayList<Ship>();
while (count < numberOfShips) {
createFleet(fleet, inFromUser.nextInt());
}
battleship.initializeGrid(playerNo);
for (int i = 0; i < fleet.size(); i++) {
System.out.println(fleet.get(i));
System.out.println("Define direction (V/H) plus coordinates");
deployShip(serverGrid, fleet.get(i), inFromUser.next().charAt(0), inFromUser.nextInt(), inFromUser.nextInt());
}
System.out.println("Placements:\n" + printBoard(serverGrid));
System.out.println("Fleet has been deployed. Press enter to continue.\n");
}
}
public class TCPClient extends BattleshipGame {
private static final int playerNo = 2;
public static void main(String[] args) {
System.out.println("You are player: " + playerNo);
battleship = new BattleshipGame();
try {
InetAddress.getLocalHost().getHostAddress();
Socket socket = new Socket(InetAddress.getLocalHost()
.getHostAddress(), 6780);
DataOutputStream dataOutputStream = new DataOutputStream(
socket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(System.in));
Scanner scan = new Scanner(System.in);
setup(scan, playerNo);
while (true) {
if (inFromClient.ready()) {
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, serverGrid));
dropBomb(x, y, serverDamage);
dataOutputStream.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
System.out.println(printBoard(serverDamage));
}
if (inFromServer.ready()) { // modtag data fra server
System.out.println(inFromServer.readLine());
System.out.println(printBoard(clientGrid));
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void setup(Scanner inFromUser, int playerNo) {
fleet = new ArrayList<Ship>();
while (count < numberOfShips) {
createFleet(fleet, inFromUser.nextInt());
}
battleship.initializeGrid(playerNo);
for (int i = 0; i < fleet.size(); i++) {
System.out.println(fleet.get(i));
System.out.println("Define direction (V/H) plus coordinates");
deployShip(clientGrid, fleet.get(i), inFromUser.next().charAt(0), inFromUser.nextInt(), inFromUser.nextInt());
}
System.out.println("Placements:\n" + printBoard(clientGrid));
System.out.println("Fleet has been deployed. Press enter to continue.\n");
}
}
package Battleships;
public class Ship {
private String name;
private int size;
private boolean isDestroyed;
public Ship(String n, int s, boolean d) {
this.name = n;
this.size = s;
this.isDestroyed = d;
}
public String getName() {
String output = "";
output = "[" + name + "]";
return output;
}
public int getSize() {
return size;
}
public String toString() {
String output = "";
output = "[" + name + ", " + size + ", " + isDestroyed + "]";
return output;
}
}