Function to check whether the game has ended - c++

From looking at the below solution, can someone please tell me how can I implement a function to check whether the game has ended? I attempted this by creating "int checkEndGame" which loops through the board and returns either a 1 or 0 but it doesn't work.
Header:
#include <iostream>
#include <string>
#include <time.h>
int generations;
int boardWidth;
int boardHeight;
char** board;
char** boardTmp;
char deadOrAlive[] = {' ', 'x'};
char dead = deadOrAlive[0];
char alive = deadOrAlive[1];
char lookLeft(int i, int j)
{
if ( i == 0)
{
return dead;
}
return board[i - 1][j];
}
char lookRight(int i, int j)
{
if (i == boardWidth - 1)
{
return dead;
}
return board[i + 1][j];
}
char lookUp(int i, int j)
{
if (j == 0)
{
return dead;
}
return board[i][j - 1];
}
char lookDown(int i, int j)
{
if (j == boardHeight - 1)
{
return dead;
}
return board[i][j + 1];
}
char lookUpLeft(int i, int j)
{
if (i == 0 || j == 0)
{
return dead;
}
return board[i - 1][j - 1];
}
char lookUpRight(int i, int j)
{
if(i == boardWidth - 1 || j == 0)
{
return dead;
}
return board[i + 1][j + 1];
}
char lookDownLeft(int i, int j)
{
if (j == boardHeight - 1 || i == 0)
{
return dead;
}
return board[i - 1][j + 1];
}
char lookDownRight(int i, int j)
{
if (j == boardHeight - 1 || i == boardWidth - 1)
{
return dead;
}
return board[i + 1][j + 1];
}
char ans;
void init();
void setBoard();
void showBoard();
void verifyDeadOrAlive();
int getNeighbors(int i, int j);
void swap();
void sleep(unsigned int mseconds);
int checkEndGame();
void playGame();
c++:
#include "stdafx.h"
#include "gameoflife.h"
using namespace std;
void init()
{
cout << "How many generations would you like to cycle through? ";
cin >> generations;
cout << "Specify a width for the board: ";
cin >> boardWidth;
cout << "Specify a height for the board: ";
cin >> boardHeight;
}
void setBoard()
{
srand(time(0));
board = new char*[boardWidth];
boardTmp = new char*[boardWidth];
for (int i = 0; i < boardWidth; ++i)
{
board[i] = new char[boardHeight];
boardTmp[i] = new char[boardHeight];
for (int j = 0; j < boardHeight; ++j)
{
board[i][j] = deadOrAlive[rand() % generations];
boardTmp[i][j] = ' ';
}
}
}
void showBoard()
{
system("cls");
for (int j = 0; j < boardHeight; ++j)
{
for (int i = 0; i < boardWidth; ++i)
{
cout << board[i][j];
}
cout << endl;
}
}
void verifyDeadOrAlive()
{
for (int j = 0; j < boardHeight; ++j)
{
for (int i = 0; i < boardWidth; ++i)
{
int neighbors = getNeighbors(i, j);
if (board[i][j] == alive)
{
if (neighbors < 2 || neighbors > 3)
{
boardTmp[i][j] = dead;
}
else
{
boardTmp[i][j] = alive;
}
}
else
{
if (neighbors == 3)
{
boardTmp[i][j] = alive;
}
else
{
boardTmp[i][j] = dead;
}
}
}
}
swap();
}
int getNeighbors(int i, int j)
{
int x = 0;
if (lookLeft(i, j) == alive)
{
x++;
}
if (lookRight(i, j) == alive)
{
x++;
}
if (lookUp(i, j) == alive)
{
x++;
}
if (lookDown(i, j) == alive)
{
x++;
}
if (lookUpLeft(i, j) == alive)
{
x++;
}
if (lookUpRight(i, j) == alive)
{
x++;
}
if (lookDownLeft(i, j) == alive)
{
x++;
}
if (lookDownRight(i, j) == alive)
{
x++;
}
return x;
}
void swap()
{
char** tmp = board;
board = boardTmp;
boardTmp = tmp;
}
void sleep(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
int checkEndGame()
{
for (int j = 0; j < boardHeight; ++j)
{
for (int i = 0; i < boardWidth; ++i)
{
if (board[i][j] == dead)
{
return 1;
}
else
{
return 0;
}
}
}
}
void playGame()
{
init();
setBoard();
do
{
showBoard();
sleep(500);
verifyDeadOrAlive();
checkEndGame();
}
while (checkEndGame == 0);
}
int main()
{
do
{
playGame();
cout << "Would you like to play again? y/n: ";
cin >> ans;
system("cls");
}
while (ans == 'Y' || ans == 'y');
return 0;
}

You want this:
int checkEndGame()
{
for (int j = 0; j < boardHeight; ++j)
{
for (int i = 0; i < boardWidth; ++i)
{
if (board[i][j] == alive)
return 0;
}
}
return 1;
}
Your function returns the moment it sees one dead cell, which is incorrect. You can abort if you see one live cell. But otherwise, you need to check every cell.
Also:
checkEndGame();
}
while (checkEndGame == 0);
is broken. checkEndGame will never be zero since it's a pointer to a function. You want:
}
while (checkEndGame() == 0);

a
You function should be like that:
int checkEndGame()
{
for (int j = 0; j < boardHeight; ++j)
{
for (int i = 0; i < boardWidth; ++i)
{
if (board[i][j] == alive){return 0; }
}
}
return 1;
}
Because you either find "alive" and say game is not over yet, or have to go through the hole board and then say the game is over because you haven't found "alive".
And as said before:
while(checkEndGame==0)
doesn't run the function to see what the returned value is, done this way all it does is checking if the memory address of you function is 0 (which it will most certainly never be unless you assign it).
to run the function and see the returned value you have to write:
while(checkEndGame()==0)
(notice the "()" at the end)

Related

How to fix signal SIGSEGV, Segmentation fault

I'm getting an error message in Codeblocks C++ 'Program received signal SIGSEGV, Segmentation fault' in comparison between a vector element and a size of vector of vectors inside for loop (line 133 if (parz_przestrzenie[i] != parz_dystanse[i].size())).
Could anyone tell me why?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int bloki_parz[100000], bloki_nieparz[100000];
int silnia(int n)
{
int liczba = 1;
for (int i = 1; i <= n; i++)
{
liczba *= i;
}
return liczba;
}
int main()
{
int n, czapka, wolne_miejsca = 0, wynik = 1;
vector<int> parz, nieparz, parz_przestrzenie, nieparz_przestrzenie, parz_przestrzenie2, nieparz_przestrzenie2;
vector<vector<int>> parz_dystanse;
vector<vector<int>> nieparz_dystanse;
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> czapka;
if (i % 2 == 0)
{
parz.push_back(czapka);
}
else
{
nieparz.push_back(czapka);
}
}
int parz_size = parz.size(), nieparz_size = nieparz.size();
// sprawdzamy czy dane nie sÂą sprzeczne ; gdy zabraknie nam miejsc do rozmieszczania
vector<int> parz_duplicate = parz;
vector<int> nieparz_duplicate = nieparz;
parz_duplicate.erase(unique(parz_duplicate.begin(), parz_duplicate.end()), parz_duplicate.end());
nieparz_duplicate.erase(unique(nieparz_duplicate.begin(), nieparz_duplicate.end()), nieparz_duplicate.end());
int parz_dupl_size = parz_duplicate.size(), nieparz_dupl_size = nieparz_duplicate.size();
if (parz_size < nieparz_dupl_size)
{
cout << 0 << endl;
return 0;
}
if (nieparz_size < parz_dupl_size)
{
cout << 0 << endl;
return 0;
}
for (int i = 0; i < parz_size - 1; i++)
{
if (parz[i] == parz[i + 1])
{
bloki_parz[i + 1] = 1;
}
}
for (int i = 0; i < nieparz_size - 1; i++)
{
if (nieparz[i] == nieparz[i + 1])
{
bloki_nieparz[i] = 1;
}
}
for (int i = 0; i < parz_size; i++)
{
vector<int> bloczek;
for (int j = i; j < parz_size; j++)
{
if (parz[j] != parz[j + 1])
{
bloczek.push_back(parz[j]);
}
else
{
i += 1;
break;
}
}
if (bloczek.size() != 0)
{
parz_dystanse.push_back(bloczek);
}
}
int parz_dyst_size = parz_dystanse.size();
if (parz[parz_size - 1] != parz[parz_size - 2])
{
parz_dystanse[parz_dyst_size - 1].push_back(parz[parz_size - 1]);
}
for (int i = 0; i < nieparz_size; i++)
{
vector<int> bloczek;
for (int j = i; j < nieparz_size; j++)
{
if (nieparz[j] != nieparz[j + 1])
{
bloczek.push_back(nieparz[j]);
}
else
{
i += 1;
break;
}
}
if (bloczek.size() != 0)
{
nieparz_dystanse.push_back(bloczek);
}
}
int nieparz_dyst_size = nieparz_dystanse.size();
int current_wynik = 0;
for (int i = 0; i < nieparz_size; i++)
{
if (bloki_parz[i] == 0)
{
current_wynik++;
}
else
{
if (current_wynik != 0)
{
parz_przestrzenie.push_back(current_wynik);
}
current_wynik = 0;
}
}
parz_przestrzenie.push_back(current_wynik);
current_wynik = 0;
for (int i = 0; i < parz_size; i++)
{
if (bloki_nieparz[i] == 0)
{
current_wynik++;
}
else
{
if (current_wynik != 0)
{
nieparz_przestrzenie.push_back(current_wynik);
}
current_wynik = 0;
}
}
nieparz_przestrzenie.push_back(current_wynik);
int parz_przest_size = parz_przestrzenie.size(), nieparz_przest_size = nieparz_przestrzenie.size();
for (int i = 0; i < 1; i++)
{
if (parz_przestrzenie[i] != parz_dystanse[i].size())
{
wynik *= parz_przestrzenie[i];
wolne_miejsca++;
}
}
for (int i = 0; i < nieparz_przest_size; i++)
{
if (nieparz_przestrzenie[i] != nieparz_dystanse[i].size())
{
wynik *= nieparz_przestrzenie[i];
wolne_miejsca++;
}
}
cout << wynik * silnia(wolne_miejsca) << endl;
}
parz_dystanse is a vector of a vector. In this case the return value of parz_dystanse.size() is a long unsigned int, whereas an element of parz_przestrzenie is an int.
You need to make explicit that parz_dystanse.size() returns an int in order to make comparitions between integer expressions of different signedness.
This will fix that problem:
if (parz_przestrzenie[i] != (int)parz_dystanse[i].size())

Replacing nested for loops in C++

So I wrote this code but the problem is I have a restriction in my assignment that I can't use nested for loops in my code.
#include<iostream>
using namespace std;
void Exchange(int* a, int* b) {
int var;
var = *a; //For swapping or exchanging values. O_o
*a = *b;
*b = var;
}
void Algorithm(int array[], int nerd) {
int i, j, k; //This is the actual algorithm which is required. ;)
for (i = 0; i < nerd;) {
for (j = i + 1; j < nerd; j++) {
if (array[j] < array[j - 1])
Exchange(&array[j], &array[j - 1]);
}
nerd--;
for (k = nerd - 1; k > i; k--) {
if (array[k] < array[k - 1])
Exchange(&array[k], &array[k - 1]);
}
i++;
}
}
int main() {
int n, i;
cout << "\nEnter the count of numbers for the algorithm: ";
cin >> n;
int arr[10];
for (i = 0; i < n; i++) {
cout << "Enter number " << i + 1 << ": ";
cin >> arr[i];
}
Algorithm(arr, n);
cout << "\nFinal Data you entered (after the algorithm performed)";
for (i = 0; i < n; i++)
cout << " -> " << arr[i];
return 0;
}
One loop using modulus on the one loop counter:
#include <utility> // std::swap
void Algorithm(int array[], int nerd) {
int max = nerd * (nerd - 1);
for(int i = 1; i < max; ++i) {
// If at start of the removed inner loop, skip i % nerd == 0
if(i % nerd == 0) ++i;
if (array[i % nerd] < array[(i-1) % nerd])
std::swap(array[i % nerd], array[(i - 1) % nerd]);
}
}
Demo
Without modulus, decreasing nerd and restarting with i = 1 each time i == nerd:
void Algorithm(int array[], int nerd) {
for(int i = 1; nerd > 1; ++i) {
if(i == nerd) { // start of the removed inner loop
--nerd; // the highest number will already be in place
i = 1;
}
if (array[i] < array[i - 1])
std::swap(array[i], array[i - 1]);
}
std::cout << "ted " << nerd << '\n';
}
Demo
An alternative to quit looping early if no swaps were made last round:
void Algorithm(int array[], int nerd) {
if(nerd < 2) return;
bool done = true;
for(int i = 1;; ++i) {
if(i % nerd == 0) {
if(done) break;
++i;
done = true;
}
if (array[i % nerd] < array[(i-1) % nerd]) {
std::swap(array[i % nerd], array[(i-1) % nerd]);
done = false;
}
}
}
Demo
The alternative without modulus and with the decreasing nerd optimization:
void Algorithm(int array[], int nerd) {
if(nerd < 2) return;
bool done = true;
for(int i = 1;; ++i) {
if(i == nerd) {
if(done || --nerd == 1) break;
i = 1;
done = true;
}
if (array[i] < array[i - 1]) {
std::swap(array[i], array[i - 1]);
done = false;
}
}
}
Demo

C++ issue with 2D vector: When executed, your code modified memory in a way that was illegal

this is my first time posting a question in SO. I've been working in a program that tests if there are four consecutive numbers of the same value. I am using Visual Studio as my IDE and my code is compiling good, the problem is that in my class, we are posting the code through a website (Pearson) which tests if the code is correct or not. The problem that is giving me is the following: "When executed, your code modified memory in a way that was illegal. Common causes for this problem include array indexing errors and pointer operation (*) errors." My understanding of pointers is very low, but I don't see anything wrong with my code.
#include <iostream>
#include <vector>
using namespace std;
int row = 6;
int col = 7;
bool checkRow(vector<vector<int>> v) {
int count = 0;
for (int i = 0; i < row; i++) {
for (int j = 1; j < col; j++) {
if (a[i][j - 1] == a[i][j]) {
count++;
}
else {
count = 0;
} if (count == 3) {
return true;
}
} count = 0;
} return false;
}
bool checkCol(vector<vector<int>> v) {
int count = 0;
for (int i = 0; i < row; i++) {
for (int j = 1; j < col; j++) {
if (a[j - 1][i] == a[j][i]) {
count++;
}
else {
count = 0;
} if (count == 3) {
return true;
}
} count = 0;
} return false;
}
bool diagonalOne(vector<vector<int>> v) {
int count = 0;
if (row < 4 || col < 4) {
return false;
}
else {
for (int k = 3; k < col; k++) {
for (int i = 1, j = k; j > 0; i++, j--) {
if (a[i][j - 1] == a[i - 1][j]) {
count++;
}
else {
count = 0;
} if (count == 3) {
return true;
}
} count = 0;
}
int i = 1;
int j = row - 1;
int k = 0;
count = 0;
for(int i = 1; row - i > 3; i++){
k = i;
for (j = col - 1; j - 1 > i; j--, k++) {
if (a[k][j] == a[k + 1][j - 1]) {
count++;
}
else {
count = 0;
} if (count == 3) {
return true;
}
} count = 0;
} return false;
}
}
bool diagonalTwo(vector<vector<int>> v) {
int count = 0;
int i, j, k;
if (row < 4 || col > 4) {
return false;
}
else {
for (i = 1; i < col - i; i++) {
k = 0;
for (j = i; j < row; j++, k++) {
if (a[k][j] == a[k + 1][j + 1]) {
count++;
}
else {
count = 0;
} if (count == 3) {
return true;
}
} count = 0;
for (i = 0; i < row - 3; i++) {
k = i;
for (j = 0; j + 1 < row - i; j++, k++) {
if (a[k][j] == a[k + 1][j + 1]) {
count++;
}
else {
count = 0;
} if (count == 3) {
return true;
}
}
} cout << endl;
count = 0;
} return false;
}
}
bool isConsecutiveFour(vector<vector<int>> & values) {
if (checkRow(values) == true) {
return true;
} if (checkCol(values) == true) {
return true;
} if (diagonalOne(values) == true) {
return true;
} if (diagonalTwo(values) == true) {
return true;
} return false;
}
int main()
{
int i = 0;
int j = 0;
vector<vector<int>>a(row);
for (i = 0; i < row; i++) {
a[i] = vector<int>(col);
for (j = 0; j < col; j++) {
cin >> a[i][j];
}
}
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
cout << a[i][j] << " ";
} cout << endl;
}
if (isConsecutiveFour(a) == true) {
cout << "The array has consecutive fours" << endl;
}
else {
cout << "The array does not have consecutive fours" << endl;
}
system("PAUSE");
return 0;
}
The bounds on the loops inside your checkCol function are wrong, that's why a segmentation fault is occurring. Make it :
for (int i = 0; i < col; i++) {
for (int j = 1; j < row; j++) {
Same error is with diagonalOne function. Make it :
for (int k = 3; k < row; k++) {
Advice : Avoid using using namespace std and system("PAUSE"), and make yourself familiar with debugger present in VS.

I made the 2048 game but its not running as it was supposed to [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I decided to make the 2048 game. It is a very popular game for beginners.
The game is almost complete now but there's this error because of which my game keeps getting closed again and again as soon as I make my first move. I have tested a lot thoroughly and couldn't trace the error(s). I am new to programming.
#include<iostream>
#include<conio.h>
#include<ctime>
#include<string>
#include<cstdlib>
#include<fstream>
#include<Windows.h>
using namespace std;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
const int limit = 4;
int board[limit][limit] = {};
int score = 0;
string name;
int highestScore;
void newGame();
void displayBoard();
bool gameOver();
int generateNum(); //generate random 2 or 4
void moveInDirection(int);
void generateNumInBoard();
int main()
{
int currentDirection;
char command, choice;
char direction[128];
string currentName;
direction['s'] = 0;
direction['w'] = 1;
direction['a'] = 3;
direction['d'] = 2;
ifstream inFile;
inFile.open("Score.txt");
inFile >> name >> highestScore;
inFile.close();
ofstream outFile;
outFile.open("Score.txt");
cout << "Please enter your name = ";
getline(cin, currentName);
newGame();
while (true)
{
system("CLS");
displayBoard();
cout << "\nEnter what you want to do = ";
command = _getche();
if (command == 'n')
{
newGame();
}
else if (command == 'e')
{
break;
}
else
{
currentDirection = direction[command];
moveInDirection(currentDirection);
}
if (gameOver())
{
if (score > highestScore)
{
outFile << currentName << " " << score;
}
do {
system("CLS");
cout << "YOU HAVE LOST :("
<< "Your score was " << score << endl
<< "Do you want to play again ( New game (n) / Exit (e) ) = ";
command = _getche();
} while (command != 'n' && command != 'e');
if (command == 'e')
{
exit(1);
}
}
}
return 0;
}
void newGame()
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
board[i][j] = 0;
}
}
board[0][0] = 2;
}
void displayBoard()
{
SetConsoleTextAttribute(hConsole, 9);
cout << "\n2048 THE GAME\n\n a = left , s = down , w = up , d = right , n = newgame , e = exit\n\n If all boxes get filled you lose\n\nBest player = " << name << " Best score = " << highestScore << "\n\n Your Score = " << score << "\n\n" << endl;
for (int i = 0; i < limit; i++)
{
cout << "\t\t|";
for (int j = 0; j < limit; j++)
{
if (board[i][j] == 0)
{
cout << " - |";
}
else
{
cout << " " << board[i][j] << " |";
}
}
cout << endl;
}
}
void moveInDirection(int currentDirection)
{
int count = 0;
bool flag = false;
if (currentDirection == 2)
{
while (count != 4)
{
for (int i = 0; i < limit; i++)
{
for (int j = limit - 1; j > 0; j--)
{
if ((board[i][j] == board[i][j - 1]) && board[i][j] != 0 && board[i][j - 1] != 0)
{
board[i][j] += board[i][j - 1];
board[i][j - 1] = 0;
score += board[i][j];
}
else if ((board[i][j] == 0) && (board[i][j - 1] != 0))
{
flag = true;
swap(board[i][j], board[i][j - 1]);
}
}
}
count++;
}
if (flag)
{
generateNumInBoard();
}
}
else if (currentDirection == 3)
{
while (count != 4)
{
for (int i = 0; i < limit; i++)
{
for (int j = 0; j < limit - 1; j++)
{
if ((board[i][j] == board[i][j + 1]) && board[i][j] != 0 && board[i][j + 1] != 0)
{
board[i][j] += board[i][j + 1];
board[i][j + 1] = 0;
score += board[i][j];
}
else if ((board[i][j] == 0) && (board[i][j + 1] != 0))
{
flag = true;
swap(board[i][j], board[i][j + 1]);
}
}
}
count++;
}
if (flag)
{
generateNumInBoard();
}
}
else if (currentDirection == 1)
{
while (count != 4)
{
for (int i = 0; i < limit - 1; i++)
{
for (int j = 0; j < limit; j++)
{
if ((board[i][j] == board[i + 1][j]) && board[i][j] != 0 && board[i + 1][j] != 0)
{
board[i][j] += board[i + 1][j];
board[i + 1][j] = 0;
score += board[i][j];
}
else if ((board[i][j] == 0) && (board[i + 1][j] != 0))
{
flag = true;
swap(board[i][j], board[i + 1][j]);
}
}
}
count++;
}
if (flag)
{
generateNumInBoard();
}
}
else if (currentDirection == 0)
{
while (count != 4)
{
for (int i = limit - 1; i >= 0; i--)
{
for (int j = 0; j < limit; j++)
{
if ((board[i][j] == board[i - 1][j]) && board[i][j] != 0 && board[i - 1][j] != 0)
{
board[i][j] += board[i - 1][j];
board[i - 1][j] = 0;
score += board[i][j];
}
else if ((board[i][j] == 0) && (board[i - 1][j] != 0))
{
flag = true;
swap(board[i][j], board[i - 1][j]);
}
}
}
count++;
}
if (flag)
{
generateNumInBoard();
}
}
}
int generateNum()
{
srand(time(NULL));
int randomNum = rand() % 4;
if (randomNum <= 2)
{
return 2;
}
else
{
return 4;
}
}
void generateNumInBoard()
{
bool flag = true;
for (int i = 0; i < limit; i++)
{
for (int j = 0; j < limit; j++)
{
if (board[i][j] == 0)
{
board[i][j] = generateNum();
flag = false;
break;
}
}
if (flag == false)
{
break;
}
}
}
bool gameOver()
{
for (int i = 0; i < limit; i++)
{
for (int j = 0; j < limit; j++)
{
if (board[i][j] == 0)
{
return true;
}
}
}
return false;
}
You made a small blunder at the fucntion gameOver() as you are making the game end if the compiler finds any 0 in the 2D array and you are display the zero as - in front end , You just need to make he false part true and viceversa.The game will work AOK :-)
bool gameOver()
{
for (int i = 0; i < limit; i++)
{
for (int j = 0; j < limit; j++)
{
if (board[i][j] == 0)
{
return false; //You need to make this false to not end game as soon as it starts
}
}
}
return true; //You need to make this true as the end condition
}

Why is my simple recursive method's final return value always off by 1?

I'm attempting to create a text-based version of this game.
Code:
#include <iostream>
#include <vector>
#include <ctime>
class Clickomania {
public:
Clickomania();
std::vector<std::vector<int> > board;
int move(int, int);
bool isSolved();
void print();
void pushDown();
bool isValid();
};
Clickomania::Clickomania()
: board(12, std::vector<int>(8,0)) {
srand((unsigned)time(0));
for(int i = 0; i < 12; i++) {
for(int j = 0; j < 8; j++) {
int color = (rand() % 3) + 1;
board[i][j] = color;
}
}
}
void Clickomania::pushDown() {
for(int i = 0; i < 8; i++) {
for(int j = 0; j < 12; j++) {
if (board[j][i] == 0) {
for(int k = j; k > 0; k--) {
board[k][i] = board[k-1][i];
}
board[0][i] = 0;
}
}
}
}
int Clickomania::move(int row, int col) {
bool match = false;
int totalMatches = 0;
if (row > 12 || row < 0 || col > 8 || col < 0) {
return 0;
}
int currentColor = board[row][col];
board[row][col] = 0;
if ((row + 1) < 12) {
if (board[row+1][col] == currentColor)
{
match = true;
totalMatches++;
totalMatches += move(row+1, col);
}
}
if ((row - 1) >= 0) {
if (board[row-1][col] == currentColor) {
match = true;
totalMatches++;
totalMatches += move(row-1, col);
}
}
if ((col + 1) < 8) {
if (board[row][col+1] == currentColor) {
match = true;
totalMatches++;
totalMatches += move(row, col+1);
}
}
if ((col - 1) >= 0) {
if (board[row][col-1] == currentColor) {
match = true;
totalMatches++;
totalMatches += move(row, col-1);
}
}
return totalMatches;
}
void Clickomania::print() {
for(int i = 0; i < 12; i++) {
for(int j = 0; j < 8; j++) {
std::cout << board[i][j];
}
std::cout << "\n";
}
}
int main() {
Clickomania game;
game.print();
int row;
int col;
std::cout << "Enter row: ";
std::cin >> row;
std::cout << "Enter col: ";
std::cin >> col;
int numDestroyed = game.move(row,col);
game.print();
std::cout << "Destroyed: " << numDestroyed << "\n";
}
The method that is giving me trouble is my "move" method. This method, given a pair of coordinates, should delete all the squares at that coordinate with the same number and likewise with all the squares with the same number connected to it.
If you play the link I gave above you'll see how the deletion works on a click.
int Clickomania::move(int row, int col) {
bool match = false;
int totalMatches = 0;
if (row > 12 || row < 0 || col > 8 || col < 0) {
return 0;
}
int currentColor = board[row][col];
board[row][col] = 0;
if ((row + 1) < 12) {
if (board[row+1][col] == currentColor) {
match = true;
totalMatches++;
totalMatches += move(row+1, col);
}
}
if ((row - 1) >= 0) {
if (board[row-1][col] == currentColor) {
match = true;
totalMatches++;
totalMatches += move(row-1, col);
}
}
if ((col + 1) < 8) {
if (board[row][col+1] == currentColor)
{
match = true;
totalMatches++;
totalMatches += move(row, col+1);
}
}
if ((col - 1) >= 0) {
if (board[row][col-1] == currentColor) {
match = true;
totalMatches++;
totalMatches += move(row, col-1);
}
}
return totalMatches;
}
My move() method above works fine, as in it will delete the appropriate "blocks" and replace them with zeros, however the number of destroyed (value returned) is always one off (too small). I believe this is because the first call of move() isn't being counted, but I don't know how to differentiate between the first call or subsequent calls in that recursive method.
How can I modify my move() method so it returns the correct number of destroyed blocks?
It looks like you're incrementing totalMoves in the wrong place(s). You should count the match at the point where you set board[r][c] = 0 and remove the other references to totalMoves++.
You are right that the first call isn't being counted, it's only counting the recursive calls.
0 based indexing. You dont want to check > you want >=
you wanna check row >= 12 col >= 8