From f864f31f8ef206a363d0dac43558d42c5db46baa Mon Sep 17 00:00:00 2001 From: Adrian Kummerlaender Date: Sat, 10 Dec 2016 12:42:20 +0100 Subject: Enable offset world drawing; center in viewport --- life.cc | 32 ++++++++++++++++++++------------ src/world.h | 14 ++++++++++++-- 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/life.cc b/life.cc index 6d98a08..d76055b 100644 --- a/life.cc +++ b/life.cc @@ -19,21 +19,25 @@ template< std::size_t WIDTH, std::size_t HEIGHT > -void draw(life::World& world) { +void draw( + std::size_t x, + std::size_t y, + life::World& world +) { tb_clear(); for ( std::size_t i = 0; i < HEIGHT; i++ ) { for ( std::size_t j = 0; j < WIDTH; j++ ) { if ( world.isLifeAt(i,j) ) { - tb_change_cell(i, j, 0x2588, TB_BLACK, TB_GREEN); + tb_change_cell(x+i, y+j, 0x2588, TB_BLACK, TB_GREEN); } else { - tb_change_cell(i, j, 0x2591, TB_BLACK, TB_BLUE); + tb_change_cell(x+i, y+j, 0x2591, TB_BLACK, TB_BLUE); } } } - print_tb(1, 21, TB_WHITE, TB_DEFAULT, "Age:"); - print_tb(6, 21, TB_WHITE, TB_DEFAULT, std::to_string(world.getAge())); + print_tb(x+1, y+21, TB_WHITE, TB_DEFAULT, "Age:"); + print_tb(x+6, y+21, TB_WHITE, TB_DEFAULT, std::to_string(world.getAge())); tb_present(); } @@ -42,11 +46,14 @@ int main(int, char*[]) { tb_init(); tb_select_output_mode(TB_OUTPUT_NORMAL); - tb_select_input_mode(TB_INPUT_ESC | TB_INPUT_MOUSE); + tb_select_input_mode(TB_INPUT_ESC | TB_INPUT_MOUSE); life::World<20,20> world; - draw(world); + std::size_t worldOffsetX = tb_width() / 2 - 10; + std::size_t worldOffsetY = tb_height() / 2 - 10; + + draw(worldOffsetX, worldOffsetY, world); while ( true ) { struct tb_event ev; @@ -57,7 +64,7 @@ int main(int, char*[]) { return -1; } - switch (t) { + switch ( t ) { case TB_EVENT_KEY: switch ( ev.key ) { case TB_KEY_ESC: @@ -69,16 +76,17 @@ int main(int, char*[]) { } break; case TB_EVENT_MOUSE: - if (ev.key == TB_KEY_MOUSE_LEFT) { - world.summonLifeAt(ev.x, ev.y); + if ( ev.key == TB_KEY_MOUSE_LEFT ) { + world.summonLifeAt(ev.x - worldOffsetX, ev.y - worldOffsetY); } - break; case TB_EVENT_RESIZE: + worldOffsetX = ev.w / 2 - 10; + worldOffsetY = ev.h / 2 - 10; break; } - draw(world); + draw(worldOffsetX, worldOffsetY, world); } return 0; diff --git a/src/world.h b/src/world.h index d951cf5..72cc32f 100644 --- a/src/world.h +++ b/src/world.h @@ -69,11 +69,21 @@ class World { } void summonLifeAt(std::size_t x, std::size_t y) { - this->matrix_[y][x] = true; + if ( x >= 0 && + x < WIDTH && + y >= 0 && + y < HEIGHT ) { + this->matrix_[y][x] = true; + } } void extinguishLifeAt(std::size_t x, std::size_t y) { - this->matrix_[y][x] = false; + if ( x >= 0 && + x < WIDTH && + y >= 0 && + y < HEIGHT ) { + this->matrix_[y][x] = false; + } } void tick() { -- cgit v1.2.3