Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.Scanner;
- public class SeaBattle2 {
- private static final int FIELD_SIZE = 15;
- private static final int SHIP_SIZE = 3;
- private static final int SHIPS_QUANTITY = 3;
- private static char[] gameField = new char[FIELD_SIZE];
- private static int[] shipsOnField = new int[FIELD_SIZE];
- private static int shipFieldsCount = SHIP_SIZE * SHIPS_QUANTITY;
- private static Scanner scanner = new Scanner(System.in);
- public static void main(String[] args) {
- startGame();
- }
- private static void startGame() {
- initialize();
- System.out.println("Игра Морской бой");
- do {
- showGameField();
- int index;
- while (true) {
- System.out.printf("Задайте ячейку от 0 до %d:%n", FIELD_SIZE - 1);
- if (scanner.hasNextInt()) {
- index = scanner.nextInt();
- scanner.nextLine();
- break;
- } else {
- scanner.nextLine();
- }
- }
- if (index < 0 || index > FIELD_SIZE - 1) {
- continue;
- }
- switch (gameField[index]) {
- case 'X':
- gameField[index] = '#';
- shipFieldsCount--;
- if (isKilled(index)) {
- System.out.println("Убит!");
- } else {
- System.out.println("Ранен!");
- }
- break;
- case '*':
- case '#':
- System.out.println("Уже стреляли.");
- break;
- default:
- System.out.println("Промах.");
- gameField[index] = '*';
- }
- } while (shipFieldsCount > 0);
- System.out.println("Победа! Все корабли потоплены.");
- System.out.println();
- showGameField();
- }
- private static void initialize() {
- Arrays.fill(gameField, '_');
- int leftBound = 0;
- int rightBound;
- int startIndex;
- int remainingQuantity = SHIPS_QUANTITY;
- while (remainingQuantity > 0) {
- rightBound = FIELD_SIZE - (SHIP_SIZE + 1) * (remainingQuantity - 1) - SHIP_SIZE;
- startIndex = getRandom(leftBound, rightBound + 1);
- for (int i = 0; i < SHIP_SIZE; i++) {
- gameField[startIndex + i] = 'X';
- shipsOnField[startIndex + i] = remainingQuantity;
- }
- leftBound = startIndex + SHIP_SIZE + 1;
- remainingQuantity--;
- }
- }
- private static void showGameField() {
- System.out.println(Arrays.toString(gameField));
- System.out.println();
- }
- private static int getRandom(int from, int to) {
- return (int) (from + Math.random() * (to - from));
- }
- private static boolean isKilled(int index) {
- int shipIndex = shipsOnField[index];
- shipsOnField[index] = -1;
- for (int value : shipsOnField) {
- if (value == shipIndex) {
- return false;
- }
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement