-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConsoleInterface.java
More file actions
289 lines (248 loc) · 11.7 KB
/
ConsoleInterface.java
File metadata and controls
289 lines (248 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package com.bankApp;
import java.util.Map;
import java.util.Scanner;
public class ConsoleInterface {
private final BankSystem bank;
private final Scanner scanner = new Scanner(System.in);
public ConsoleInterface(BankSystem bank) {
this.bank = bank;
}
public void run() {
boolean running = true;
while (running) {
if (bank.getCurrentUser() == null) {
showMainMenu();
} else {
showUserMenu();
}
}
}
private void showMainMenu() {
System.out.println("\n--- Главное меню ---");
System.out.println("1. Регистрация");
System.out.println("2. Вход");
System.out.println("3. Выход");
System.out.print("Выберите действие: ");
String choice = scanner.nextLine();
switch (choice) {
case "1" -> register();
case "2" -> login();
case "3" -> {
bank.saveData();
System.out.println("До свидания!");
System.exit(0);
}
default -> System.out.println("Неверный выбор");
}
}
private void register() {
System.out.print("Введите имя пользователя: ");
String username = scanner.nextLine();
System.out.print("Введите пароль: ");
String password = scanner.nextLine();
boolean success = bank.registerUser(username, password);
System.out.println(success ? "Регистрация прошла успешно" : "Пользователь уже существует");
}
private void login() {
System.out.print("Введите имя пользователя: ");
String username = scanner.nextLine();
System.out.print("Введите пароль: ");
String password = scanner.nextLine();
User user = bank.login(username, password);
if (user != null) {
bank.setCurrentUser(user);
System.out.println("Вы вошли как " + user.getUsername());
showBalanceAndMoons();
} else {
System.out.println("Неверные имя пользователя или пароль");
}
}
private void showUserMenu() {
User currentUser = bank.getCurrentUser();
showBalanceAndMoons();
System.out.println("\n--- Меню пользователя (" + currentUser.getUsername() + ") ---");
System.out.println("1. Перевести деньги");
System.out.println("2. Просмотреть подарки");
System.out.println("3. Отправить подарок");
System.out.println("4. Магазин");
if (isAdmin()) {
System.out.println("5. Добавить деньги (только для админа)");
System.out.println("6. Зачислить луны (только для админа)");
System.out.println("7. Выйти");
} else {
System.out.println("5. Выйти");
}
System.out.print("Выберите действие: ");
String choice = scanner.nextLine();
switch (choice) {
case "1" -> transferMoney();
case "2" -> viewGifts();
case "3" -> sendGift();
case "4" -> showShopMenu();
case "5" -> {
if (isAdmin()) addMoney();
else logout();
}
case "6" -> {
if (isAdmin()) addMoons();
else System.out.println("Неверный выбор");
}
case "7" -> {
if (isAdmin()) logout();
else System.out.println("Неверный выбор");
}
default -> System.out.println("Неверный выбор");
}
}
private void showShopMenu() {
User currentUser = bank.getCurrentUser();
showBalanceAndMoons();
while (true) {
System.out.println("\n--- Магазин ---");
System.out.println("1. Купить луны для себя");
System.out.println("2. Купить подарочный код");
System.out.println("3. Активировать подарочный код");
if (currentUser.getRole() == Role.ADMIN || currentUser.getRole() == Role.MERCHANT) {
System.out.println("4. Посмотреть все активные подарочные коды");
}
System.out.println("0. Вернуться в главное меню");
System.out.print("Выберите действие: ");
String choice = scanner.nextLine();
switch (choice) {
case "1" -> buyMoonsForSelf();
case "2" -> buyGiftCode();
case "3" -> redeemGiftCode();
case "4" -> {
if (currentUser.getRole() == Role.ADMIN || currentUser.getRole() == Role.MERCHANT) {
viewAllActiveGiftCodes();
} else {
System.out.println("Неверный выбор");
}
}
case "0" -> { return; }
default -> System.out.println("Неверный выбор");
}
}
}
private void buyMoonsForSelf() {
System.out.println("\n--- Пакеты лун ---");
for (int i = 0; i < Shop.MOON_PACKS.length; i++) {
System.out.println(i + 1 + ". " + Shop.MOON_PACKS[i][0] + " лун за " + Shop.MOON_PACKS[i][1] + " монет");
}
int packIndex = (int) readDouble("Выберите пакет: ") - 1;
if (Shop.buyMoonsForSelf(bank.getCurrentUser(), packIndex)) {
bank.saveData();
System.out.println("Покупка прошла успешно!");
} else {
System.out.println("Недостаточно средств или неверный пакет.");
}
}
private void buyGiftCode() {
System.out.println("\n--- Пакеты лун (для подарочного кода) ---");
for (int i = 0; i < Shop.MOON_PACKS.length; i++) {
double costWithMarkup = Shop.MOON_PACKS[i][1] * 1.2;
System.out.println(i + 1 + ". " + Shop.MOON_PACKS[i][0] + " лун за " + costWithMarkup + " монет");
}
int packIndex = (int) readDouble("Выберите пакет: ") - 1;
String code = Shop.buyGiftCode(bank.getCurrentUser(), packIndex, bank);
if (code != null) {
bank.saveData();
System.out.println("Подарочный код создан: " + code);
} else {
System.out.println("Недостаточно средств или неверный пакет.");
}
}
private void redeemGiftCode() {
System.out.print("Введите подарочный код: ");
String code = scanner.nextLine();
if (Shop.redeemGiftCode(bank.getCurrentUser(), code, bank)) {
bank.saveData();
System.out.println("Подарочный код активирован!");
} else {
System.out.println("Неверный или уже использованный код.");
}
}
private void viewAllActiveGiftCodes() {
Map<String, Integer> activeCodes = bank.getAllActiveGiftCodes();
if (activeCodes.isEmpty()) {
System.out.println("Нет активных кодов");
} else {
System.out.println("\n--- Активные подарочные коды ---");
for (Map.Entry<String, Integer> entry : activeCodes.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue() + " лун");
}
}
}
private void showBalanceAndMoons() {
User currentUser = bank.getCurrentUser();
System.out.println("\nБаланс: " + currentUser.getBalance() + " монет | Лун: " + currentUser.getMoons());
}
private boolean isAdmin() {
User user = bank.getCurrentUser();
return user != null && user.getRole() == Role.ADMIN;
}
private void transferMoney() {
System.out.print("Введите имя пользователя для перевода: ");
String toUsername = scanner.nextLine();
double amount = readDouble("Введите сумму для перевода: ");
boolean success = bank.transfer(toUsername, amount);
if (success) bank.saveData();
System.out.println(success ? "Перевод выполнен" : "Ошибка перевода");
}
private void addMoney() {
System.out.print("Введите имя пользователя для пополнения: ");
String username = scanner.nextLine();
double amount = readDouble("Введите сумму: ");
boolean success = bank.addMoney(username, amount);
System.out.println(success ? "Баланс пополнен" : "Ошибка пополнения");
}
private void viewGifts() {
User currentUser = bank.getCurrentUser();
System.out.println("\n--- Подарки ---");
if (currentUser.getGifts().isEmpty()) {
System.out.println("Подарков нет");
} else {
for (Gift gift : currentUser.getGifts()) {
System.out.println("- " + gift);
}
}
}
private void sendGift() {
System.out.println("\nДоступные подарки:");
for (Map.Entry<String, Gift> entry : Gift.getAvailableGifts().entrySet()) {
System.out.println("- " + entry.getKey() + " (" + entry.getValue().getCostInMoons() + " лун)");
}
System.out.print("Введите имя пользователя, которому отправить подарок: ");
String toUsername = scanner.nextLine();
System.out.print("Введите название подарка: ");
String giftName = scanner.nextLine();
boolean success = bank.sendGift(toUsername, giftName);
if (success) bank.saveData();
System.out.println(success ? "Подарок отправлен" : "Не удалось отправить подарок");
}
private void logout() {
bank.logout();
System.out.println("Вы вышли из аккаунта");
}
private double readDouble(String prompt) {
while (true) {
try {
System.out.print(prompt);
return Double.parseDouble(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Некорректное число. Попробуйте снова.");
}
}
}
private void addMoons() {
if (!isAdmin()) {
System.out.println("Недостаточно прав.");
return;
}
System.out.print("Введите имя пользователя для зачисления лун: ");
String username = scanner.nextLine();
int moonsAmount = (int) readDouble("Введите количество лун: ");
boolean success = bank.addMoonsToUser(username, moonsAmount);
System.out.println(success ? "Луны зачислены" : "Ошибка зачисления");
}
}