Minesweeper implementation using C++ and Qt.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

108 lines
3.2 KiB

#include "board.h"
//Constructor that creates the board of the game for a size
Board::Board(int Nbombs, int rows, int cols){
this->rows=rows;
this->cols=cols;
this->Nbombs=Nbombs;
for(int j=0;j<rows;j++){ //Start-up empty gameBoard
gameBoard.push_back(QVector<int>(cols));
for(int k=0;k<cols;k++){
gameBoard[j][k] = 0;
}
}
srand(time(NULL)); //seed
for (int i=0;i<Nbombs;i++){
int x,y;
x=rand()%rows; //x between 0 and number of rows
y=rand()%cols; //y between 0 and number of columns
if(gameBoard[x][y]==0){ //No bomb previously there
gameBoard[x][y]=-1;
}
else i=i-1; //fix counter
}
//Scan all the vector and calculate the number of neighbor bombs in positions that don't have a bomb
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
if (gameBoard[i][j] != -1){
gameBoard[i][j] = calculateNeighborsBombs(i,j);
}
}
}
}
//Constructor that takes an already made board
Board::Board(QVector< QVector<int> > board){
rows = board.size();
cols = board.at(0).size();
this->gameBoard = board;
int sum = 0;
//Calculate how many bombs the board has
for(int i=0; i<rows; ++i){
for(int j=0; j<cols; ++j){
if(gameBoard.at(i).at(j) == -1){
++sum;
}
}
}
Nbombs = sum;
}
//Method that calculates and returns the number of neighbors bombs of a position (x,y) in the board
int Board::calculateNeighborsBombs(int x,int y){
int sum=0;
if(gameBoard.at(x).at(y) != -1){ //No bomb in gameBoard[x][y]
for(int i=x-1; i<x+2; i++){
for(int j=y-1; j<y+2; j++){
if(isInsideTheBoard(i,j)){
if(gameBoard.at(i).at(j) == -1){ //bomb in gameBoard[i][j]
sum=sum+1;
}
}
}
}
}
return sum;
}
bool Board::isInsideTheBoard(int x, int y){
return ((x < rows) && (x >= 0) && (y < cols) && (y >= 0));
}
//Return the vector of the board
QVector< QVector<int> > Board::getBoard(){
return gameBoard;
}
//Return the number of bombs of a position x,y
int Board::getNumberOfBombs(int x,int y){
return gameBoard[x][y];
}
int Board::getNbombs() const{
return Nbombs;
}
//Return the board with data encrypted
QVector<QVector<int> > Board::getEncryption(){
QVector< QVector<int> > encrypt(gameBoard.size(), QVector<int>(gameBoard.at(0).size()));
for(int i=0; i<gameBoard.size(); ++i){
for(int j=0; j<gameBoard.at(i).size(); ++j){
encrypt[i].replace(j,(gameBoard.at(i).at(j) ^ XOR_NUM) + i);
}
}
return encrypt;
}
//Return the decrypted board
QVector< QVector<int> > Board::getDecryption(QVector< QVector<int> > board){
QVector< QVector<int> > decrypt(board.size(), QVector<int>(board.at(0).size()));
for(int i=0; i<board.size(); ++i){
for(int j=0; j<board.at(i).size(); ++j){
decrypt[i].replace(j,((board.at(i).at(j) - i) ^ XOR_NUM));
}
}
return decrypt;
}