Currently, I have a function that loops to gather input for program execution, but I feel that it is a bit lacking, overthought and unoptimized. I would love any input on the process, coding style, or usability of the function.
I feel like the use of while (true) is not really optimized here.
My code uses curses and unistd.h.
// Heart of the display of the program
void startEvolutionLoop (Grid* grid, size_t speed) {
clear();
// Infinitely loops until 'q' is pressed
while (true) {
// First of all displays the grid with supporting information
displayGrid(grid);
printw("[Space] Evolve once [Enter] Run evolutions [q] Exit\n");
// Gets the most recently touched character
int c = getch();
// - if space (' ') evolves and loops again
// - if ('q') ends the loops
// - if enter ('\n') starts a sub-loop similar to the main one, but waits for any character to stop
if (c == ' ') {
grid->evolve();
} else if (c == 'q') {
return;
} else if (c == '\n') {
nodelay(stdscr, TRUE); // Getting of the input is asyncronous
// Infinitely loops until any key is pressed
while (true) {
grid->evolve();
displayGrid(grid);
printw("Press any key to end execution... \n"); // Extra whitespace to override previously written stuff in this area
// If there has been something inputted, then break out of this sub-loop
if (getch() != ERR) {
break;
}
usleep((__useconds_t)speed * 1000); // Sleep the desired amount of time (in micro seconds converted to milliseconds)
}
}
}
}
For context (which is not necessary), you can check out my GitHub Repo.