S3_Cpp/Aufg6/MineSweeper.cpp

103 lines
2.9 KiB
C++
Raw Permalink Normal View History

2024-11-15 00:57:31 +00:00
#include <iostream>
#include "../Aufg5/Mastermind.h"
struct MineSweeperBoard {
std::string field[16][16];
int bombCounter = 0;
void debugBoard(std::string character) {
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
field[i][j] = character;
}
}
}
bool hasBomb(int i1, int i2) {
return field[i1][i2] == "x";
}
void spreadBombs() {
while (bombCounter < 99) {
short x = getRandomNumberInRange(0,15);
short y = getRandomNumberInRange(0,15);
if (field[x][y] != "x") {
field[x][y] = "x";
bombCounter++;
}
2024-11-15 00:57:31 +00:00
}
}
2024-11-15 00:57:31 +00:00
std::string countNeighbourBombs(int i, int j) {
i--;
j--;
int counter = 0;
// int counter; // Not setting this nerd to 0 can cause a bug
2024-11-15 00:57:31 +00:00
for (int k = 0; k < 3; k++) {
for (int l = 0; l < 3; l++) {
if ((i+k < 16) && (j+l < 16) && (i+l >= 0) && (j+l >= 0)) {
// if ((i+k < 16) && (j+l < 16) && (i-l >= 0) && (j-l >= 0)) {
if (field[i+k][j+l] == "x") {
counter++;
}
}
}
}
return std::to_string(counter);
}
std::string countNeighbourBombsBetter(int i, int j) {
int counter = 0;
// int counter; // Not setting this nerd to 0 can cause a bug
for (int k = -1; k <= 1; k++) {
for (int l = -1; l <= 1; l++) {
if ((i+k < 16) && (j+l < 16) && (i+l >= 0) && (j+l >= 0)) {
2024-11-15 00:57:31 +00:00
if (field[i+k][j+l] == "x") {
counter++;
}
}
}
}
return std::to_string(counter);
}
2024-11-15 00:57:31 +00:00
void calculateExplosiveNeighbours() {
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
if (field[i][j] != "x") {
field[i][j] = countNeighbourBombs(i, j);
}
}
}
}
2024-11-15 00:57:31 +00:00
void printBoard() {
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
std::cout << field[i][j] << " ";
}
std::cout << std::endl;
}
}
};
void Aufg6Main() {
MineSweeperBoard board;
board.printBoard();
std::cout << "Empty Board? ==============" << std::endl << std::endl;
board.spreadBombs();
board.printBoard();
std::cout << "Bombed Board? ==============" << std::endl << std::endl;
board.calculateExplosiveNeighbours();
board.printBoard();
std::cout << "Solved Board? ==============" << std::endl << std::endl;
board.debugBoard(".");
board.field[14][14] = "x";
board.field[13][13] = "x";
board.field[13][15] = "x";
board.calculateExplosiveNeighbours();
board.printBoard();
}