/
Vagabond132
/
TerrariaCourse
Обзор
Документация
Войти
/
Vagabond132
/
TerrariaCourse
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
Windows
ConsoleController/Game/ConsoleControllerGame.cs
213 строк
6 KB
Vagabond132
Комментарии добавлены
12 янв 2025, 15:30
12 янв 2025, 15:30
0078286
Код
Авторство
О чём код?
using ConsoleController.Menu; using ConsoleView.Game; using ConsoleView.Menu; using Model.Menu; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using View; namespace ConsoleController.Game { /// <summary> /// Контроллер игры в консоли /// </summary> public class ConsoleControllerGame : Controller.Menu.ControllerGame { /// <summary> /// Получение нажатий клавиш /// </summary> /// <param name="vKey">код клавиши</param> /// <returns></returns> [DllImport("user32.dll")] private static extern short GetAsyncKeyState(int vKey); /// <summary> /// Таймер для ломания блоков /// </summary> private static Stopwatch breakBlockTimer = new Stopwatch(); /// <summary> /// Необходимость выхода /// </summary> private volatile bool _shouldExit = false; /// <summary> /// Пауза ли сейчас /// </summary> private volatile bool _isPause = false; /// <summary> /// Представление игры /// </summary> private ConsoleGameView _gameViewConsole; /// <summary> /// Контроллер паузы /// </summary> private ConsolePauseController _pauseController; /// <summary> /// Консольное представления игры /// </summary> public ConsoleGameView GameViewConsole { get => _gameViewConsole; set => _gameViewConsole = value; } /// <summary> /// Пауза ли сейчас /// </summary> public bool IsPause { get => _isPause; set => _isPause = value; } /// <summary> /// Конструктор /// </summary> /// <param name="parPlayerName">имя игрока</param> public ConsoleControllerGame(string parPlayerName) { Game = new Model.GameComponents.GameModel(parPlayerName); _gameViewConsole = new ConsoleGameView(Game); } /// <summary> /// Обновление /// </summary> public override void Update() { Thread modelDrawing = new Thread(Drawing); Thread modelEngine = new Thread(Engine); modelDrawing.Start(); modelEngine.Start(); modelDrawing.Join(); modelEngine.Join(); } /// <summary> /// Отрисовка UI /// </summary> private void Drawing() { while (!_shouldExit && !IsPause) { _gameViewConsole.Draw(); } } /// <summary> /// Работа логики игры /// </summary> private void Engine() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); long previousTime = stopwatch.ElapsedMilliseconds; while (!_shouldExit) { // Обработка паузы if (IsPause) { while (Console.KeyAvailable) { Console.ReadKey(true); } _pauseController = new ConsolePauseController(Game.Player.Name, Game.Player.Score); _pauseController.Start(); if (_pauseController.NeedExit) { //ControllerMenuMainConsole().Start(); _shouldExit = false; break; } else { IsPause = false; } } long currentTime = stopwatch.ElapsedMilliseconds; long deltaTime = currentTime - previousTime; previousTime = currentTime; KeyEventHandler(deltaTime); _gameViewConsole.Draw(); Game.UpdatePlayerPosition(deltaTime); } } /// <summary> /// Начало /// </summary> public override void Start() { Update(); } /// <summary> /// Обработчик события нажатия на кнопку /// </summary> void KeyEventHandler(float parDeltaTime) { _shouldExit = false; if (!breakBlockTimer.IsRunning) { breakBlockTimer.Start(); } if (IsKeyPressed((int)ConsoleKey.A) || IsKeyPressed((int)ConsoleKey.LeftArrow)) { Game.GoLeft(parDeltaTime); } if (IsKeyPressed((int)ConsoleKey.D) || IsKeyPressed((int)ConsoleKey.RightArrow)) { Game.GoRight(parDeltaTime); } if (IsKeyPressed((int)ConsoleKey.Spacebar)) { Game.Jump(); } if (IsKeyPressed((int)ConsoleKey.E)) { // Ломаем блоки с паузой if (breakBlockTimer.ElapsedMilliseconds >= 300) // 1 секунда { Game.BreakBlock(); breakBlockTimer.Restart(); // Перезапускаем таймер } } if (IsKeyPressed((int)ConsoleKey.W)) { // Ломаем блоки с паузой if (breakBlockTimer.ElapsedMilliseconds >= 300) // 1 секунда { Game.BreakBlocksAbove(); breakBlockTimer.Restart(); // Перезапускаем таймер } } if (IsKeyPressed((int)ConsoleKey.S)) { // Ломаем блоки с паузой if (breakBlockTimer.ElapsedMilliseconds >= 300) // 1 секунда { Game.BreakBlocksBelow(); breakBlockTimer.Restart(); // Перезапускаем таймер } } if (IsKeyPressed((int)ConsoleKey.Escape)) { _isPause = true; } } /// <summary> /// Проверяет, нажата ли клавиша /// </summary> /// <param name="vKey">Код клавиши</param> /// <returns>True, если клавиша нажата</returns> private bool IsKeyPressed(int vKey) { return (GetAsyncKeyState(vKey) & 0x8000) != 0; } } }