From 40c16b3ce542f0446618fefe466b159e5ed2c3c2 Mon Sep 17 00:00:00 2001 From: AnotherTest Date: Wed, 19 Aug 2020 18:24:03 +0430 Subject: [PATCH] 2048: Do not allow the creation of games with invalid board sizes The logic only works with nxn grids, so no need to take separate row_size/column_size arguments. --- Games/2048/Game.cpp | 15 +++++++-------- Games/2048/Game.h | 5 ++--- Games/2048/main.cpp | 4 ++-- 3 files changed, 11 insertions(+), 13 deletions(-) diff --git a/Games/2048/Game.cpp b/Games/2048/Game.cpp index 244548db8e1..cf029426bb8 100644 --- a/Games/2048/Game.cpp +++ b/Games/2048/Game.cpp @@ -27,14 +27,13 @@ #include "Game.h" #include -Game::Game(size_t rows, size_t columns) - : m_rows(rows) - , m_columns(columns) +Game::Game(size_t grid_size) + : m_grid_size(grid_size) { - m_board.resize(rows); + m_board.resize(grid_size); for (auto& row : m_board) { - row.ensure_capacity(columns); - for (size_t i = 0; i < columns; i++) + row.ensure_capacity(grid_size); + for (size_t i = 0; i < grid_size; i++) row.append(0); } @@ -47,8 +46,8 @@ void Game::add_random_tile() int row; int column; do { - row = rand() % m_rows; - column = rand() % m_columns; + row = rand() % m_grid_size; + column = rand() % m_grid_size; } while (m_board[row][column] != 0); size_t value = rand() < RAND_MAX * 0.9 ? 2 : 4; diff --git a/Games/2048/Game.h b/Games/2048/Game.h index dfaad90a9ce..031364f7017 100644 --- a/Games/2048/Game.h +++ b/Games/2048/Game.h @@ -30,7 +30,7 @@ class Game final { public: - Game(size_t rows, size_t columns); + Game(size_t); Game(const Game&) = default; enum class MoveOutcome { @@ -59,8 +59,7 @@ public: private: void add_random_tile(); - size_t m_rows { 0 }; - size_t m_columns { 0 }; + size_t m_grid_size { 0 }; Board m_board; size_t m_score { 0 }; diff --git a/Games/2048/main.cpp b/Games/2048/main.cpp index c65be54ffb1..22d0dd82be2 100644 --- a/Games/2048/main.cpp +++ b/Games/2048/main.cpp @@ -75,7 +75,7 @@ int main(int argc, char** argv) main_widget.set_layout(); main_widget.set_fill_with_background_color(true); - Game game { 4, 4 }; + Game game { 4 }; auto& board_view = main_widget.add(&game.board()); board_view.set_focus(true); @@ -90,7 +90,7 @@ int main(int argc, char** argv) update(); auto start_a_new_game = [&]() { - game = Game(4, 4); + game = Game(4); update(); };