diff --git a/conway.c b/conway.c index c618448..fbd919e 100644 --- a/conway.c +++ b/conway.c @@ -1,6 +1,7 @@ // A console conway's game of life program by Bruce Hill // Released under the MIT license, see LICENSE for details. #include +#include #include #include #include @@ -11,8 +12,9 @@ #define CELL(cells, x, y) cells[(((y)+H) % H)*W + (((x)+W) % W)] static char rules[2][9] = {{0,0,0,1,0,0,0,0,0}, {0,0,1,1,0,0,0,0,0}}; -static unsigned int W, H; +static unsigned int W = 0, H = 0; static char alive_color[64] = "\033[47m", dead_color[64] = "\033[0m"; +int ttyin_fd = -1; static void update(FILE *out, const char *cells, char *future_cells) { @@ -39,6 +41,16 @@ static void update(FILE *out, const char *cells, char *future_cells) fflush(out); } +static void update_term_size(int sig) +{ + (void)sig; + struct winsize sz = {0}; + ioctl(ttyin_fd, TIOCGWINSZ, &sz); + W = sz.ws_col / 2; + H = sz.ws_row; + printf("WINSIZE: %d, %d", W, H); +} + static int gethexrgb(const char *str, int *r, int *g, int *b) { if (str[0] == '#') ++str; @@ -86,7 +98,7 @@ int main(int argc, char **argv) { } } - int ttyin_fd = open("/dev/tty", O_RDONLY | O_NONBLOCK); + ttyin_fd = open("/dev/tty", O_RDONLY | O_NONBLOCK); if (ttyin_fd < 0) { fprintf(stderr, "Couldn't open terminal input.\n"); return 1; @@ -107,7 +119,6 @@ int main(int argc, char **argv) { return 1; struct winsize wsize = {0}; - ioctl(STDOUT_FILENO, TIOCGWINSZ, &wsize); fputs("\033[?25l" // Hide cursor "\033[?1049;" // Use alternate screen "1000;" // Enable mouse x/y on press @@ -115,12 +126,14 @@ int main(int argc, char **argv) { "1006" // Use mouse SGR mode "h", tty_out); + update_term_size(0); + signal(SIGWINCH, update_term_size); + char *buffers[2]; - int flipflop = 0; + int flipflop = 0, prev_W = W, prev_H = H; resize: // TODO: handle resize in SIGWINCH handler // Cells are 2 characters wide so they look square - W = wsize.ws_col/2, H = wsize.ws_row; buffers[0] = calloc(W*H, sizeof(char)); buffers[1] = calloc(W*H, sizeof(char)); for (int x = 0; x < W; x++) @@ -130,6 +143,14 @@ int main(int argc, char **argv) { int draw_mode = 1, paused = 0; fputs("\033[2J", tty_out); while (1) { + if (prev_W != W || prev_H != H) { + prev_W = W, prev_H = H; + free(buffers[0]); + free(buffers[1]); + buffers[0] = calloc(W*H, sizeof(char)); + buffers[1] = calloc(W*H, sizeof(char)); + goto resize; + } if (!paused) { update(tty_out, buffers[flipflop], buffers[!flipflop]); flipflop = !flipflop;