Advertisement
Manavard

Untitled

Mar 4th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.61 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.*;
  4.  
  5. public class DotComBust {
  6. private GameHelper helper = new GameHelper();
  7. private ArrayList<DotCom> dotComList = new ArrayList<DotCom>();
  8. private int numOfGuesses = 0;
  9. // Оьъявляем и инициализируем переменные которые нам понадобятся.
  10.  
  11. private void setUpGame() {
  12. //создадим несколько "сайтов" и присвоим им адреса.
  13. DotCom one = new DotCom();
  14. one.setName("Pets.com");
  15. DotCom two = new DotCom();
  16. two.setName("eToys.com");
  17. DotCom three = new DotCom();
  18. three.setName("Go2.com");
  19. dotComList.add(one);
  20. dotComList.add(two);
  21. dotComList.add(three);
  22. // Создаем три обьекта ДотКом, даем им имена и помещаем в АррайЛист
  23.  
  24. System.out.println("Ваша цель - потопить три 'сайта'.");
  25. System.out.println("Mail.ru, Yandex.ru, Google.com");
  26. System.out.println("Попытайтесь потопить их за минимальное количество ходов");
  27. //Выводим краткие инструкции для пользователя
  28.  
  29. for (DotComToSet : dotComList) { //повторяем с каждым объектом ДотКом в списке
  30. ArrayList<String> newLocation = helper.placeDotCom(3); //запрашиваем у вспомогательного объекта адресс "сайта"
  31. dotComToSet.setLocationCells(newLocation); //вызываем сеттер из объекта ДотКом что бы передать ему местоположение, которое только что получили от вспомогательного объекта
  32. } // конец цикла Фор
  33. } //конец метода СетАпГейм
  34.  
  35. private void startPlaying() {
  36. while (!dotComList.isEmpty()) { //до тех пор, пока список объектов ДотКом не станет пустым
  37. String userGuess = helper.getUserInput("Сделайте ход"); //Получаем пользовательский ввод
  38. checkUserGuess(userGuess); //вызываем наш метод ЧекЮсерГуесс
  39. } //конец while
  40. finishGame(); //Вызываем наш метод finishGame
  41. } // конец метода startPlaying method
  42.  
  43. private void chekUserGuess(String userGuess) {
  44. numOfGuesses++;//Инкрементируем количество попыток которые сделал пользователь
  45. String result = "Мимо";//Подразумеваем промах, пока не выяснили обратного
  46.  
  47. for (DotCom dotComToTest : dotComsList) { //Повторяем это для всех объектов ДотКомв списке
  48. result = dotComToTest.chekYourself(userGuess); // Просим ДотКОм проверить ход пользователя, ищем попадание или потопление
  49. if (result.equals("Попал")) {
  50. break; //Выбираемся из цикла раньше времени, нет смысла проверять другие сайты
  51. }
  52. if (result.equals("Потопил")) {
  53. dotComList.remove(dotComToTest); //Ему пришел конец, так что удаляем его из списка сайтов и выходим из цикла.
  54. break;
  55. }
  56. } // конец цикла ФОР
  57. System.out.println(result); //Выводим для пользователя результат
  58. } // конец метода
  59.  
  60. private void finishGame() {
  61. System.out.println("Все сайты ушли ко дну! Ваши акции теперь ничего не стоят.");
  62. if (numOfGuesses <= 18) {
  63. System.out.println("Это заняло у вас всего " + numOfGuesses + "попыток.");
  64. System.out.println("Вы успели выбраться до того, как ваши вложения утонули.");
  65. } else {
  66. System.out.println("Это заняло у вас довольно много времени. " + numOfGuesses + "попыток.");
  67. System.out.println("Рыбы водят хороводы вокруг ваших вложений.");
  68. } //Выводим сообщение о том как пользователь прошел игру.
  69. } // конец метода
  70.  
  71. public static void main(String[] args) {
  72. DotComBust game = new DotComBust(); //Создаем игровой объект
  73. game.setUpGame(); //Говорим игровому объекту подготовить игру
  74. game.startPlaying(); //Говорим игровому объекту начать главный игровой цикл(продолжаем запрашивать пользовательский ввод и проверять полученные данные
  75. }
  76. }
  77.  
  78. package com.company;
  79.  
  80. import java.util.*;
  81.  
  82. public class DotCom {
  83. private ArrayList<String> locationCells;
  84. private String name;
  85.  
  86. public void setLocationCells(ArrayList<String> loc) {
  87. locationCells = loc;
  88. }
  89.  
  90. public void setName(String n) {
  91. name = n;
  92. }
  93.  
  94. public String checkYourself(String userInput) {
  95. String result = "Мимо";
  96. int index = locationCells.indexOf(userInput);
  97. if (index >= 0) {
  98. locationCells.remove(index);
  99.  
  100. if (locationCells.isEmpty()) {
  101. result = "Потопил";
  102. System.out.println("Ой! Вы потопили" + name + " : ( ");
  103. } else {
  104. result = "Попал";
  105. } //Конец ИФ
  106. }
  107. return result;
  108. }
  109. }
  110.  
  111.  
  112.  
  113.  
  114.  
  115. package com.company;
  116.  
  117. import java.io.*;
  118. import java.util.*;
  119.  
  120. public class GameHelper {
  121. private static final String alphabet = "abcdefg";
  122. private int gridLenght = 7;
  123. private int gridSize = 49;
  124. private int[] grid = new int[gridSize];
  125. private int comCount = 0;
  126.  
  127. public String getUserInput(String prompt) {
  128. String inputLine = null;
  129. System.out.print(prompt + " ");
  130. try {
  131. BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
  132. inputLine = is.readLine();
  133. if (inputLine.length() == 0) return null;
  134. } catch (IOException e) {
  135. System.out.println("IOException: " + e);
  136. }
  137. return inputLine.toLowerCase();
  138. }
  139.  
  140. public ArrayList<String> placeDotCom(int comSize) {
  141. ArrayList<String> alphaCells = new ArrayList<String>();
  142. String[] alphacoords = new String[comSize];
  143. String temp = null;
  144. int[] coords = new int[comSize];
  145. int attempts = 0;
  146. boolean success = false;
  147. int location = 0;
  148.  
  149. comCount++;
  150. int incr = 1;
  151. if ((comCount % 2) == 1) {
  152. incr = gridLenght;
  153. }
  154.  
  155. while (!success & attempts++ < 200) {
  156. location = (int) (Math.random() * gridSize);
  157. //System.out.println("пробуем" + location);
  158. int x = 0;
  159. success = true;
  160. while (success && x < comSize) {
  161. if (grid[location] == 0) {
  162. coords[x++] = location;
  163. location += incr;
  164. if (location >= gridSize) {
  165. success = false;
  166. }
  167. if (x > 0 && (location % gridLenght == 0)) {
  168. success = false;
  169. }
  170. } else {
  171. //System.out.println("используется " + location);
  172. success = false;
  173. }
  174. }
  175. }
  176.  
  177. int x = 0;
  178. int row = 0;
  179. int column = 0;
  180. //System.out.println("\n");
  181. while (x < comSize) {
  182. grid[coords[x]] = 1;
  183. row = (int) (coords[x] / gridLenght);
  184. column = coords[x] % gridLenght;
  185. temp = String.valueOf(alphabet.charAt(column));
  186.  
  187. alphaCells.add(temp.concat(Integer.toString(row)));
  188. x++;
  189. //System.out.print(" coord " + x + " = " + alphaCells.get(x-1));
  190. }
  191.  
  192. //System.out.println("\n");
  193.  
  194. return alphaCells;
  195. }
  196. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement