Skip to content

Commit

Permalink
Now the terminal screen is resized to fit the game if one or both dim…
Browse files Browse the repository at this point in the history
…ensions are too small. At exit, it restores the terminal window to its original size.
  • Loading branch information
razterizer committed Oct 10, 2024
1 parent 371629c commit 710f805
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
13 changes: 13 additions & 0 deletions GameEngine.h
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ class GameEngine
HiScoreItem curr_score_item;
int hiscore_caret_idx = 0;

int term_win_rows = 0;
int term_win_cols = 0;


bool handle_hiscores(const HiScoreItem& curr_hsi)
{
const int c_max_num_hiscores = 20;
Expand Down Expand Up @@ -217,6 +221,13 @@ class GameEngine
return_cursor();
hide_cursor();

std::tie(term_win_rows, term_win_cols) = get_terminal_window_size();
int new_rows = term_win_rows;
int new_cols = term_win_cols;
math::maximize(new_rows, NR + 1);
math::maximize(new_cols, NC);
resize_terminal_window(new_rows, new_cols);

//nodelay(stdscr, TRUE);

curr_rnd_seed = rnd::srand_time();
Expand Down Expand Up @@ -251,6 +262,8 @@ class GameEngine
{
restore_cursor();
show_cursor();
if (term_win_rows > 0 && term_win_cols > 0)
resize_terminal_window(term_win_rows, term_win_cols);
on_quit();
}

Expand Down
37 changes: 37 additions & 0 deletions Screen.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@
#ifdef _WIN32
#define NOMINMAX // Should fix the std::min()/max() and std::numeric_limits<T>::min()/max() compilation problems.
#include <windows.h>
#else
#include <sys/ioctl.h>
#include <unistd.h>
#endif
#include <ranges>


// Game Over
int game_over_timer = 10;
int you_won_timer = 10;
Expand Down Expand Up @@ -103,6 +107,39 @@ void gotorc(int r, int c)
#endif
}

std::pair<int, int> get_terminal_window_size()
{
int rows = 0;
int cols = 0;
#ifdef _WIN32
// Windows-specific code
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) {
cols = csbi.srWindow.Right - csbi.srWindow.Left + 1;
rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
} else {
// If we fail to get the size
rows = cols = -1;
}
#else
// POSIX (Linux/macOS) specific code
struct winsize size;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0) {
rows = size.ws_row;
cols = size.ws_col;
} else {
// If we fail to get the size
rows = cols = -1;
}
#endif
return { rows, cols };
}

void resize_terminal_window(int nr, int nc)
{
std::cout << "\033[8;" << nr + 1 << ";" << nc << "t"; // Resize terminal.
}

template<int NR, int NC>
void draw_frame(SpriteHandler<NR, NC>& sh, Color fg_color)
{
Expand Down

0 comments on commit 710f805

Please sign in to comment.