/
anya155
/
Bingo
Обзор
Документация
Войти
/
anya155
/
Bingo
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
UI/ConsoleUI.cs
391 строка
15 KB
Элина Зезаева
Изменения вывода режима любой строки
20 дек 2025, 14:45
20 дек 2025, 14:45
d7290ed
Код
Авторство
О чём код?
using LotoGame.GameLogic; using LotoGame.Models; namespace LotoGame.UI { /// <summary> /// Пользовательский интерфейс для консоли. /// </summary> public class ConsoleUI { private readonly ConsoleColor[] _cardColors = { ConsoleColor.Green, ConsoleColor.White, ConsoleColor.DarkGray }; /// <summary> /// Показывает анимированный текст. /// </summary> /// <param name="text">Текст для отображения.</param> /// <param name="delay">Задержка между символами.</param> public void ShowAnimatedText(string text, int delay = 50) { foreach (char c in text) { Console.Write(c); Thread.Sleep(delay); } Console.WriteLine(); } /// <summary> /// Очищает экран. /// </summary> public void ClearScreen() { Console.Clear(); } /// <summary> /// Выводит заголовок. /// </summary> /// <param name="title">Текст заголовка.</param> public void PrintHeader(string title) { Console.WriteLine(new string('═', 60)); Console.WriteLine($" {title}"); Console.WriteLine(new string('═', 60)); } /// <summary> /// Выводит сообщение. /// </summary> /// <param name="message">Текст сообщения.</param> /// <param name="color">Цвет текста.</param> public void PrintMessage(string message, ConsoleColor color = ConsoleColor.White) { Console.ForegroundColor = color; Console.WriteLine(message); Console.ResetColor(); } /// <summary> /// Выводит предупреждение. /// </summary> /// <param name="message">Текст предупреждения.</param> public void PrintWarning(string message) { PrintMessage($"⚠️ {message}", ConsoleColor.Yellow); } /// <summary> /// Выводит сообщение об ошибке. /// </summary> /// <param name="message">Текст ошибки.</param> public void PrintError(string message) { PrintMessage($"❌ {message}", ConsoleColor.Red); } /// <summary> /// Выводит сообщение об успехе. /// </summary> /// <param name="message">Текст сообщения.</param> public void PrintSuccess(string message) { PrintMessage($"✅ {message}", ConsoleColor.Green); } /// <summary> /// Отображает карточку игрока. /// </summary> /// <param name="card">Карточка для отображения.</param> /// <param name="playerName">Имя игрока.</param> /// <param name="lastMarkedNumber">Последнее отмеченное число.</param> public void DisplayCard(Card card, string playerName = "", int lastMarkedNumber = 0) { if (!string.IsNullOrEmpty(playerName)) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine($"\n🎫 Карточка игрока: {playerName}"); Console.ResetColor(); Console.WriteLine(new string('─', 53)); } for (int i = 0; i < 3; i++) { Console.Write(" "); for (int col = 0; col < 9; col++) { if (card.Numbers[i][col] == 0) { Console.Write(" . "); } else if (card.Marked[i][col]) { Console.ForegroundColor = _cardColors[0]; Console.Write($" [{card.Numbers[i][col],2}] "); Console.ResetColor(); } else { Console.Write($" {card.Numbers[i][col],2} "); } } Console.WriteLine(); } if (!string.IsNullOrEmpty(playerName)) { Console.WriteLine(new string('─', 53)); } } /// <summary> /// Отображает карточку победителя. /// </summary> /// <param name="winner">Победитель игры.</param> public void DisplayWinnerCard(Player winner) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"\n🎫 Карточка победителя {winner.Name}:"); Console.ResetColor(); Console.WriteLine(new string('═', 53)); for (int i = 0; i < 3; i++) { Console.Write(" "); for (int col = 0; col < 9; col++) { if (winner.Card.Numbers[i][col] == 0) { Console.Write(" . "); } else if (winner.Card.Marked[i][col]) { Console.ForegroundColor = ConsoleColor.Green; Console.BackgroundColor = ConsoleColor.DarkGreen; Console.Write($" [{winner.Card.Numbers[i][col],2}] "); Console.ResetColor(); } else { Console.Write($" {winner.Card.Numbers[i][col],2} "); } } Console.WriteLine(); } Console.WriteLine(new string('═', 53)); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"🎯 Очков набрано: {winner.Score}"); Console.ResetColor(); } /// <summary> /// Отображает пример победной карточки. /// </summary> public void DisplayVictoryCard() { Console.WriteLine(); Console.WriteLine(new string('═', 53)); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("✨ Задача: закройте любую строку на своей карточке!"); Console.ResetColor(); } /// <summary> /// Обновляет отображение карточки. /// </summary> /// <param name="player">Игрок.</param> /// <param name="markedNumber">Отмеченное число.</param> public void UpdateCardDisplay(Player player, int markedNumber) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"\n✨ Обновленная карточка {player.Name}:"); Console.ResetColor(); Console.WriteLine(new string('─', 53)); for (int i = 0; i < 3; i++) { Console.Write(" "); for (int col = 0; col < 9; col++) { if (player.Card.Numbers[i][col] == 0) { Console.Write(" . "); } else if (player.Card.Marked[i][col]) { if (player.Card.Numbers[i][col] == markedNumber) { Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.Green; Console.Write($" [{player.Card.Numbers[i][col],2}] "); Console.ResetColor(); } else { Console.ForegroundColor = ConsoleColor.Green; Console.Write($" [{player.Card.Numbers[i][col],2}] "); Console.ResetColor(); } } else { Console.Write($" {player.Card.Numbers[i][col],2} "); } } Console.WriteLine(); } Console.WriteLine(new string('─', 53)); Thread.Sleep(300); } /// <summary> /// Отображает текущее состояние игры. /// </summary> /// <param name="game">Текущая игра.</param> /// <param name="currentPlayer">Текущий игрок.</param> /// <param name="playerNumber">Номер игрока.</param> public void DisplayGameState(Game game, Player? currentPlayer = null, int playerNumber = 1) { ClearScreen(); Console.ForegroundColor = ConsoleColor.Magenta; PrintHeader($"🎲 ИГРА В ЛОТО - Ход {game.CurrentTurn} 🎲"); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"🎲 Осталось бочонков: {game.BarrelBag.GetRemainingCount()}"); Console.ResetColor(); if (game.LastDrawnBarrel.HasValue) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine($"🎯 Последний бочонок: [{game.LastDrawnBarrel.Value}]"); Console.ResetColor(); } Console.WriteLine(new string('─', 60)); if (currentPlayer != null) { ConsoleColor playerColor = playerNumber == 1 ? ConsoleColor.Green : ConsoleColor.Blue; Console.ForegroundColor = playerColor; string playerInfo = $"{currentPlayer.Name} (Игрок {playerNumber}, очки: {currentPlayer.Score})"; DisplayCard(currentPlayer.Card, playerInfo); Console.ResetColor(); Console.WriteLine(); } else { for (int i = 0; i < game.Players.Count; i++) { ConsoleColor playerColor = i == 0 ? ConsoleColor.Green : ConsoleColor.Blue; Console.ForegroundColor = playerColor; string playerInfo = $"{game.Players[i].Name} (Игрок {i + 1}, очки: {game.Players[i].Score})"; DisplayCard(game.Players[i].Card, playerInfo); Console.ResetColor(); Console.WriteLine(); } } } /// <summary> /// Считывает строку от пользователя. /// </summary> /// <param name="prompt">Подсказка.</param> /// <returns>Введенная строка.</returns> public string ReadString(string prompt) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Write($"{prompt}: "); Console.ResetColor(); return Console.ReadLine()?.Trim() ?? string.Empty; } /// <summary> /// Считывает целое число от пользователя. /// </summary> /// <param name="prompt">Подсказка.</param> /// <param name="min">Минимальное значение.</param> /// <param name="max">Максимальное значение.</param> /// <returns>Введенное число.</returns> public int ReadInt(string prompt, int min = int.MinValue, int max = int.MaxValue) { while (true) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Write($"{prompt}: "); Console.ResetColor(); string input = Console.ReadLine()?.Trim() ?? string.Empty; if (int.TryParse(input, out int result)) { if (result >= min && result <= max) { return result; } PrintWarning($"Число должно быть от {min} до {max}"); } else { PrintWarning("Введите целое число"); } } } /// <summary> /// Считывает ответ да/нет от пользователя. /// </summary> /// <param name="prompt">Подсказка.</param> /// <returns>True, если ответ "да".</returns> public bool ReadYesNo(string prompt) { while (true) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Write($"{prompt} (да/нет): "); Console.ResetColor(); string input = Console.ReadLine()?.Trim().ToLower() ?? string.Empty; if (input == "да" || input == "д" || input == "y" || input == "yes") { return true; } if (input == "нет" || input == "н" || input == "n" || input == "no") { return false; } PrintWarning("Введите 'да' или 'нет'"); } } /// <summary> /// Ожидает нажатия любой клавиши. /// </summary> /// <param name="message">Сообщение для отображения.</param> public void WaitForAnyKey(string message = "⌨️ Нажмите любую клавишу для продолжения...") { Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine($"\n{message}"); Console.ResetColor(); Console.ReadKey(true); } /// <summary> /// Выводит разделитель. /// </summary> /// <param name="length">Длина разделителя.</param> /// <param name="symbol">Символ разделителя.</param> /// <param name="color">Цвет разделителя.</param> public void PrintSeparator(int length = 60, char symbol = '─', ConsoleColor color = ConsoleColor.DarkGray) { Console.ForegroundColor = color; Console.WriteLine(new string(symbol, length)); Console.ResetColor(); } } }