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.
This commit is contained in:
AnotherTest 2020-08-19 18:24:03 +04:30 committed by Andreas Kling
parent 16e86a3dda
commit 40c16b3ce5
Notes: sideshowbarker 2024-07-19 03:23:26 +09:00
3 changed files with 11 additions and 13 deletions

View file

@ -27,14 +27,13 @@
#include "Game.h"
#include <stdlib.h>
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;

View file

@ -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 };

View file

@ -75,7 +75,7 @@ int main(int argc, char** argv)
main_widget.set_layout<GUI::VerticalBoxLayout>();
main_widget.set_fill_with_background_color(true);
Game game { 4, 4 };
Game game { 4 };
auto& board_view = main_widget.add<BoardView>(&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();
};