сделай так чтобы линия не мерцала #include <iostream> #include <vector> #include…
- User
сделай так чтобы линия не мерцала
#include #include #include #include #include #include <conio.h> // Для работы с _kbhit() и _getch() #include <windows.h> // Для получения размеров консоли и скрытия курсора
class Symbol { public: Symbol(char character = ' ', int color = 10) // Зеленый цвет по умолчанию : character(character), color(color) {}
char getCharacter() const { return character; } void setCharacter(char character) { this->character = character; } int getColor() const { return color; } // Получаем цвет символа void setColor(int color) { this->color = color; } // Устанавливаем цвет символаprivate: char character; // Символ, который будет отображаться int color; // Цвет символа };
class Line { public: Line(int length, bool epilepsyMode) : length(length), epilepsyMode(epilepsyMode) { // Устанавливаем единый случайный цвет для всей линии в режиме эпилепсии lineColor = epilepsyMode ? getRandomColor() : 10; // Зеленый цвет для обычного режима
// Генерируем случайные символы для линии for (int i = 0; i < length; ++i) { char randomChar = getRandomCharacter(); int color = (epilepsyMode ? lineColor : 10); // Используем единый цвет для режима эпилепсии symbols.push_back(Symbol(randomChar, color)); } // Устанавливаем цвет последнего символа (справа) в белый symbols[length - 1].setColor(15); } void move() { // Сдвигаем все символы влево for (int i = 0; i < length - 1; ++i) { symbols[i] = symbols[i + 1]; // Перемещаем символы влево } // Генерируем новый случайный символ в конце generateNewSymbol(); } char getCharacter(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getCharacter(); } return ' '; } int getColor(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getColor(); // Получаем цвет символа } return 7; // Цвет по умолчанию (белый) } void draw(int position, int consoleWidth, int startPosition) const { // Рисуем пустые строки перед линией для вертикального смещения for (int j = 0; j < startPosition; ++j) { std::cout << std::endl; } // Если позиция больше нуля, добавляем пробелы, чтобы сдвинуть линию вправо if (position >= 0) { std::cout << std::string(position, ' '); // Добавляем пробелы для смещения линии вправо } // Рисуем видимую часть линии int startIndex = std::max(0, -position); // Начальный индекс для рисования, если линия еще выползает int visibleLength = std::min(length - startIndex, consoleWidth - position); // Длина видимой части for (int i = startIndex; i < startIndex + visibleLength; ++i) { setColor(getColor(i)); // Устанавливаем цвет символа перед выводом std::cout << getCharacter(i); } std::cout << std::endl; }private: int length; // Длина линии std::vector symbols; // Вектор символов, составляющих линию bool epilepsyMode; // Режим эпилепсии int lineColor; // Единый цвет для всей линии в режиме эпилепсии
void generateNewSymbol() { char newChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; // Используем единый цвет в режиме эпилепсии symbols[length - 1] = Symbol(newChar, 15); // Последний символ белый symbols[length - 2].setColor(color); // Задаем единый цвет предпоследнему символу } static char getRandomCharacter() { // Массив символов, включая буквы и специальные символы const char characters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+[]{}|;':\",.<>?`~"; return characters[rand() % (sizeof(characters) - 1)]; // Генерируем случайный символ } static int getRandomColor() { return 1 + rand() % 15; // Возвращаем случайный цвет (1 - 15) } // Функция для установки цвета текста в консоли static void setColor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); }};
class AppManager { public: AppManager() : speed(1), length(10), epilepsyMode(false), running(true) { srand(static_cast(time(nullptr))); // Инициализация генератора случайных чисел getConsoleSize(); // Получаем размеры консоли }
// Метод для запуска приложения void start() { configureSettings(); // Запрос настроек у пользователя // Скрываем курсор перед началом симуляции HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); // Получаем дескриптор консоли CONSOLE_CURSOR_INFO cursorInfo; // Структура для хранения информации о курсоре GetConsoleCursorInfo(hConsole, &cursorInfo); // Получаем информацию о курсоре cursorInfo.bVisible = FALSE; // Скрыть курсор SetConsoleCursorInfo(hConsole, &cursorInfo); // Устанавливаем обновленные параметры курсора std::cout << "Matrix Simulation is starting..." << std::endl; // Сообщение о начале симуляции while (running) { // Пока программа работает int startPosition = rand() % (consoleHeight - 1); // Случайная вертикальная позиция Line line(length, epilepsyMode); // Создаем линию заданной длины с учетом режима эпилепсии int position = -length; // Начальная горизонтальная позиция линии (начинает за левым краем) // Пока линия полностью не исчезнет за правым краем экрана while (position < consoleWidth) { system("cls"); // Очищаем консоль (специфично для Windows) line.draw(position, consoleWidth, startPosition); // Рисуем линию std::this_thread::sleep_for(std::chrono::milliseconds(1000 / speed)); // Управляем скоростью line.move(); // Сдвигаем символы линии // Увеличиваем позицию, чтобы линия двигалась вправо ++position; // Проверяем, нажата ли клавиша 'q' для выхода if (_kbhit() && _getch() == 'q') { running = false; // Завершаем работу программы break; // Выходим из цикла } } // Если режим эпилепсии активен, добавляем задержку для эффекта if (epilepsyMode) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); // Добавляем задержку для эффекта } } }private: int speed; // Скорость падения линий int length; // Длина линий bool epilepsyMode; // Режим эпилепсии bool running; // Флаг работы программы int consoleWidth; // Ширина консоли int consoleHeight; // Высота консоли
void configureSettings() { std::cout << "Welcome to the Matrix Simulation!" << std::endl; // Приветственное сообщение // Ввод скорости while (true) { std::cout << "Enter speed (1 - 30): "; // Запрос скорости if (std::cin >> speed && speed >= 1 && speed <= 30) break; // Чтение значения скорости и проверка std::cin.clear(); // Сброс флага ошибки std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Очистка буфера ввода std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } // Ввод длины while (true) { std::cout << "Enter line length (1 - 30): "; // Запрос длины if (std::cin >> length && length >= 1 && length <= 30) break; // Чтение значения длины и проверка std::cin.clear(); // Сброс флага ошибки std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Очистка буфера ввода std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } // Ввод режима эпилепсии char epilepsyInput; while (true) { std::cout << "Epilepsy mode (Y/N)? "; // Запрос режима эпилепсии if (std::cin >> epilepsyInput && (epilepsyInput == 'Y' || epilepsyInput == 'y' || epilepsyInput == 'N' || epilepsyInput == 'n')) break; std::cin.clear(); // Сброс флага ошибки std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Очистка буфера ввода std::cout << "Invalid input. Please enter 'Y' or 'N'." << std::endl; } // Устанавливаем режим эпилепсии на основе ввода пользователя epilepsyMode = (epilepsyInput == 'Y' || epilepsyInput == 'y'); } void getConsoleSize() { // Получаем размеры окна консоли CONSOLE_SCREEN_BUFFER_INFO csbi; // Структура для хранения информации о консоли GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); // Получаем информацию о буфере consoleWidth = csbi.srWindow.Right - csbi.srWindow.Left + 1; // Ширина консоли consoleHeight = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; // Высота консоли }};
// Главная функция int main() { AppManager appManager; // Создаем объект управления appManager.start(); // Запускаем симуляцию
return 0; // Завершаем программу}
- Assistant
Для устранения мерцания линии в консольном приложении можно использовать метод двойной буферизации. Это позволяет обновить экран консоли только один раз за каждый кадр, вместо того, чтобы очищать и перерисовывать экран каждый раз. В Windows это можно сделать, используя ручку консоли для прямого управления курсором и избегая вызова
system("cls"). Вместо этого, перерисовывайте только ту часть экрана, которая изменяется.Вот возможные изменения, которые можно внести в код:
- Вместо
system("cls")используйтеSetConsoleCursorPosition()для управления положением курсора. - Сохраняйте состояние предыдущей строки для сравнения и обновления только изменённых частей.
Ниже представлен пример обновлённого кода:
#include <iostream> #include <vector> #include <thread> #include <chrono> #include <random> #include <conio.h> #include <windows.h> class Symbol { public: Symbol(char character = ' ', int color = 10) : character(character), color(color) {} char getCharacter() const { return character; } void setCharacter(char character) { this->character = character; } int getColor() const { return color; } void setColor(int color) { this->color = color; } private: char character; int color; }; class Line { public: Line(int length, bool epilepsyMode) : length(length), epilepsyMode(epilepsyMode) { lineColor = epilepsyMode ? getRandomColor() : 10; for (int i = 0; i < length; ++i) { char randomChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; symbols.push_back(Symbol(randomChar, color)); } symbols[length - 1].setColor(15); } void move() { for (int i = 0; i < length - 1; ++i) { symbols[i] = symbols[i + 1]; } generateNewSymbol(); } void draw(HANDLE hConsole, int position, int consoleWidth, int startPosition) const { CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(hConsole, &csbi); COORD cursorPos; cursorPos.X = 0; cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); if (position >= 0) { std::cout << std::string(position, ' '); } int startIndex = std::max(0, -position); int visibleLength = std::min(length - startIndex, consoleWidth - position); for (int i = startIndex; i < startIndex + visibleLength; ++i) { setColor(getColor(i)); std::cout << getCharacter(i); } std::cout << std::endl; } private: int length; std::vector<Symbol> symbols; bool epilepsyMode; int lineColor; void generateNewSymbol() { char newChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; symbols[length - 1] = Symbol(newChar, 15); symbols[length - 2].setColor(color); } static char getRandomCharacter() { const char characters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+[]{}|;':\",.<>?`~"; return characters[rand() % (sizeof(characters) - 1)]; } static int getRandomColor() { return 1 + rand() % 15; } static void setColor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } char getCharacter(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getCharacter(); } return ' '; } int getColor(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getColor(); } return 7; } }; class AppManager { public: AppManager() : speed(1), length(10), epilepsyMode(false), running(true) { srand(static_cast<unsigned int>(time(nullptr))); getConsoleSize(); } void start() { configureSettings(); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO cursorInfo; GetConsoleCursorInfo(hConsole, &cursorInfo); cursorInfo.bVisible = FALSE; SetConsoleCursorInfo(hConsole, &cursorInfo); std::cout << "Matrix Simulation is starting..." << std::endl; while (running) { int startPosition = rand() % (consoleHeight - 1); Line line(length, epilepsyMode); int position = -length; while (position < consoleWidth) { line.draw(hConsole, position, consoleWidth, startPosition); std::this_thread::sleep_for(std::chrono::milliseconds(1000 / speed)); line.move(); ++position; if (_kbhit() && _getch() == 'q') { running = false; break; } } if (epilepsyMode) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); } } } private: int speed; int length; bool epilepsyMode; bool running; int consoleWidth; int consoleHeight; void configureSettings() { std::cout << "Welcome to the Matrix Simulation!" << std::endl; while (true) { std::cout << "Enter speed (1 - 30): "; if (std::cin >> speed && speed >= 1 && speed <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } while (true) { std::cout << "Enter line length (1 - 30): "; if (std::cin >> length && length >= 1 && length <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } char epilepsyInput; while (true) { std::cout << "Epilepsy mode (Y/N)? "; if (std::cin >> epilepsyInput && (epilepsyInput == 'Y' || epilepsyInput == 'y' || epilepsyInput == 'N' || epilepsyInput == 'n')) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter 'Y' or 'N'." << std::endl; } epilepsyMode = (epilepsyInput == 'Y' || epilepsyInput == 'y'); } void getConsoleSize() { CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); consoleWidth = csbi.srWindow.Right - csbi.srWindow.Left + 1; consoleHeight = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; } }; int main() { AppManager appManager; appManager.start(); return 0; }В этом обновлении использован метод управления курсором
SetConsoleCursorPosition, чтобы избежать мерцающего экрана, характерного для методаsystem("cls"). Вместо очистки экрана, обновляется только область вывода, что значительно снижает мерцание. - Вместо
- User
теперь линия двигается плавно, но когда доходит до конца последний символ остается около правой границы консоли, надо это исправить
#include #include #include #include #include #include <conio.h> #include <windows.h>
class Symbol { public: Symbol(char character = ' ', int color = 10) : character(character), color(color) {}
char getCharacter() const { return character; } void setCharacter(char character) { this->character = character; } int getColor() const { return color; } void setColor(int color) { this->color = color; }private: char character; int color; };
class Line { public: Line(int length, bool epilepsyMode) : length(length), epilepsyMode(epilepsyMode) { lineColor = epilepsyMode ? getRandomColor() : 10;
for (int i = 0; i < length; ++i) { char randomChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; symbols.push_back(Symbol(randomChar, color)); } symbols[length - 1].setColor(15); } void move() { for (int i = 0; i < length - 1; ++i) { symbols[i] = symbols[i + 1]; } generateNewSymbol(); } void draw(HANDLE hConsole, int position, int consoleWidth, int startPosition) const { CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(hConsole, &csbi); COORD cursorPos; cursorPos.X = 0; cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); if (position >= 0) { std::cout << std::string(position, ' '); } int startIndex = std::max(0, -position); int visibleLength = std::min(length - startIndex, consoleWidth - position); for (int i = startIndex; i < startIndex + visibleLength; ++i) { setColor(getColor(i)); std::cout << getCharacter(i); } std::cout << std::endl; }private: int length; std::vector symbols; bool epilepsyMode; int lineColor;
void generateNewSymbol() { char newChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; symbols[length - 1] = Symbol(newChar, 15); symbols[length - 2].setColor(color); } static char getRandomCharacter() { const char characters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+[]{}|;':\",.<>?`~"; return characters[rand() % (sizeof(characters) - 1)]; } static int getRandomColor() { return 1 + rand() % 15; } static void setColor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } char getCharacter(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getCharacter(); } return ' '; } int getColor(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getColor(); } return 7; }};
class AppManager { public: AppManager() : speed(1), length(10), epilepsyMode(false), running(true) { srand(static_cast(time(nullptr))); getConsoleSize(); }
void start() { configureSettings(); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO cursorInfo; GetConsoleCursorInfo(hConsole, &cursorInfo); cursorInfo.bVisible = FALSE; SetConsoleCursorInfo(hConsole, &cursorInfo); std::cout << "Matrix Simulation is starting..." << std::endl; while (running) { int startPosition = rand() % (consoleHeight - 1); Line line(length, epilepsyMode); int position = -length; while (position < consoleWidth) { line.draw(hConsole, position, consoleWidth, startPosition); std::this_thread::sleep_for(std::chrono::milliseconds(1000 / speed)); line.move(); ++position; if (_kbhit() && _getch() == 'q') { running = false; break; } } if (epilepsyMode) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); } } }private: int speed; int length; bool epilepsyMode; bool running; int consoleWidth; int consoleHeight;
void configureSettings() { std::cout << "Welcome to the Matrix Simulation!" << std::endl; while (true) { std::cout << "Enter speed (1 - 30): "; if (std::cin >> speed && speed >= 1 && speed <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } while (true) { std::cout << "Enter line length (1 - 30): "; if (std::cin >> length && length >= 1 && length <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } char epilepsyInput; while (true) { std::cout << "Epilepsy mode (Y/N)? "; if (std::cin >> epilepsyInput && (epilepsyInput == 'Y' || epilepsyInput == 'y' || epilepsyInput == 'N' || epilepsyInput == 'n')) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter 'Y' or 'N'." << std::endl; } epilepsyMode = (epilepsyInput == 'Y' || epilepsyInput == 'y'); } void getConsoleSize() { CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); consoleWidth = csbi.srWindow.Right - csbi.srWindow.Left + 1; consoleHeight = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; }};
int main() { AppManager appManager; appManager.start();
return 0;}
- Assistant
Чтобы исправить проблему с оставлением последнего символа около правой границы консоли, можно добавить логическое условие, которое будет скрывать последнюю часть строки, когда она выходит за пределы экрана. Это можно сделать, проверив текущую позицию строки относительно ширины консоли и изменив длину видимой части строки в зависимости от её положения.
Измените метод
drawклассаLine, добавив проверку на выход строки за правую границу экрана:void draw(HANDLE hConsole, int position, int consoleWidth, int startPosition) const { CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(hConsole, &csbi); COORD cursorPos; // Перемещаем курсор на нужную позицию cursorPos.X = 0; cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); // Добавляем пробелы для смещения линии вправо if (position >= 0) { std::cout << std::string(position, ' '); } // Определяем начальный индекс и видимую длину строки int startIndex = std::max(0, -position); int visibleLength = std::min(length - startIndex, consoleWidth - position); // Обрезка видимой длины, если линия частично выходит за правую границу if (position + visibleLength > consoleWidth) { visibleLength = consoleWidth - position; } // Рисуем видимую часть линии for (int i = startIndex; i < startIndex + visibleLength; ++i) { setColor(getColor(i)); std::cout << getCharacter(i); } // Устанавливаем цвет по умолчанию в конце строки setColor(7); std::cout << std::string(consoleWidth - (position + visibleLength), ' ') << std::endl; }Дополнительные изменения:
- Учтите, что обрезка
visibleLengthдоconsoleWidth - positionнеобходима для предотвращения выхода за пределы экрана. - Устанавливайте цвет текста по умолчанию (обычно белый, код
7), когда нужно вставить пробелы вместо символов за правой границей.
Эти изменения гарантируют, что символы не будут оставаться на экране после полного перемещения строки вправо. Таким образом, консольный вывод будет аккуратно подчищаться, чтобы не оставлять артефактов от движения строк.
- Учтите, что обрезка
- User
'это не помогло, давай попробуем что-то другое
- Assistant
Прошу прощения за то, что предложенные изменения не помогли достичь желаемого результата. Давайте попробуем другой подход. Мы можем использовать метод, который оставляет пустые пространства там, где линия выходит за пределы экрана, и использовать
SetConsoleCursorPosition()для перемещения курсора в начало следующей строки после отрисовки текущей линии.Вот обновленный метод
draw, который должен решить проблему:void draw(HANDLE hConsole, int position, int consoleWidth, int startPosition) const { // Устанавливаем курсор в начало линии COORD cursorPos; cursorPos.X = 0; cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); // Выводим пробелы для смещения линии вправо if (position >= 0) { std::cout << std::string(position, ' '); } // Индекс и длина видимой части линии int startIndex = std::max(0, -position); int visibleLength = std::min(length - startIndex, consoleWidth - position); // Рисуем видимую часть линии for (int i = startIndex; i < startIndex + visibleLength; ++i) { setColor(getColor(i)); std::cout << getCharacter(i); } // Возвращаем цвет по умолчанию setColor(7); // Заполняем оставшуюся часть строки пробелами, если линия выходит за пределы if (position < consoleWidth) { std::cout << std::string(consoleWidth - (position + visibleLength), ' '); } // Перемещаем курсор в следующую строку cursorPos.X = 0; cursorPos.Y++; SetConsoleCursorPosition(hConsole, cursorPos); }Эти изменения помогут:
-
Правильное управление пробелами: Если линия выходит за пределы экрана, оставляем пустое пространство, чтобы замаскировать оставшиеся символы.
-
Установка курсора в начало следующей строки: После отрисовки текущей линии курсор перемещается в следующую строку, что предотвращает проблемы с остаточными символами.
-
Управление цветом: Обеспечивает возврат стандартного цвета текста после отрисовки символов.
Попробуйте внести эти изменения и протестируйте программу ещё раз. Это должно помочь избавиться от отображения лишних символов в конце строки.
-
- User
объясни каждую строчку кода
#include #include #include #include #include #include <conio.h> #include <windows.h>
class Symbol { public: Symbol(char character = ' ', int color = 10) : character(character), color(color) {}
char getCharacter() const { return character; } void setCharacter(char character) { this->character = character; } int getColor() const { return color; } void setColor(int color) { this->color = color; }private: char character; int color; };
class Line { public: Line(int length, bool epilepsyMode) : length(length), epilepsyMode(epilepsyMode) { lineColor = epilepsyMode ? getRandomColor() : 10;
for (int i = 0; i < length; ++i) { char randomChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; symbols.push_back(Symbol(randomChar, color)); } symbols[length - 1].setColor(15); } void move() { for (int i = 0; i < length - 1; ++i) { symbols[i] = symbols[i + 1]; } generateNewSymbol(); } void draw(HANDLE hConsole, int position, int consoleWidth, int startPosition) const { // Устанавливаем курсор в начало линии COORD cursorPos; cursorPos.X = 0; cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); // Выводим пробелы для смещения линии вправо if (position >= 0) { std::cout << std::string(position, ' '); } // Индекс и длина видимой части линии int startIndex = std::max(0, -position); int visibleLength = std::min(length - startIndex, consoleWidth - position); // Рисуем видимую часть линии for (int i = startIndex; i < startIndex + visibleLength; ++i) { setColor(getColor(i)); std::cout << getCharacter(i); } // Возвращаем цвет по умолчанию setColor(7); // Заполняем оставшуюся часть строки пробелами, если линия выходит за пределы if (position < consoleWidth) { std::cout << std::string(consoleWidth - (position + visibleLength), ' '); } // Перемещаем курсор в следующую строку cursorPos.X = 0; cursorPos.Y++; SetConsoleCursorPosition(hConsole, cursorPos); }private: int length; std::vector symbols; bool epilepsyMode; int lineColor;
void generateNewSymbol() { char newChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; symbols[length - 1] = Symbol(newChar, 15); symbols[length - 2].setColor(color); } static char getRandomCharacter() { const char characters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+[]{}|;':\",.<>?`~"; return characters[rand() % (sizeof(characters) - 1)]; } static int getRandomColor() { return 1 + rand() % 15; } static void setColor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } char getCharacter(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getCharacter(); } return ' '; } int getColor(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getColor(); } return 7; }};
class AppManager { public: AppManager() : speed(1), length(10), epilepsyMode(false), running(true) { srand(static_cast(time(nullptr))); getConsoleSize(); }
void start() { configureSettings(); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO cursorInfo; GetConsoleCursorInfo(hConsole, &cursorInfo); cursorInfo.bVisible = FALSE; SetConsoleCursorInfo(hConsole, &cursorInfo); std::cout << "Matrix Simulation is starting..." << std::endl; while (running) { int startPosition = rand() % (consoleHeight - 1); Line line(length, epilepsyMode); int position = -length; while (position < consoleWidth) { line.draw(hConsole, position, consoleWidth, startPosition); std::this_thread::sleep_for(std::chrono::milliseconds(1000 / speed)); line.move(); ++position; if (_kbhit() && _getch() == 'q') { running = false; break; } } if (epilepsyMode) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); } } }private: int speed; int length; bool epilepsyMode; bool running; int consoleWidth; int consoleHeight;
void configureSettings() { std::cout << "Welcome to the Matrix Simulation!" << std::endl; while (true) { std::cout << "Enter speed (1 - 30): "; if (std::cin >> speed && speed >= 1 && speed <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } while (true) { std::cout << "Enter line length (1 - 30): "; if (std::cin >> length && length >= 1 && length <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } char epilepsyInput; while (true) { std::cout << "Epilepsy mode (Y/N)? "; if (std::cin >> epilepsyInput && (epilepsyInput == 'Y' || epilepsyInput == 'y' || epilepsyInput == 'N' || epilepsyInput == 'n')) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter 'Y' or 'N'." << std::endl; } epilepsyMode = (epilepsyInput == 'Y' || epilepsyInput == 'y'); } void getConsoleSize() { CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); consoleWidth = csbi.srWindow.Right - csbi.srWindow.Left + 1; consoleHeight = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; }};
int main() { AppManager appManager; appManager.start();
return 0;}
- Assistant
Давайте разберём каждую строчку кода, чтобы понять, как он работает:
Подключение библиотек
#include <iostream> #include <vector> #include <thread> #include <chrono> #include <random> #include <conio.h> #include <windows.h>- Эти библиотеки добавляют необходимые функции для работы с вводом/выводом, векторами, многопоточностью, измерением времени, генерацией случайных чисел, работы с клавиатурными событиями и функциями Windows.
Класс
Symbolclass Symbol { public: Symbol(char character = ' ', int color = 10) : character(character), color(color) {} // Конструктор инициализирует символ (по умолчанию - пробел) и цвет (по умолчанию - зелёный). char getCharacter() const { return character; } void setCharacter(char character) { this->character = character; } int getColor() const { return color; } void setColor(int color) { this->color = color; } // Методы для получения и задания символа и цвета. private: char character; int color; };- Класс
Symbolпредназначен для представления символа с заданным цветом.
Класс
Lineclass Line { public: Line(int length, bool epilepsyMode) : length(length), epilepsyMode(epilepsyMode) { // Конструктор принимает длину линии и флаг режима эпилепсии и инициализирует несколько переменных. lineColor = epilepsyMode ? getRandomColor() : 10; // Устанавливает случайный цвет для линии, если режим эпилепсии активен, иначе зелёный. for (int i = 0; i < length; ++i) { char randomChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; symbols.push_back(Symbol(randomChar, color)); // Заполняет линию случайными символами, каждый из которых имеет цвет, соответствующий режиму. } symbols[length - 1].setColor(15); // Последний символ окрашен в белый цвет. } void move() { for (int i = 0; i < length - 1; ++i) { symbols[i] = symbols[i + 1]; } generateNewSymbol(); // Сдвигает все символы влево и генерирует новый символ в конце линии. } void draw(HANDLE hConsole, int position, int consoleWidth, int startPosition) const { COORD cursorPos; cursorPos.X = 0; cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); // Перемещает курсор в начало строки `startPosition` в консоли. if (position >= 0) { std::cout << std::string(position, ' '); } // Добавляет пробелы для сдвига линии вправо, если позиция больше или равна нулю. int startIndex = std::max(0, -position); int visibleLength = std::min(length - startIndex, consoleWidth - position); // Вычисляет индекс начала и видимую длину линии в зависимости от позиции и ширины консоли. for (int i = startIndex; i < startIndex + visibleLength; ++i) { setColor(getColor(i)); std::cout << getCharacter(i); } // Отображает видимую часть линии с корректным цветом. setColor(7); // Сбрасывает цвет символов на цвет по умолчанию (белый). if (position < consoleWidth) { std::cout << std::string(consoleWidth - (position + visibleLength), ' '); } // Добавляет пробелы в оставшуюся часть строки, если линия частично выходит за пределы экрана. cursorPos.X = 0; cursorPos.Y++; SetConsoleCursorPosition(hConsole, cursorPos); // Перемещает курсор в начало следующей строки. } private: int length; std::vector<Symbol> symbols; bool epilepsyMode; int lineColor; // Переменные для хранения длины линии, символов, режима эпилепсии и цвета линии. void generateNewSymbol() { char newChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; symbols[length - 1] = Symbol(newChar, 15); symbols[length - 2].setColor(color); // Генерирует новый символ в конце линии и устанавливает цвет для предпоследнего символа. } static char getRandomCharacter() { const char characters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+[]{}|;':\",.<>?`~"; return characters[rand() % (sizeof(characters) - 1)]; // Возвращает случайный символ из заданного набора символов. } static int getRandomColor() { return 1 + rand() % 15; // Возвращает случайный цвет от 1 до 15 (в диапазоне допустимых кодов для консоли). } static void setColor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); // Устанавливает цвет текста в консоли на заданный. } char getCharacter(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getCharacter(); } return ' '; // Возвращает символ по индексу, если индекс валидный, иначе пробел. } int getColor(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getColor(); } return 7; // Возвращает цвет символа по индексу, если индекс валидный, иначе цвет по умолчанию. } };Класс
AppManagerclass AppManager { public: AppManager() : speed(1), length(10), epilepsyMode(false), running(true) { srand(static_cast<unsigned int>(time(nullptr))); getConsoleSize(); } // Конструктор устанавливает начальные параметры и инициализирует генератор случайных чисел. void start() { configureSettings(); // Настраивает параметры приложения, запрашивая настройки у пользователя. HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO cursorInfo; GetConsoleCursorInfo(hConsole, &cursorInfo); cursorInfo.bVisible = FALSE; SetConsoleCursorInfo(hConsole, &cursorInfo); // Получает дескриптор консоли и скрывает курсор. std::cout << "Matrix Simulation is starting..." << std::endl; // Выводит сообщение о старте симуляции. while (running) { int startPosition = rand() % (consoleHeight - 1); Line line(length, epilepsyMode); int position = -length; // Создаёт линию заданной длины, устанавливает начальную позицию линии на -длину (чтобы вначале линия появлялась с левой стороны). while (position < consoleWidth) { line.draw(hConsole, position, consoleWidth, startPosition); std::this_thread::sleep_for(std::chrono::milliseconds(1000 / speed)); line.move(); ++position; // Отрисовывает линию, изменяет её позицию, засыпает на время, чтобы управлять скоростью линий. if (_kbhit() && _getch() == 'q') { running = false; break; // Прерывает выполнение, если была нажата клавиша 'q'. } } if (epilepsyMode) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); // Добавляет задержку для эффекта линии в режиме эпилепсии. } } } private: int speed; int length; bool epilepsyMode; bool running; int consoleWidth; int consoleHeight; // Переменные для хранения скорости, длины, состояния режима эпилепсии, флага работы программы и размеров консоли. void configureSettings() { std::cout << "Welcome to the Matrix Simulation!" << std::endl; // Выводит приветствие. while (true) { std::cout << "Enter speed (1 - 30): "; if (std::cin >> speed && speed >= 1 && speed <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; // Запрашивает у пользователя скорость, проверяя, что она в нужном диапазоне. } while (true) { std::cout << "Enter line length (1 - 30): "; if (std::cin >> length && length >= 1 && length <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; // Запрашивает у пользователя длину линий, проверяя, что она в нужном диапазоне. } char epilepsyInput; while (true) { std::cout << "Epilepsy mode (Y/N)? "; if (std::cin >> epilepsyInput && (epilepsyInput == 'Y' || epilepsyInput == 'y' || epilepsyInput == 'N' || epilepsyInput == 'n')) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter 'Y' or 'N'." << std::endl; } // Запрашивает режим эпилепсии. epilepsyMode = (epilepsyInput == 'Y' || epilepsyInput == 'y'); } void getConsoleSize() { CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); consoleWidth = csbi.srWindow.Right - csbi.srWindow.Left + 1; consoleHeight = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; // Определяет размеры консольного окна и сохраняет их в переменные. } }; int main() { AppManager appManager; appManager.start(); // Создаёт объект `AppManager` и запускает симуляцию. return 0; }Резюме
Этот код создает текстовую анимацию, имитирующую вид "цифрового дождя", известного из фильма "Матрица". Приложение управляет консолью Windows для отображения потока случайных символов, текуще-х справа налево через экран. Пользователь может задать скорость, длину линий и выбрать режим эпилепсии, который изменяет цвет символов.
- User
мне кажется надо поменять суть отрисовки линию не надо сдвигать, надо затирать символы слева и добавлять новый справа
- Assistant
Если вы хотите, чтобы линия вместо перемещения вправо затирала символы слева и добавляла новые справа (как прокрутка строки текста), то можно изменить логику в классе
Lineтак, чтобы она затирала старые символы вместо сдвига. Это потребует изменения методаdrawи, возможно,move. Давайте обновим эти методы:Изменение метода
moveВ методе
moveбольше не будем сдвигать массив символов, а просто будем затирать с начала и добавлять новую символику в конец.void move() { // Сдвигаем на одно место и генерируем новый символ справа for (int i = 0; i < length - 1; ++i) { symbols[i] = symbols[i + 1]; } generateNewSymbol(); }Изменение метода
drawОбеспечим, чтобы символы стирались слева и добавлялись справа.
void draw(HANDLE hConsole, int position, int consoleWidth, int startPosition, int prevPosition) const { // Перемещаем курсор в начальное положение строки COORD cursorPos; cursorPos.Y = startPosition; // Участок экрана, который нужно очистить int eraseLength = std::max(0, prevPosition); for (int i = 0; i < eraseLength; ++i) { cursorPos.X = i; SetConsoleCursorPosition(hConsole, cursorPos); std::cout << " "; // Затираем символ, печатая пробел. } // Определяем начало и длину видимой части. int lineStart = std::max(position, 0); int visibleLength = std::min(consoleWidth, position + length) - lineStart; // Отображаем символы. for (int i = 0; i < visibleLength; ++i) { cursorPos.X = lineStart + i; SetConsoleCursorPosition(hConsole, cursorPos); setColor(getColor(i)); std::cout << getCharacter(i); } // Возвращаем цвет по умолчанию в конце. setColor(7); }Дополнительные изменения
- Обратите внимание на то, что теперь метод
drawпринимает дополнительный параметрprevPosition. Этот параметр нужен для правильного стирания символов слева, так как так мы можем знать, где начиналась линия в предыдущем кадре. - Изменения позволят линии казаться передвигающейся без физического сдвига всех символов, что может быть менее затратным с точки зрения вычислений.
- Переменные сохраняются между вызовами, позволяя вызвать
drawс предыдущей и текущей позициями для правильного отображения.
Попробуйте данный подход — он должен быть более оптимальным и убедительным.
- Обратите внимание на то, что теперь метод
- User
сделай что-то на подобие этого, переделай мой код программы
for (int i = 0; i < height + this->Size; i++) { // Двигаемся до крайней левой позиции и заползаем (если не надо заползать, просто сложение убрать) // Удаляем последний символ хвоста (затирание следа) if (i == height) { this->is_wall = true; } if (to_romb == false) { to_romb = true; if (height - i + this->Size <= height) { manager.setCursorPosition(height - i + this->Size, randomY + 1); std::cout << " "; manager.setCursorPosition(height - i + this->Size, randomY - 1); std::cout << " "; } if (height - i >= 0) { if (i != 0) { vec[(i - 1) % this->Size].SetColor(this->is_epelepsy); manager.setCursorPosition(height - i + 1, randomY + 1); std::cout << this->vec[(i - 1) % this->Size]; manager.setCursorPosition(height - i + 1, randomY - 1); std::cout << this->vec[(i - 1) % this->Size]; } vec[i % this->Size] = Symbol(this->is_epelepsy,this->is_wall); manager.setCursorPosition(height - i, randomY); std::cout << this->vec[i % this->Size]; } } else { to_romb = false; if (height - i + this->Size <= height) { manager.setCursorPosition(height - i + this->Size, randomY); std::cout << " "; } // Рисуем новую "голову" в начале if (height - i >= 0) { if (i != 0) { vec[(i - 1) % this->Size].SetColor(this->is_epelepsy); manager.setCursorPosition(height - i + 1, randomY); std::cout << this->vec[(i - 1) % this->Size]; }
vec[i % this->Size] = Symbol(this->is_epelepsy, this->is_wall); manager.setCursorPosition(height - i, randomY + 1); std::cout << this->vec[i % this->Size]; manager.setCursorPosition(height - i, randomY - 1); std::cout << this->vec[i % this->Size]; }} Sleep(delay); }
- Assistant
Понятно, вы хотите создать эффект ползущей горизонтальной линии, где новый символ появляется справа, а слева следы затираются. Я помогу вам переделать ваш код, чтобы это реализовать. Мы сохраним концепцию анимации, переписав логику так, чтобы линия не двигалась целиком вправо, а затиралась слева и добавлялась справа.
Вот как может выглядеть обновленная реализация:
#include <iostream> #include <vector> #include <thread> #include <chrono> #include <random> #include <conio.h> #include <windows.h> class Symbol { public: Symbol(char character = ' ', int color = 10) : character(character), color(color) {} char getCharacter() const { return character; } int getColor() const { return color; } void setCharacter(char character) { this->character = character; } void setColor(int color) { this->color = color; } private: char character; int color; }; class Line { public: Line(int length, bool epilepsyMode) : length(length), epilepsyMode(epilepsyMode), position(0) { lineColor = epilepsyMode ? getRandomColor() : 10; for (int i = 0; i < length; ++i) { generateNewSymbol(i); } symbols[length - 1].setColor(15); } void draw(HANDLE hConsole, int consoleWidth, int consoleHeight) { COORD cursorPos = { 0, static_cast<SHORT>(rand() % (consoleHeight - 1)) }; // Затираем старый символ (в начале линии) int erasePos = position - length; if (erasePos >= 0) { SetConsoleCursorPosition(hConsole, { static_cast<SHORT>(erasePos), cursorPos.Y }); std::cout << " "; } // Печатаем новый символ (в конце линии) int drawPos = position; if (drawPos < consoleWidth) { setColor(getColor(drawPos % length)); SetConsoleCursorPosition(hConsole, { static_cast<SHORT>(drawPos), cursorPos.Y }); std::cout << getCharacter(drawPos % length); } // Обновляем положение "головы" ++position; // Если достигли конца экрана, начинаем заново if (position - length >= consoleWidth) { position = 0; } // Сбрасываем цвет консоли setColor(7); } private: int length; std::vector<Symbol> symbols; bool epilepsyMode; int lineColor; int position; // Текущая позиция "головы" линии void generateNewSymbol(int index) { char newChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; symbols[index] = Symbol(newChar, color); } static char getRandomCharacter() { const char characters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+[]{}|;':\",.<>?`~"; return characters[rand() % (sizeof(characters) - 1)]; } static int getRandomColor() { return 1 + rand() % 15; } static void setColor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } char getCharacter(int index) const { return symbols[index].getCharacter(); } int getColor(int index) const { return symbols[index].getColor(); } }; class AppManager { public: AppManager() : speed(1), length(10), epilepsyMode(false), running(true) { srand(static_cast<unsigned int>(time(nullptr))); getConsoleSize(); } void start() { configureSettings(); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO cursorInfo; GetConsoleCursorInfo(hConsole, &cursorInfo); cursorInfo.bVisible = FALSE; SetConsoleCursorInfo(hConsole, &cursorInfo); std::cout << "Matrix Simulation is starting..." << std::endl; while (running) { Line line(length, epilepsyMode); while (running) { line.draw(hConsole, consoleWidth, consoleHeight); std::this_thread::sleep_for(std::chrono::milliseconds(1000 / speed)); // Проверяем, не нажата ли клавиша 'q' if (_kbhit() && _getch() == 'q') { running = false; break; } } if (epilepsyMode) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); } } } private: int speed; int length; bool epilepsyMode; bool running; int consoleWidth; int consoleHeight; void configureSettings() { std::cout << "Welcome to the Matrix Simulation!" << std::endl; while (true) { std::cout << "Enter speed (1 - 30): "; if (std::cin >> speed && speed >= 1 && speed <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } while (true) { std::cout << "Enter line length (1 - 30): "; if (std::cin >> length && length >= 1 && length <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } char epilepsyInput; while (true) { std::cout << "Epilepsy mode (Y/N)? "; if (std::cin >> epilepsyInput && (epilepsyInput == 'Y' || epilepsyInput == 'y' || epilepsyInput == 'N' || epilepsyInput == 'n')) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter 'Y' or 'N'." << std::endl; } epilepsyMode = (epilepsyInput == 'Y' || epilepsyInput == 'y'); } void getConsoleSize() { CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); consoleWidth = csbi.srWindow.Right - csbi.srWindow.Left + 1; consoleHeight = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; } }; int main() { AppManager appManager; appManager.start(); return 0; }Объяснение
-
Класс
Symbol: хранящий символ и его цвет. -
Класс
Line:- Содержит
symbolsдля хранения линии символов. positionотслеживает текущую голову линии (где будет добавлен новый символ).drawзатирает символ вerasePosи добавляет новый символ вdrawPos.
- Содержит
-
Класс
AppManager:- Запускает и управляет всей симуляцией.
- Входит в основной цикл, где создаёт и отрисовывает линию.
-
Метод
draw: Этот метод отвечает за то, чтобы затирать символы слева и добавлять новые справа, сохраняя иллюзию для пользователя что линия движется.
Эта версия кода позволяет линиям затирать символы слева и добавлять новые справа, создавая плавный и эффективный визуальный эффект строки, текущей по экрану.
-
- User
симуляция не запускается и через время консоль закрывается
- Assistant
Давайте проверим и исправим потенциальные ошибки, которые могут быть причиной того, что консоль закрывается. Вы можете внести следующие изменения, чтобы убедиться, что программа работает корректно:
-
Проблема с случайными Y-координатами: Убедитесь, что
Draw()всегда получает корректные значения для позиционирования. Вероятно, стоит фиксировать Y-координату или проверять её до вызова отрисовки. -
Корректное завершение программы: Добавьте паузу или ручное завершение после выхода из основного цикла, чтобы увидеть ошибки.
-
Убедитесь, что не выходит за границы индексов: проверьте операции с индексами и счётчиками.
Вот исправленный вариант:
#include <iostream> #include <vector> #include <thread> #include <chrono> #include <random> #include <conio.h> #include <windows.h> class Symbol { public: Symbol(char character = ' ', int color = 10) : character(character), color(color) {} char getCharacter() const { return character; } int getColor() const { return color; } void setCharacter(char character) { this->character = character; } void setColor(int color) { this->color = color; } private: char character; int color; }; class Line { public: Line(int length, bool epilepsyMode) : length(length), epilepsyMode(epilepsyMode), position(0) { lineColor = epilepsyMode ? getRandomColor() : 10; for (int i = 0; i < length; ++i) { generateNewSymbol(i); } symbols[length - 1].setColor(15); } void draw(HANDLE hConsole, int consoleWidth, int fixedY) { // Затираем старый символ (в начале линии) int erasePos = position - length; if (erasePos >= 0) { SetConsoleCursorPosition(hConsole, { static_cast<SHORT>(erasePos), static_cast<SHORT>(fixedY) }); std::cout << " "; } // Печатаем новый символ (в конце линии) int drawPos = position; if (drawPos < consoleWidth) { setColor(getColor(drawPos % length)); SetConsoleCursorPosition(hConsole, { static_cast<SHORT>(drawPos), static_cast<SHORT>(fixedY) }); std::cout << getCharacter(drawPos % length); } // Обновляем положение "головы" ++position; // Если достигли конца экрана, начинаем заново if (position >= consoleWidth + length) { position = 0; } // Сбрасываем цвет консоли setColor(7); } private: int length; std::vector<Symbol> symbols; bool epilepsyMode; int lineColor; int position; // Текущая позиция "головы" линии void generateNewSymbol(int index) { char newChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; symbols[index] = Symbol(newChar, color); } static char getRandomCharacter() { const char characters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+[]{}|;':\",.<>?`~"; return characters[rand() % (sizeof(characters) - 1)]; } static int getRandomColor() { return 1 + rand() % 15; } static void setColor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } char getCharacter(int index) const { return symbols[index].getCharacter(); } int getColor(int index) const { return symbols[index].getColor(); } }; class AppManager { public: AppManager() : speed(1), length(10), epilepsyMode(false), running(true) { srand(static_cast<unsigned int>(time(nullptr))); getConsoleSize(); } void start() { configureSettings(); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO cursorInfo; GetConsoleCursorInfo(hConsole, &cursorInfo); cursorInfo.bVisible = FALSE; SetConsoleCursorInfo(hConsole, &cursorInfo); std::cout << "Matrix Simulation is starting..." << std::endl; while (running) { Line line(length, epilepsyMode); int fixedY = rand() % (consoleHeight - 1); // Фиксируем Y-координату while (running) { line.draw(hConsole, consoleWidth, fixedY); std::this_thread::sleep_for(std::chrono::milliseconds(1000 / speed)); // Проверяем, не нажата ли клавиша 'q' if (_kbhit() && _getch() == 'q') { running = false; break; } } if (epilepsyMode) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); } } // Добавляем паузу перед закрытием консоли std::cout << "Simulation ended. Press any key to close."; _getch(); } private: int speed; int length; bool epilepsyMode; bool running; int consoleWidth; int consoleHeight; void configureSettings() { std::cout << "Welcome to the Matrix Simulation!" << std::endl; while (true) { std::cout << "Enter speed (1 - 30): "; if (std::cin >> speed && speed >= 1 && speed <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } while (true) { std::cout << "Enter line length (1 - 30): "; if (std::cin >> length && length >= 1 && length <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } char epilepsyInput; while (true) { std::cout << "Epilepsy mode (Y/N)? "; if (std::cin >> epilepsyInput && (epilepsyInput == 'Y' || epilepsyInput == 'y' || epilepsyInput == 'N' || epilepsyInput == 'n')) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter 'Y' or 'N'." << std::endl; } epilepsyMode = (epilepsyInput == 'Y' || epilepsyInput == 'y'); } void getConsoleSize() { CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); consoleWidth = csbi.srWindow.Right - csbi.srWindow.Left + 1; consoleHeight = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; } }; int main() { AppManager appManager; appManager.start(); return 0; }Объяснение внесённых изменений:
- Фиксированные Y-координаты: Мы добавили переменную
fixedY, которая задается единожды случайным образом в каждом циклеwhile (running), чтобы предотвратить произвольное скакание линии вверх и вниз. - Сохранение ранней позиции: Использование дополнительных проверок, чтобы точнее контролировать, где затирать и где рисовать символы.
- Вывод сообщений об окончании программы и ожидание ввода: Последний вывод и функция
_getch()помогают увидеть, когда программа завершилась, вместо мгновенного закрытия окна. - Управление позиционированием: Система следит за начальной и конечной позицией и корректно их управляет.
Эти изменения должны исправить проблемы с закрытием и корректно отображать строку с затиранием символов слева.
-
- User
#include #include #include #include #include #include <conio.h> #include <windows.h>
class Symbol { public: Symbol(char character = ' ', int color = 10) : character(character), color(color) {}
char getCharacter() const { return character; } void setCharacter(char character) { this->character = character; } int getColor() const { return color; } void setColor(int color) { this->color = color; }private: char character; int color; };
class Line { public: Line(int length, bool epilepsyMode) : length(length), epilepsyMode(epilepsyMode) { lineColor = epilepsyMode ? getRandomColor() : 10;
for (int i = 0; i < length; ++i) { char randomChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; symbols.push_back(Symbol(randomChar, color)); } symbols[length - 1].setColor(15); } void move() { for (int i = 0; i < length - 1; ++i) { symbols[i] = symbols[i + 1]; } generateNewSymbol(); } void draw(HANDLE hConsole, int position, int consoleWidth, int startPosition) const { CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(hConsole, &csbi); COORD cursorPos; cursorPos.X = 0; cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); if (position >= 0) { std::cout << std::string(position, ' '); } int startIndex = std::max(0, -position); int visibleLength = std::min(length - startIndex, consoleWidth - position); for (int i = startIndex; i < startIndex + visibleLength; ++i) { setColor(getColor(i)); std::cout << getCharacter(i); } std::cout << std::endl; }private: int length; std::vector symbols; bool epilepsyMode; int lineColor;
void generateNewSymbol() { char newChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; symbols[length - 1] = Symbol(newChar, 15); symbols[length - 2].setColor(color); } static char getRandomCharacter() { const char characters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+[]{}|;':\",.<>?`~"; return characters[rand() % (sizeof(characters) - 1)]; } static int getRandomColor() { return 1 + rand() % 15; } static void setColor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } char getCharacter(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getCharacter(); } return ' '; } int getColor(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getColor(); } return 7; }};
class AppManager { public: AppManager() : speed(1), length(10), epilepsyMode(false), running(true) { srand(static_cast(time(nullptr))); getConsoleSize(); }
void start() { configureSettings(); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO cursorInfo; GetConsoleCursorInfo(hConsole, &cursorInfo); cursorInfo.bVisible = FALSE; SetConsoleCursorInfo(hConsole, &cursorInfo); std::cout << "Matrix Simulation is starting..." << std::endl; while (running) { int startPosition = rand() % (consoleHeight - 1); Line line(length, epilepsyMode); int position = -length; while (position < consoleWidth) { line.draw(hConsole, position, consoleWidth, startPosition); std::this_thread::sleep_for(std::chrono::milliseconds(1000 / speed)); line.move(); ++position; if (_kbhit() && _getch() == 'q') { running = false; break; } } if (epilepsyMode) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); } } }private: int speed; int length; bool epilepsyMode; bool running; int consoleWidth; int consoleHeight;
void configureSettings() { std::cout << "Welcome to the Matrix Simulation!" << std::endl; while (true) { std::cout << "Enter speed (1 - 30): "; if (std::cin >> speed && speed >= 1 && speed <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } while (true) { std::cout << "Enter line length (1 - 30): "; if (std::cin >> length && length >= 1 && length <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } char epilepsyInput; while (true) { std::cout << "Epilepsy mode (Y/N)? "; if (std::cin >> epilepsyInput && (epilepsyInput == 'Y' || epilepsyInput == 'y' || epilepsyInput == 'N' || epilepsyInput == 'n')) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter 'Y' or 'N'." << std::endl; } epilepsyMode = (epilepsyInput == 'Y' || epilepsyInput == 'y'); } void getConsoleSize() { CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); consoleWidth = csbi.srWindow.Right - csbi.srWindow.Left + 1; consoleHeight = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; }};
int main() { AppManager appManager; appManager.start();
return 0;}
- Assistant
Похоже, вы хотите изменить код таким образом, чтобы создавалась иллюзия движения линии, где старые символы затираются слева, а новые добавляются справа. Давайте изменим метод
moveв вашем классеLineдля этой задачи, и обновим методdrawдля подходящей отрисовки.Изменения в классе
Line-
Метод
move: Вместо сдвига символов влево, изменяйте первый символ на пробел и добавляйте новый символ в конце. -
Метод
draw: Сначала затирай старый символ, а затем добавляйте новый в конце линии.
Вот как это может быть реализовано:
class Line { public: Line(int length, bool epilepsyMode) : length(length), epilepsyMode(epilepsyMode) { lineColor = epilepsyMode ? getRandomColor() : 10; for (int i = 0; i < length; ++i) { char randomChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; symbols.push_back(Symbol(randomChar, color)); } symbols[length - 1].setColor(15); } void move() { // Затираем первый символ, добавляя пробел symbols[0] = Symbol(' ', 7); // Сдвигаем все символы один шаг влево for (int i = 1; i < length - 1; ++i) { symbols[i] = symbols[i + 1]; } // Новый символ на правом конце generateNewSymbol(length - 1); } void draw(HANDLE hConsole, int position, int consoleWidth, int startPosition) const { COORD cursorPos; // Удаляем старые символы за границами if (position - 1 >= 0 && position - 1 < consoleWidth) { cursorPos.X = static_cast<SHORT>(position - 1); cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); std::cout << " "; } // Рисуем видимую часть линии int startIndex = std::max(0, -position); int visibleLength = std::min(length - startIndex, consoleWidth - position); for (int i = startIndex; i < startIndex + visibleLength; ++i) { setColor(getColor(i)); cursorPos.X = static_cast<SHORT>(position + i); cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); std::cout << getCharacter(i); } } private: int length; std::vector<Symbol> symbols; bool epilepsyMode; int lineColor; void generateNewSymbol(int index) { char newChar = getRandomCharacter(); int color = epilepsyMode ? lineColor : 10; symbols[index] = Symbol(newChar, 15); } static char getRandomCharacter() { const char characters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+[]{}|;':\",.<>?`~"; return characters[rand() % (sizeof(characters) - 1)]; } static int getRandomColor() { return 1 + rand() % 15; } static void setColor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } char getCharacter(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getCharacter(); } return ' '; } int getColor(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getColor(); } return 7; } };Объяснение изменений:
-
Метод
move: Вместо полной замены всего массива символов на одну позицию влево, сразу устанавливаем первый символ как пробел, а затем сдвигаем остальные вправо, добавляя новый символ в конце. -
Метод
draw: Теперь он также затирает предыдущую позицию линии пробелом перед тем, как рисовать новый конец линии справа.
Это должно помочь создать более плавную анимацию, где только видимые части линии обновляются на экране, без удаления и перерисовки всего экрана консоли.
-
- User
теперь стало все хорошо, но потерялись цвета, линия всегда белая
- Assistant
Чтобы сохранить цвет каждого символа при отрисовке линии вместе с её движением, важно корректно сохранять и задавать цвет каждого символа как в методе
move, так и в методеdraw.Давайте убедимся, что цвета задаются правильно:
-
Проверка и задание цвета при генерации нового символа: Цвет символа должен корректно задаваться при его генерации. В режиме эпилепсии каждому символу может назначаться случайный цвет.
-
Установка цвета перед выводом каждого символа: Убедитесь, что цвет устанавливается непосредственно перед выводом каждого символа методом
SetConsoleTextAttribute.
Пожалуйста, проверьте обновленный код:
class Line { public: Line(int length, bool epilepsyMode) : length(length), epilepsyMode(epilepsyMode) { lineColor = epilepsyMode ? getRandomColor() : 10; for (int i = 0; i < length; ++i) { char randomChar = getRandomCharacter(); int color = epilepsyMode ? getRandomColor() : 10; symbols.push_back(Symbol(randomChar, color)); } symbols[length - 1].setColor(15); // Последний символ цветом 15 (белый) } void move() { // Затираем первый символ, добавляя пробел и цвет по умолчанию symbols[0] = Symbol(' ', 7); // Сдвигаем все символы один шаг влево for (int i = 1; i < length - 1; ++i) { symbols[i] = symbols[i + 1]; } // Новый символ на правом конце generateNewSymbol(length - 1); } void draw(HANDLE hConsole, int position, int consoleWidth, int startPosition) const { COORD cursorPos; // Удаляем старые символы за границами if (position - 1 >= 0 && position - 1 < consoleWidth) { cursorPos.X = static_cast<SHORT>(position - 1); cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); std::cout << " "; } // Рисуем видимую часть линии int startIndex = std::max(0, -position); int visibleLength = std::min(length - startIndex, consoleWidth - position); for (int i = startIndex; i < startIndex + visibleLength; ++i) { setColor(getColor(i)); cursorPos.X = static_cast<SHORT>(position + i); cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); std::cout << getCharacter(i); } } private: int length; std::vector<Symbol> symbols; bool epilepsyMode; int lineColor; void generateNewSymbol(int index) { char newChar = getRandomCharacter(); int color = epilepsyMode ? getRandomColor() : 10; symbols[index] = Symbol(newChar, color); } static char getRandomCharacter() { const char characters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+[]{}|;':\",.<>?`~"; return characters[rand() % (sizeof(characters) - 1)]; } static int getRandomColor() { return 1 + rand() % 15; } static void setColor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } char getCharacter(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getCharacter(); } return ' '; } int getColor(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getColor(); } return 7; } };Основные моменты:
-
Генерация символов: Теперь в режиме эпилепсии каждый новый символ получает случайный цвет, а не только вся линия. Это может помочь в стилистике, если это необходимо.
-
Задание цвета в
draw: Переустанавливаем цвет непосредственно перед выводом символа, чтобы отображать его цвет правильно.
Это должно решить проблему с потерей цвета и обеспечить корректную цветовую схему для движущейся линии.
-
- User
при обоих цветовых режимах крайний правый символ всегда должен быть белым, а при режиме эпилепсии у каждой отдельной линии должен быть свой рандомный цвет
#include #include #include #include #include #include <conio.h> #include <windows.h>
class Symbol { public: Symbol(char character = ' ', int color = 10) : character(character), color(color) {}
char getCharacter() const { return character; } void setCharacter(char character) { this->character = character; } int getColor() const { return color; } void setColor(int color) { this->color = color; }private: char character; int color; };
class Line { public: Line(int length, bool epilepsyMode) : length(length), epilepsyMode(epilepsyMode) { lineColor = epilepsyMode ? getRandomColor() : 10;
for (int i = 0; i < length; ++i) { char randomChar = getRandomCharacter(); int color = epilepsyMode ? getRandomColor() : 10; symbols.push_back(Symbol(randomChar, color)); } symbols[length - 1].setColor(15); // Последний символ цветом 15 (белый) } void move() { // Затираем первый символ, добавляя пробел и цвет по умолчанию symbols[0] = Symbol(' ', 7); // Сдвигаем все символы один шаг влево for (int i = 1; i < length - 1; ++i) { symbols[i] = symbols[i + 1]; } // Новый символ на правом конце generateNewSymbol(length - 1); } void draw(HANDLE hConsole, int position, int consoleWidth, int startPosition) const { COORD cursorPos; // Удаляем старые символы за границами if (position - 1 >= 0 && position - 1 < consoleWidth) { cursorPos.X = static_cast<SHORT>(position - 1); cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); std::cout << " "; } // Рисуем видимую часть линии int startIndex = std::max(0, -position); int visibleLength = std::min(length - startIndex, consoleWidth - position); for (int i = startIndex; i < startIndex + visibleLength; ++i) { setColor(getColor(i)); cursorPos.X = static_cast<SHORT>(position + i); cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); std::cout << getCharacter(i); } }private: int length; std::vector symbols; bool epilepsyMode; int lineColor;
void generateNewSymbol(int index) { char newChar = getRandomCharacter(); int color = epilepsyMode ? getRandomColor() : 10; symbols[index] = Symbol(newChar, color); } static char getRandomCharacter() { const char characters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+[]{}|;':\",.<>?`~"; return characters[rand() % (sizeof(characters) - 1)]; } static int getRandomColor() { return 1 + rand() % 15; } static void setColor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } char getCharacter(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getCharacter(); } return ' '; } int getColor(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getColor(); } return 7; }};
class AppManager { public: AppManager() : speed(1), length(10), epilepsyMode(false), running(true) { srand(static_cast(time(nullptr))); getConsoleSize(); }
void start() { configureSettings(); HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO cursorInfo; GetConsoleCursorInfo(hConsole, &cursorInfo); cursorInfo.bVisible = FALSE; SetConsoleCursorInfo(hConsole, &cursorInfo); std::cout << "Matrix Simulation is starting..." << std::endl; while (running) { int startPosition = rand() % (consoleHeight - 1); Line line(length, epilepsyMode); int position = -length; while (position < consoleWidth) { line.draw(hConsole, position, consoleWidth, startPosition); std::this_thread::sleep_for(std::chrono::milliseconds(1000 / speed)); line.move(); ++position; if (_kbhit() && _getch() == 'q') { running = false; break; } } if (epilepsyMode) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); } } }private: int speed; int length; bool epilepsyMode; bool running; int consoleWidth; int consoleHeight;
void configureSettings() { std::cout << "Welcome to the Matrix Simulation!" << std::endl; while (true) { std::cout << "Enter speed (1 - 30): "; if (std::cin >> speed && speed >= 1 && speed <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } while (true) { std::cout << "Enter line length (1 - 30): "; if (std::cin >> length && length >= 1 && length <= 30) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter a number between 1 and 30." << std::endl; } char epilepsyInput; while (true) { std::cout << "Epilepsy mode (Y/N)? "; if (std::cin >> epilepsyInput && (epilepsyInput == 'Y' || epilepsyInput == 'y' || epilepsyInput == 'N' || epilepsyInput == 'n')) break; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid input. Please enter 'Y' or 'N'." << std::endl; } epilepsyMode = (epilepsyInput == 'Y' || epilepsyInput == 'y'); } void getConsoleSize() { CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); consoleWidth = csbi.srWindow.Right - csbi.srWindow.Left + 1; consoleHeight = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; }};
int main() { AppManager appManager; appManager.start();
return 0;}
- Assistant
Чтобы реализовать ваше требование, нужно немного изменить логику программы:
-
Крайний правый символ всегда должен быть белым: Для этого мы можем установить цвет для последнего символа прямо при создании каждой новой линии и поддерживать его в методе
move. -
Эпилептический режим: Каждая новая линия должна получать уникальный случайный цвет, если включен режим эпилепсии.
Внесем необходимые изменения в код:
class Line { public: Line(int length, bool epilepsyMode) : length(length), epilepsyMode(epilepsyMode) { // Устанавливаем уникальный случайный цвет для всей линии в режиме эпилепсии lineColor = epilepsyMode ? getRandomColor() : 10; for (int i = 0; i < length; ++i) { char randomChar = getRandomCharacter(); // Используем общий цвет для всей линии в режиме эпилепсии int color = (epilepsyMode ? lineColor : 10); symbols.push_back(Symbol(randomChar, color)); } // Устанавливаем крайний правый символ в белый symbols[length - 1].setColor(15); // Последний символ цветом 15 (белый) } void move() { // Сдвигаем все символы один шаг влево for (int i = 0; i < length - 1; ++i) { symbols[i] = symbols[i + 1]; } // Генерация нового символа для крайнего правого generateNewSymbol(length - 1); // Устанавливаем крайний символ в белый symbols[length - 1].setColor(15); } void draw(HANDLE hConsole, int position, int consoleWidth, int startPosition) const { COORD cursorPos; // Удаляем старые символы за границами if (position - 1 >= 0 && position - 1 < consoleWidth) { cursorPos.X = static_cast<SHORT>(position - 1); cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); std::cout << " "; } // Рисуем видимую часть линии int startIndex = std::max(0, -position); int visibleLength = std::min(length - startIndex, consoleWidth - position); for (int i = startIndex; i < startIndex + visibleLength; ++i) { setColor(getColor(i)); cursorPos.X = static_cast<SHORT>(position + i); cursorPos.Y = startPosition; SetConsoleCursorPosition(hConsole, cursorPos); std::cout << getCharacter(i); } } private: int length; std::vector<Symbol> symbols; bool epilepsyMode; int lineColor; void generateNewSymbol(int index) { char newChar = getRandomCharacter(); int color = (epilepsyMode ? lineColor : 10); symbols[index] = Symbol(newChar, color); } static char getRandomCharacter() { const char characters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+[]{}|;':\",.<>?`~"; return characters[rand() % (sizeof(characters) - 1)]; } static int getRandomColor() { return 1 + rand() % 15; } static void setColor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } char getCharacter(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getCharacter(); } return ' '; } int getColor(int index) const { if (index >= 0 && index < symbols.size()) { return symbols[index].getColor(); } return 7; } };Основные изменения:
-
Единый цвет для линии в режиме эпилепсии: Каждый символ в линии, кроме последнего, наследует цвет обнаруженной линии.
-
Крайний правый символ всегда белый: В
generateNewSymbolи после каждогоmove()методsetColor(15)используется для изменения цвета последнего символа на белый. -
Shift логика: Все символы копируются на одну позицию влево, а новый символ с цветом линии добавляется в конец (последний) позицию с белым цветом.
Эти изменения помогут вам добиться нужного эффекта, когда каждая линия имеет свое собственное случайное окрашивание в режиме эпилепсии, а крайний правый символ всегда белый.
-