Guest User

Untitled

a guest
Apr 20th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.75 KB | None | 0 0
  1. /*На примере плоского Морского боя из прошлой лекции
  2. 0. Попробуйте его восстановить по памяти. Если не получится – подглядите в лекции
  3. 1. Сделайте так, чтобы корабль располагался в случайной ячейке
  4. 2. Сделайте так, чтобы корабль был не однопалубный, а, например, трехпалубный
  5. 3. Сложное задание (* необязательное) Сделайте так, чтобы кораблей было несколько (например, три)!*/
  6.  
  7. import java.util.Scanner;
  8.  
  9. public class SeaBattle {
  10.  
  11. public static void main(String[] args) {
  12. doGame();
  13. }
  14.  
  15. public static void doGame() {
  16. int MAX_SIZE = 10; // размер поля
  17. int shipLength = 1; // длина корабля(ей)
  18. int shipCount = 3; // кол-во кораблей
  19. int[] shipPosition = new int[shipCount];
  20. char[] cells;
  21. boolean cellsShipFlag = false;
  22.  
  23. // проверка - а можно ли?
  24. if (shipCount*shipLength + (shipCount-1) > MAX_SIZE ) {
  25. System.out.printf("Невозможно разместить %d кораблей длиной=%d на поле размером %d", shipCount, shipLength, MAX_SIZE);
  26. return;
  27. }
  28.  
  29. // инициализация
  30. for (int j = 0; j < shipCount; j++) {
  31. //System.out.println("!!!!!!!!j=" + j);
  32. boolean isValid = true;
  33. do {
  34. isValid = true;
  35. shipPosition[j] = (int) (Math.random()*(MAX_SIZE));
  36. // проверка - выход за границы поля
  37. if ((shipPosition[j] + shipLength) > MAX_SIZE ) {
  38. shipPosition[j] = MAX_SIZE - shipLength;
  39. }
  40. // проверка - валидность расположения (не соприкасаться и не перекрыывть)
  41. // а так же несовпадения (уникальность) координат
  42. for (int k = 0; k < j; k++) {
  43. if (j!=k) { // не проверять себя
  44. if ((shipPosition[k]-1<=shipPosition[j] && shipPosition[j]<=shipPosition[k]+shipLength)
  45. || (shipPosition[k]-1<=shipPosition[j]+shipLength-1
  46. && shipPosition[j]+shipLength-1<=shipPosition[k]+shipLength)
  47. ) {
  48. isValid = false;
  49. break;
  50. }
  51. }
  52. }
  53. } while (!isValid);
  54. }
  55.  
  56. // заполнение
  57. cells = new char[MAX_SIZE];
  58. for (int i = 0; i <cells.length; i++) {
  59. cellsShipFlag = false;
  60. for (int j = 0; j < shipCount; j++) {
  61. if (shipPosition[j]<=i && i<=shipPosition[j]+shipLength-1) {
  62. cellsShipFlag = true;
  63. break;
  64. }
  65. }
  66. cells[i] = (cellsShipFlag) ? 'x' : '.';
  67. }
  68.  
  69.  
  70. // игра
  71. Scanner scanner = new Scanner(System.in);
  72. int shoot = 0;
  73. do {
  74. // ввод
  75. while (true) {
  76. if (scanner.hasNextInt()) {
  77. shoot = scanner.nextInt();
  78. break;
  79. }
  80. else {
  81. String s = scanner.nextLine();
  82. }
  83. }
  84.  
  85. // проверка
  86. if (shoot>MAX_SIZE) {
  87. System.out.println("Выстрел за пределами поля!");
  88. }
  89. else {
  90. switch (cells[shoot]) {
  91. case '.' :
  92. cells[shoot] = '*';
  93. System.out.println("Промах");
  94. break;
  95. case 'x' :
  96. cells[shoot] = '#';
  97. System.out.println("Попадание!");
  98. break;
  99. default :
  100. System.out.println("Уже стрелял!");
  101. }
  102. }
  103. // проверка - есть ли еще во что стрелять?
  104. boolean victoria = true;
  105. for (int i = 0; i < cells.length; i++) {
  106. if (cells[i]=='x') {
  107. victoria = false;
  108. break;
  109. }
  110. }
  111. if (victoria) {
  112. System.out.println("Победа!");
  113. break;
  114. }
  115. } while (true);
  116.  
  117. }
  118.  
  119. }
Add Comment
Please, Sign In to add comment