Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.*;
- public class DotComBust {
- private GameHelper helper = new GameHelper();
- private ArrayList<DotCom> dotComList = new ArrayList<DotCom>();
- private int numOfGuesses = 0;
- // Оьъявляем и инициализируем переменные которые нам понадобятся.
- private void setUpGame() {
- //создадим несколько "сайтов" и присвоим им адреса.
- DotCom one = new DotCom();
- one.setName("Pets.com");
- DotCom two = new DotCom();
- two.setName("eToys.com");
- DotCom three = new DotCom();
- three.setName("Go2.com");
- dotComList.add(one);
- dotComList.add(two);
- dotComList.add(three);
- // Создаем три обьекта ДотКом, даем им имена и помещаем в АррайЛист
- System.out.println("Ваша цель - потопить три 'сайта'.");
- System.out.println("Mail.ru, Yandex.ru, Google.com");
- System.out.println("Попытайтесь потопить их за минимальное количество ходов");
- //Выводим краткие инструкции для пользователя
- for (DotComToSet : dotComList) { //повторяем с каждым объектом ДотКом в списке
- ArrayList<String> newLocation = helper.placeDotCom(3); //запрашиваем у вспомогательного объекта адресс "сайта"
- dotComToSet.setLocationCells(newLocation); //вызываем сеттер из объекта ДотКом что бы передать ему местоположение, которое только что получили от вспомогательного объекта
- } // конец цикла Фор
- } //конец метода СетАпГейм
- private void startPlaying() {
- while (!dotComList.isEmpty()) { //до тех пор, пока список объектов ДотКом не станет пустым
- String userGuess = helper.getUserInput("Сделайте ход"); //Получаем пользовательский ввод
- checkUserGuess(userGuess); //вызываем наш метод ЧекЮсерГуесс
- } //конец while
- finishGame(); //Вызываем наш метод finishGame
- } // конец метода startPlaying method
- private void chekUserGuess(String userGuess) {
- numOfGuesses++;//Инкрементируем количество попыток которые сделал пользователь
- String result = "Мимо";//Подразумеваем промах, пока не выяснили обратного
- for (DotCom dotComToTest : dotComsList) { //Повторяем это для всех объектов ДотКомв списке
- result = dotComToTest.chekYourself(userGuess); // Просим ДотКОм проверить ход пользователя, ищем попадание или потопление
- if (result.equals("Попал")) {
- break; //Выбираемся из цикла раньше времени, нет смысла проверять другие сайты
- }
- if (result.equals("Потопил")) {
- dotComList.remove(dotComToTest); //Ему пришел конец, так что удаляем его из списка сайтов и выходим из цикла.
- break;
- }
- } // конец цикла ФОР
- System.out.println(result); //Выводим для пользователя результат
- } // конец метода
- private void finishGame() {
- System.out.println("Все сайты ушли ко дну! Ваши акции теперь ничего не стоят.");
- if (numOfGuesses <= 18) {
- System.out.println("Это заняло у вас всего " + numOfGuesses + "попыток.");
- System.out.println("Вы успели выбраться до того, как ваши вложения утонули.");
- } else {
- System.out.println("Это заняло у вас довольно много времени. " + numOfGuesses + "попыток.");
- System.out.println("Рыбы водят хороводы вокруг ваших вложений.");
- } //Выводим сообщение о том как пользователь прошел игру.
- } // конец метода
- public static void main(String[] args) {
- DotComBust game = new DotComBust(); //Создаем игровой объект
- game.setUpGame(); //Говорим игровому объекту подготовить игру
- game.startPlaying(); //Говорим игровому объекту начать главный игровой цикл(продолжаем запрашивать пользовательский ввод и проверять полученные данные
- }
- }
- package com.company;
- import java.util.*;
- public class DotCom {
- private ArrayList<String> locationCells;
- private String name;
- public void setLocationCells(ArrayList<String> loc) {
- locationCells = loc;
- }
- public void setName(String n) {
- name = n;
- }
- public String checkYourself(String userInput) {
- String result = "Мимо";
- int index = locationCells.indexOf(userInput);
- if (index >= 0) {
- locationCells.remove(index);
- if (locationCells.isEmpty()) {
- result = "Потопил";
- System.out.println("Ой! Вы потопили" + name + " : ( ");
- } else {
- result = "Попал";
- } //Конец ИФ
- }
- return result;
- }
- }
- package com.company;
- import java.io.*;
- import java.util.*;
- public class GameHelper {
- private static final String alphabet = "abcdefg";
- private int gridLenght = 7;
- private int gridSize = 49;
- private int[] grid = new int[gridSize];
- private int comCount = 0;
- public String getUserInput(String prompt) {
- String inputLine = null;
- System.out.print(prompt + " ");
- try {
- BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
- inputLine = is.readLine();
- if (inputLine.length() == 0) return null;
- } catch (IOException e) {
- System.out.println("IOException: " + e);
- }
- return inputLine.toLowerCase();
- }
- public ArrayList<String> placeDotCom(int comSize) {
- ArrayList<String> alphaCells = new ArrayList<String>();
- String[] alphacoords = new String[comSize];
- String temp = null;
- int[] coords = new int[comSize];
- int attempts = 0;
- boolean success = false;
- int location = 0;
- comCount++;
- int incr = 1;
- if ((comCount % 2) == 1) {
- incr = gridLenght;
- }
- while (!success & attempts++ < 200) {
- location = (int) (Math.random() * gridSize);
- //System.out.println("пробуем" + location);
- int x = 0;
- success = true;
- while (success && x < comSize) {
- if (grid[location] == 0) {
- coords[x++] = location;
- location += incr;
- if (location >= gridSize) {
- success = false;
- }
- if (x > 0 && (location % gridLenght == 0)) {
- success = false;
- }
- } else {
- //System.out.println("используется " + location);
- success = false;
- }
- }
- }
- int x = 0;
- int row = 0;
- int column = 0;
- //System.out.println("\n");
- while (x < comSize) {
- grid[coords[x]] = 1;
- row = (int) (coords[x] / gridLenght);
- column = coords[x] % gridLenght;
- temp = String.valueOf(alphabet.charAt(column));
- alphaCells.add(temp.concat(Integer.toString(row)));
- x++;
- //System.out.print(" coord " + x + " = " + alphaCells.get(x-1));
- }
- //System.out.println("\n");
- return alphaCells;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement