Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*На примере плоского Морского боя из прошлой лекции
- 0. Попробуйте его восстановить по памяти. Если не получится – подглядите в лекции
- 1. Сделайте так, чтобы корабль располагался в случайной ячейке
- 2. Сделайте так, чтобы корабль был не однопалубный, а, например, трехпалубный
- 3. Сложное задание (* необязательное) Сделайте так, чтобы кораблей было несколько (например, три)!*/
- import java.util.Scanner;
- public class SeaBattle {
- public static void main(String[] args) {
- doGame();
- }
- public static void doGame() {
- int MAX_SIZE = 10; // размер поля
- int shipLength = 1; // длина корабля(ей)
- int shipCount = 3; // кол-во кораблей
- int[] shipPosition = new int[shipCount];
- char[] cells;
- boolean cellsShipFlag = false;
- // проверка - а можно ли?
- if (shipCount*shipLength + (shipCount-1) > MAX_SIZE ) {
- System.out.printf("Невозможно разместить %d кораблей длиной=%d на поле размером %d", shipCount, shipLength, MAX_SIZE);
- return;
- }
- // инициализация
- for (int j = 0; j < shipCount; j++) {
- //System.out.println("!!!!!!!!j=" + j);
- boolean isValid = true;
- do {
- isValid = true;
- shipPosition[j] = (int) (Math.random()*(MAX_SIZE));
- // проверка - выход за границы поля
- if ((shipPosition[j] + shipLength) > MAX_SIZE ) {
- shipPosition[j] = MAX_SIZE - shipLength;
- }
- // проверка - валидность расположения (не соприкасаться и не перекрыывть)
- // а так же несовпадения (уникальность) координат
- for (int k = 0; k < j; k++) {
- if (j!=k) { // не проверять себя
- if ((shipPosition[k]-1<=shipPosition[j] && shipPosition[j]<=shipPosition[k]+shipLength)
- || (shipPosition[k]-1<=shipPosition[j]+shipLength-1
- && shipPosition[j]+shipLength-1<=shipPosition[k]+shipLength)
- ) {
- isValid = false;
- break;
- }
- }
- }
- } while (!isValid);
- }
- // заполнение
- cells = new char[MAX_SIZE];
- for (int i = 0; i <cells.length; i++) {
- cellsShipFlag = false;
- for (int j = 0; j < shipCount; j++) {
- if (shipPosition[j]<=i && i<=shipPosition[j]+shipLength-1) {
- cellsShipFlag = true;
- break;
- }
- }
- cells[i] = (cellsShipFlag) ? 'x' : '.';
- }
- // игра
- Scanner scanner = new Scanner(System.in);
- int shoot = 0;
- do {
- // ввод
- while (true) {
- if (scanner.hasNextInt()) {
- shoot = scanner.nextInt();
- break;
- }
- else {
- String s = scanner.nextLine();
- }
- }
- // проверка
- if (shoot>MAX_SIZE) {
- System.out.println("Выстрел за пределами поля!");
- }
- else {
- switch (cells[shoot]) {
- case '.' :
- cells[shoot] = '*';
- System.out.println("Промах");
- break;
- case 'x' :
- cells[shoot] = '#';
- System.out.println("Попадание!");
- break;
- default :
- System.out.println("Уже стрелял!");
- }
- }
- // проверка - есть ли еще во что стрелять?
- boolean victoria = true;
- for (int i = 0; i < cells.length; i++) {
- if (cells[i]=='x') {
- victoria = false;
- break;
- }
- }
- if (victoria) {
- System.out.println("Победа!");
- break;
- }
- } while (true);
- }
- }
Add Comment
Please, Sign In to add comment