From d6e09fa0969faccbf7bf7cd100e38e6d6c710fe7 Mon Sep 17 00:00:00 2001 From: h45-taylor <harvey.taylor3@live.uwe.ac.uk> Date: Wed, 10 Jan 2024 19:13:16 +0000 Subject: [PATCH] added move left and right functions --- 2048.cpp | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++--- game.hpp | 3 +-- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/2048.cpp b/2048.cpp index ad08f06..46af5da 100644 --- a/2048.cpp +++ b/2048.cpp @@ -105,11 +105,64 @@ void Board::userInput() { } void Board::moveLeft() { - // create + for (int i = 0; i < SIZE; ++i) { + // Slide tiles to the left + for (int j = 0; j < SIZE - 1; ++j) { + if (board[i][j] == 0) { // If the current tile is empty move the numbers left + for (int k = j + 1; k < SIZE; ++k) { + if (board[i][k] != 0) { //checks if the position to the left is empty + board[i][j] = board[i][k]; // moves the current tile as far left as it can without merging + board[i][k] = 0; // sets the original tile to 0 + moved = true; // set movement bool to true to not allow 2 moves at once + break; + } + } + + } else { + // If the current tile is not empty, try to merge with the next tile + for (int k = j + 1; k < SIZE; ++k) { + if (board[i][k] != 0) { //check if there is a number to the left + if (board[i][j] == board[i][k]) { // If Number in Grid position i j match i k + board[i][j] *= 2; // then double the value of the left tile + board[i][k] = 0; // set the tile to the right of the merged one to 0 + moved = true; // set movement bool to true + } + break; + } + } + } + } + } } - void Board::moveRight() { - // create + for (int i = 0; i < SIZE; ++i) { + // Slide tiles to the left + for (int j = 0; j < SIZE - 1; ++j) { + if (board[i][j] == 0) { // If the current tile is empty move the numbers left + for (int k = j + 1; k < SIZE; ++k) { + if (board[i][k] != 0) { + board[i][j] = board[i][k]; + board[i][k] = 0; + moved = true; // set movement bool to true to not allow 2 moves at once + break; + } + } + + } else { + // If the current tile is not empty, try to merge with the next tile + for (int k = j + 1; k < SIZE; ++k) { + if (board[i][k] != 0) { //check if there is a number to the left + if (board[i][k] == board[i][j]) { // If Number in Grid position i j match i k + board[i][k] *= 2; // then double the value of the left tile + board[i][j] = 0; // set the tile to the right of the merged one to 0 + moved = true; // set movement bool to true + } + break; + } + } + } + } + } } void Board::moveUp() { diff --git a/game.hpp b/game.hpp index 3cdc8dd..082be87 100644 --- a/game.hpp +++ b/game.hpp @@ -23,5 +23,4 @@ public: Board(); void run(); -}; -#endif \ No newline at end of file +}; \ No newline at end of file -- GitLab