Skip to content

Instantly share code, notes, and snippets.

@olegrewko
Created May 20, 2020 18:14
Show Gist options
  • Select an option

  • Save olegrewko/b58d55a7abaa85698bbb6959d0ae75ef to your computer and use it in GitHub Desktop.

Select an option

Save olegrewko/b58d55a7abaa85698bbb6959d0ae75ef to your computer and use it in GitHub Desktop.
Морской бой ООП-001
package IgorDolgov.seabattle;
import java.util.Scanner;
import static IgorDolgov.seabattle.SeaBattle.shoot;
public class SeaBattle {
static int shoot;
public static void main(String[] args) {
doGame();
}
private static void doGame() {
Field field = new Field();
Player player = new Player();
field.init();
field.initPhantom();
field.setShip();
do {
field.show();
System.out.println("Здесь реальное расположение кораблей");
field.showPhantom();
System.out.println("Здесь прячем");
shoot = player.getShoot();
field.doShoot(shoot);
} while (field.continueGame());
field.showPhantom();
}
}
////////////////////////////////////////////////////////////////
class Field {
char[] cells = new char[10];
char cellsPhantom[] = new char[10];
Ship ship;
void show() {
System.out.println(cells);
}
void showPhantom() {
System.out.println(cellsPhantom);
}
void init() {
for (int i = 0; i < cells.length; i++) {
cells[i] = '.';
}
}
void initPhantom() {
for (int i = 0; i < cellsPhantom.length; i++) {
cellsPhantom[i] = '.';
}
}
void doShoot(int shoot) {
int ch = 0;
if ((cells[shoot] == '.') || (cells[shoot] == '#')) {
System.out.println("Мимо");
cellsPhantom[shoot] = '*';
System.out.println(cellsPhantom);
}
if (cells[shoot] == 'X') {
ch++;
if (ch == 2) {
System.out.println("Убил");
cellsPhantom[shoot] = '#';
System.out.println(cellsPhantom);
// break; Почему здесь нельзя break?
} else {
System.out.println("Попал");
}
cellsPhantom[shoot] = '#';
System.out.println(cellsPhantom);
}
}
boolean continueGame() {
boolean sd = ((cells[ship.position] == 'X') && (cells[ship.position02] == 'X'));
return sd;
}
void setShip() {
Ship ship = new Ship();
ship.position = (int) (Math.random() * 9);
cells[ship.position] = 'X';
if ((ship.position + 1) > 10) {
ship.position02 = ship.position - 1;
} else {
ship.position02 = ship.position + 1;
}
cells[ship.position02] = 'X';
}
}
/////////////////////////////////////////////////////
class Player {
int getShoot() {
Scanner scanner = new Scanner(System.in);
while (true) {
if (scanner.hasNextInt()) {
shoot = scanner.nextInt();
break;
} else {
String temp = scanner.nextLine();
}
}
System.out.println("Ваш выстрел: " + shoot);
return shoot;
}
}
////////////////////////////////////////////////////
class Ship {
int position02;
int position;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment