Created
January 1, 2025 14:34
-
-
Save haseeb-heaven/a318bd70c56c9a97ba86f0dd3c09682b to your computer and use it in GitHub Desktop.
Simulation of falling matrix in C++ 20 , modular and robust approach.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
#include <random> | |
#include <thread> | |
#include <chrono> | |
void initialize_random_seed() { | |
std::random_device rd; | |
std::srand(rd()); | |
} | |
std::vector<bool> create_column_states(int width) { | |
return std::vector<bool>(width, false); | |
} | |
std::string get_character_pool() { | |
return "1234567890qwertyuiopasdfghjklzxcvbnm,./';[]!@#$%^&*()-=_+"; | |
} | |
void toggle_random_columns(std::vector<bool>& column_states, int number_of_flips) { | |
for (int flip_index = 0; flip_index < number_of_flips; ++flip_index) { | |
int random_column_index = std::rand() % column_states.size(); | |
column_states[random_column_index] = !column_states[random_column_index]; | |
} | |
} | |
void print_matrix_line(const std::vector<bool>& column_states, const std::string& character_pool) { | |
for (size_t column_index = 0; column_index < column_states.size(); column_index += 2) { | |
if (column_states[column_index]) { | |
std::cout << character_pool[std::rand() % character_pool.size()] << " "; | |
} else { | |
std::cout << " "; | |
} | |
} | |
std::cout << '\n'; | |
} | |
void run_falling_matrix_effect(int matrix_width, int number_of_flips_per_line, int sleep_duration_milliseconds) { | |
initialize_random_seed(); | |
auto column_states = create_column_states(matrix_width); | |
auto character_pool = get_character_pool(); | |
while (true) { | |
print_matrix_line(column_states, character_pool); | |
toggle_random_columns(column_states, number_of_flips_per_line); | |
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_duration_milliseconds)); | |
} | |
} | |
int main() { | |
int matrix_width = 70; | |
int number_of_flips_per_line = 5; | |
int sleep_duration_milliseconds = 100; | |
try { | |
run_falling_matrix_effect(matrix_width, number_of_flips_per_line, sleep_duration_milliseconds); | |
} catch (const std::exception& exception) { | |
std::cerr << "Error: " << exception.what() << '\n'; | |
return EXIT_FAILURE; | |
} catch (...) { | |
std::cerr << "An unknown error occurred.\n"; | |
return EXIT_FAILURE; | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment