diff --git a/src/edu/androidclub/Application.java b/src/edu/androidclub/Application.java index 4978d01..20b2526 100644 --- a/src/edu/androidclub/Application.java +++ b/src/edu/androidclub/Application.java @@ -3,6 +3,7 @@ import edu.androidclub.domain.Item; import edu.androidclub.domain.ItemBox; +import java.util.Scanner; import java.util.Stack; /* @@ -59,49 +60,106 @@ private void test() { // Создадим наборы продуктов для ячеек схемы (пустые) Stack colas = new Stack<>(); // 1 Stack sprites = new Stack<>(); // 2 + Stack fantas = new Stack<>(); // 2 + Stack milkas = new Stack<>(); // 2 // Заполним наши наборы продуктами colas.push(new Cola()); colas.push(new Cola()); colas.push(new Cola()); + sprites.push(new Sprite()); sprites.push(new Sprite()); + fantas.push(new Fanta()); + fantas.push(new Fanta()); + fantas.push(new Fanta()); + + milkas.push(new Milka()); + milkas.push(new Milka()); + milkas.push(new Milka()); + milkas.push(new Milka()); + milkas.push(new Milka()); + milkas.push(new Milka()); + // Создадим объекты-координаты наших наборов продуктов в схеме Coordinates colaCors = new Coordinates(1, 1); Coordinates spriteCors = new Coordinates(1, 2); + Coordinates fantaCors = new Coordinates(3, 0); + Coordinates milkaCors = new Coordinates(2, 2); // Поместии наборы продуктов в схему itemScheme.put(colaCors, colas); itemScheme.put(spriteCors, sprites); + itemScheme.put(fantaCors, fantas); + itemScheme.put(milkaCors, milkas); + //itemScheme.put(colaCors, sprites); + + // Создадим нашу витрину (коробку продуктов) на основании схемы ItemBox itemBox = new ProductsBox(itemScheme); // Протестируем схему - заставим витрину выдавать объекты на заданных координатах - System.out.println( // Напечатать в консоль - itemBox.emit( // Выдать предмет - new Coordinates(1, 1) // Указываем координату - ) - .getName() // Получить имя предмета - ); // OK - System.out.println(itemBox.emit(new Coordinates(1, 1)).getName()); // OK - System.out.println(itemBox.emit(new Coordinates(1, 1)).getName()); // OK - - System.out.println(itemBox.emit(new Coordinates(1, 1)).getName()); // FAIL - предметы кончились в ячейке + + // Тест выдачи и проверки на пустоту слота + Scanner s = new Scanner(System.in); + s.nextLine(); + itemBox.emit(new Coordinates(1, 1)); + s.nextLine(); + itemBox.emit(new Coordinates(1, 1)); + s.nextLine(); + itemBox.emit(new Coordinates(1, 1)); + s.nextLine(); + itemBox.emit(new Coordinates(1, 1)); + + // Тест некорректных координат + s.nextLine(); + itemBox.emit(new Coordinates(25, 25)); + + // Тратим другие продукты + s.nextLine(); + itemBox.emit(new Coordinates(2, 2)); + s.nextLine(); + itemBox.emit(new Coordinates(2, 2)); + s.nextLine(); + itemBox.emit(new Coordinates(2, 2)); + + s.nextLine(); + itemBox.emit(new Coordinates(3, 0)); + s.nextLine(); + itemBox.emit(new Coordinates(3, 0)); + s.nextLine(); + itemBox.emit(new Coordinates(3, 0)); + s.nextLine(); + itemBox.emit(new Coordinates(3, 0)); + + } // Опишем Колу как подкласс Предмета public static class Cola extends Item { public Cola() { - super("Cola"); // Вызов конструктора класса-родителя (класса Item) + super("Cola", 45); // Вызов конструктора класса-родителя (класса Item) } } // Опишем Спрайт как подкласс Предмета public static class Sprite extends Item { public Sprite() { - super("Sprite"); + super("Sprite", 65); + } + } + + public static class Fanta extends Item { + public Fanta() { + super("Fanta", 125); + } + } + + public static class Milka extends Item { + public Milka() { + super("Milka", 5); } } } diff --git a/src/edu/androidclub/ProductsBox.java b/src/edu/androidclub/ProductsBox.java index 6e71494..fcdbed9 100644 --- a/src/edu/androidclub/ProductsBox.java +++ b/src/edu/androidclub/ProductsBox.java @@ -11,26 +11,74 @@ public class ProductsBox implements ItemBox { private ItemInfoScheme scheme; + private VoidItem voidItem; + public Screen screen; + // Требует схему при создании public ProductsBox(ItemInfoScheme scheme) { this.scheme = scheme; + this.voidItem = new VoidItem(); + this.screen = new Screen(); + screen.update(scheme); + } + + private Stack getItems(Coordinates coordinates){ + try{ + Stack items = scheme.get(coordinates); + return items; + } + // неверные координаты + catch(NullPointerException e){ + screen.setNotice("Ошибка!"); + screen.update(scheme); + return null; + } } // Выдать предмет по координатам @Override public Item emit(Coordinates coordinates) { // Получить стопку предметов на позиции - Stack items = scheme.get(coordinates); + Stack items = getItems(coordinates); + if (this.amount(coordinates) > 0) { + // Возвращаем верхний элемент и удаляем его с вершины стопки + Item top = items.pop(); + screen.setNotice("продан " + top.getName() + " на (" + coordinates.getRow() + ", " + coordinates.getColumn() + ") за " + top.getCost() + " денег"); + screen.update(scheme); + return top; - // Если пусто - возвращаем пустоту - if (items.empty()) { - return null; } + else if(this.amount(coordinates) == -1){ + screen.setNotice("Обращение к несуществующей/пустой ячейке"); + screen.update(scheme); + return voidItem; + } + else{ + // Вернуть пустой предмет? о_О + // Тут возникла проблема, т.к. вне зависимости от условий мы вызываем метод getName() + // и я не знал, как вырутиться + // Мне кажется, я сделал костыль + screen.setNotice("Ячейка (" + coordinates.getRow() + ", " + coordinates.getColumn() + ") пуста!"); + screen.update(scheme); + return voidItem; + } + } - // Возвращаем верхний элемент и удаляем его с вершины стопки - return items.pop(); + @Override + public int amount(Coordinates coordinates) { + // Получить стопку предметов на позиции + Stack items = getItems(coordinates); + if(items != null) { + // Вернуть количество + return items.size(); + } + else{ + return -1; + } } + + } diff --git a/src/edu/androidclub/Screen.java b/src/edu/androidclub/Screen.java new file mode 100644 index 0000000..52adc9c --- /dev/null +++ b/src/edu/androidclub/Screen.java @@ -0,0 +1,119 @@ +package edu.androidclub; + +import edu.androidclub.domain.AppScreen; + +import java.util.StringJoiner; + +/** + * Created by WinDA on 22.11.2016. + */ +public class Screen implements AppScreen{ + String notice; + + public Screen(){ + setNotice("Купи еду"); + } +/* + [Сообщение] + + |----------|----------| + |Спрайт[65]| | + |----------|----------| + |Фанта[55] | | + |----------|----------| + */ + + @Override + public void update(ItemInfoScheme scheme) { + clear(); + System.out.println(getNotice()); // Текст сверху + + // Определяем размеры прямоугольника и ячейки + int maxRow = 0; + int maxCol = 0; + int minRow = 0; + int minCol = 0; + int maxLength = 1; + for(Coordinates i: scheme.keySet()){ + // ищем наибольшую и наименьшую Y + if(i.getColumn() > maxCol){ + maxCol = i.getColumn(); + } + else if(i.getColumn() < minCol){ + minCol = i.getColumn(); + } + + // ищем наибольший и наименьший X + if(i.getRow() > maxRow){ + maxRow = i.getRow(); + } + else if(i.getRow() < minRow){ + minRow = i.getRow(); + } + + if(scheme.get(i) != null && scheme.get(i).size() > 0){ + if(scheme.get(i).lastElement().getName().length() > maxLength){ + maxLength = scheme.get(i).lastElement().getName().length(); + } + } + } + + maxLength += 10; // Добавить места для цены и количества + + String emptyCell = multiply(" ", maxLength); + + // Начинаем рисование + String barrier = "|" + multiply("-", maxLength); + System.out.print(multiply(barrier, maxCol - minCol)); + System.out.println("|"); + for(int i = minRow; i <= maxRow; i++){ + for(int j = minCol; j <= maxCol; j++){ + System.out.print("|"); + + Coordinates coordinates = new Coordinates(i, j); + + if(scheme.get(coordinates) != null && scheme.get(coordinates).size() > 0){ + String name = scheme.get(coordinates).lastElement().getName(); + int cost = scheme.get(coordinates).lastElement().getCost(); + int amount = scheme.get(coordinates).size(); + + //Это костыль для красоты + int s1 = ("" + cost).length(); + int s2 = ("" + amount).length(); + + System.out.print(name + "[" + cost + "]" + "(" + amount + ")" + multiply(" ", maxLength - name.length() - 4 - s1 - s2)); + } + else{ + System.out.print(emptyCell); + } + } + System.out.println("|"); + System.out.print(multiply(barrier, maxCol - minCol)); + System.out.println("|"); + } + } + + @Override + public void setNotice(String text) { + this.notice = " [" + text + "]"; + } + + @Override + public String getNotice() { + return this.notice; + } + + @Override + public void clear() { + System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); + } + + private String multiply(String s, int amount){ + String res = new String(s); + for(int j = 0; j < amount; j++){ + res = res + s; + } + return res.toString(); + } + +} diff --git a/src/edu/androidclub/VoidItem.java b/src/edu/androidclub/VoidItem.java new file mode 100644 index 0000000..f3304cc --- /dev/null +++ b/src/edu/androidclub/VoidItem.java @@ -0,0 +1,13 @@ +package edu.androidclub; + +import edu.androidclub.domain.Item; + +/** + * Created by WinDA on 22.11.2016. + */ +// пустой предмет +public class VoidItem extends Item { + public VoidItem() { + super("Пустота", 0); // Вызов конструктора класса-родителя (класса Item) + } +} diff --git a/src/edu/androidclub/domain/AppScreen.java b/src/edu/androidclub/domain/AppScreen.java index 46dbc09..76a6f54 100644 --- a/src/edu/androidclub/domain/AppScreen.java +++ b/src/edu/androidclub/domain/AppScreen.java @@ -1,9 +1,14 @@ package edu.androidclub.domain; +import edu.androidclub.ItemInfoScheme; + /* * Интерфейс, представляющий собой описание функционал экрана аппарата * */ public interface AppScreen { - void printText(String text); + String notice = ""; + void setNotice(String s); + String getNotice(); + void update(ItemInfoScheme scheme); void clear(); } diff --git a/src/edu/androidclub/domain/Item.java b/src/edu/androidclub/domain/Item.java index 87e3204..59d3609 100644 --- a/src/edu/androidclub/domain/Item.java +++ b/src/edu/androidclub/domain/Item.java @@ -4,13 +4,21 @@ // Он тоже неизменяемый - т.к. все поля final public abstract class Item { private final String name; + private final int cost; - public Item(String name) { + + public Item(String name, int cost) { this.name = name; + this.cost = cost; } // Получить имя public String getName() { return name; } + + // Получить цену + public int getCost() { + return cost; + } } diff --git a/src/edu/androidclub/domain/ItemBox.java b/src/edu/androidclub/domain/ItemBox.java index dd93439..a22eaff 100644 --- a/src/edu/androidclub/domain/ItemBox.java +++ b/src/edu/androidclub/domain/ItemBox.java @@ -9,5 +9,7 @@ public interface ItemBox { /* Выдать предмет по его координатам */ Item emit(Coordinates coordinates); + /* Количество предметов по координатам */ + int amount(Coordinates coordinates); }