minefield.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. #include "minefield.hpp"
  2. #include <ctime>
  3. #include <random>
  4. #include <algorithm>
  5. #include <iostream>
  6. // Define difficulty presets
  7. const GameDifficulty MineField::DIFFICULTY_EASY = {"Beginner", 9, 9, 10};
  8. const GameDifficulty MineField::DIFFICULTY_MEDIUM = {"Intermediate", 16, 16, 40};
  9. const GameDifficulty MineField::DIFFICULTY_HARD = {"Expert", 30, 16, 99};
  10. const GameDifficulty MineField::DIFFICULTY_EXPERT = {"Master", 30, 20, 145};
  11. MineField::MineField(int cols, int rows, int mines) :
  12. m_rows(rows),
  13. m_cols(cols),
  14. m_totalMines(mines),
  15. m_remainingFlags(mines),
  16. m_openCells(0),
  17. m_gameState(GameState::READY),
  18. m_timerRunning(false)
  19. {
  20. // Create cells
  21. m_cells.reserve(m_cols * m_rows);
  22. for (int i = 0; i < m_cols * m_rows; i++)
  23. {
  24. std::shared_ptr<Cell> cell = std::make_shared<Cell>();
  25. m_cells.push_back(cell);
  26. }
  27. }
  28. MineField::~MineField()
  29. {
  30. m_cells.clear();
  31. }
  32. void MineField::startTimer()
  33. {
  34. if (!m_timerRunning)
  35. {
  36. m_startTime = std::chrono::steady_clock::now();
  37. m_timerRunning = true;
  38. }
  39. }
  40. void MineField::stopTimer()
  41. {
  42. if (m_timerRunning)
  43. {
  44. m_endTime = std::chrono::steady_clock::now();
  45. m_timerRunning = false;
  46. }
  47. }
  48. int MineField::getElapsedTime() const
  49. {
  50. if (m_timerRunning)
  51. {
  52. auto now = std::chrono::steady_clock::now();
  53. return std::chrono::duration_cast<std::chrono::milliseconds>(now - m_startTime).count();
  54. }
  55. else if (m_gameState == GameState::WON || m_gameState == GameState::LOST)
  56. {
  57. return std::chrono::duration_cast<std::chrono::milliseconds>(m_endTime - m_startTime).count();
  58. }
  59. return 0;
  60. }
  61. void MineField::timerTick()
  62. {
  63. if (m_timerRunning)
  64. {
  65. timerSignal.emit(getElapsedTime());
  66. }
  67. }
  68. void MineField::reset()
  69. {
  70. // Reset all cells
  71. for (auto& cell : m_cells)
  72. {
  73. cell->isBomb = false;
  74. cell->isFlagged = false;
  75. cell->isCleared = false;
  76. cell->bombsNearby = -1;
  77. }
  78. // Reset game state
  79. m_openCells = 0;
  80. m_remainingFlags = m_totalMines;
  81. m_gameState = GameState::READY;
  82. m_timerRunning = false;
  83. // Emit signals
  84. resetSignal.emit();
  85. remainingFlagsSignal.emit(m_remainingFlags);
  86. }
  87. void MineField::startNewGame(int cols, int rows, int mines)
  88. {
  89. // Store new dimensions
  90. m_cols = cols;
  91. m_rows = rows;
  92. m_totalMines = mines;
  93. m_remainingFlags = mines;
  94. // Create new cells
  95. m_cells.clear();
  96. m_cells.reserve(m_cols * m_rows);
  97. for (int i = 0; i < m_cols * m_rows; i++)
  98. {
  99. std::shared_ptr<Cell> cell = std::make_shared<Cell>();
  100. m_cells.push_back(cell);
  101. }
  102. // Reset game state
  103. m_openCells = 0;
  104. m_gameState = GameState::READY;
  105. m_timerRunning = false;
  106. // Emit signals
  107. resetSignal.emit();
  108. remainingFlagsSignal.emit(m_remainingFlags);
  109. }
  110. void MineField::initBombs(int firstX, int firstY)
  111. {
  112. if (m_gameState != GameState::READY)
  113. {
  114. return;
  115. }
  116. // Start timer when first cell is clicked
  117. startTimer();
  118. m_gameState = GameState::PLAYING;
  119. // Create a vector of all possible positions
  120. std::vector<int> positions;
  121. positions.reserve(m_cols * m_rows);
  122. for (int i = 0; i < m_cols * m_rows; i++)
  123. {
  124. positions.push_back(i);
  125. }
  126. // Remove first clicked position and surrounding cells from available positions
  127. positions.erase(
  128. std::remove_if(positions.begin(), positions.end(),
  129. [this, firstX, firstY](int pos) {
  130. int x = pos % m_cols;
  131. int y = pos / m_cols;
  132. return std::abs(x - firstX) <= 1 && std::abs(y - firstY) <= 1;
  133. }
  134. ),
  135. positions.end()
  136. );
  137. // Use modern random generator
  138. std::random_device rd;
  139. std::mt19937 gen(rd());
  140. // Shuffle positions
  141. std::shuffle(positions.begin(), positions.end(), gen);
  142. // Place mines
  143. int minesToPlace = std::min(m_totalMines, static_cast<int>(positions.size()));
  144. for (int i = 0; i < minesToPlace; i++)
  145. {
  146. m_cells.at(positions[i])->isBomb = true;
  147. }
  148. }
  149. bool MineField::openCell(int x, int y)
  150. {
  151. // Ignore if game is over or cell is already open/flagged
  152. if (m_gameState != GameState::PLAYING && m_gameState != GameState::READY)
  153. {
  154. return false;
  155. }
  156. if (isOpened(x, y) || isFlagged(x, y))
  157. {
  158. return false;
  159. }
  160. // Start timer on first click if not already started
  161. if (m_gameState == GameState::READY)
  162. {
  163. initBombs(x, y);
  164. }
  165. // Check if bomb
  166. if (isBomb(x, y))
  167. {
  168. // Only emit the game over signal if we haven't already
  169. if (m_gameState != GameState::LOST) {
  170. m_gameState = GameState::LOST;
  171. stopTimer();
  172. gameOverSignal.emit();
  173. }
  174. return false;
  175. }
  176. // Open cell
  177. setOpenCell(x, y);
  178. // If no bombs nearby, open surrounding cells
  179. if (bombsNearby(x, y) == 0)
  180. {
  181. openNeighboorhood(x, y);
  182. }
  183. return true;
  184. }
  185. void MineField::computeBombsNearby(int x, int y)
  186. {
  187. int total = 0;
  188. // Check all 8 neighboring cells
  189. for (int i = -1; i <= 1; i++)
  190. {
  191. for (int j = -1; j <= 1; j++)
  192. {
  193. // Skip the cell itself
  194. if (i == 0 && j == 0)
  195. {
  196. continue;
  197. }
  198. int nx = x + i;
  199. int ny = y + j;
  200. // Check if within bounds
  201. if (nx >= 0 && nx < m_cols && ny >= 0 && ny < m_rows)
  202. {
  203. if (isBomb(nx, ny))
  204. {
  205. ++total;
  206. }
  207. }
  208. }
  209. }
  210. m_cells.at(x + y * m_cols)->bombsNearby = total;
  211. }
  212. void MineField::openNeighboorhood(int x, int y)
  213. {
  214. // Check all 8 neighboring cells
  215. for (int i = -1; i <= 1; i++)
  216. {
  217. for (int j = -1; j <= 1; j++)
  218. {
  219. // Skip the cell itself
  220. if (i == 0 && j == 0)
  221. {
  222. continue;
  223. }
  224. int nx = x + i;
  225. int ny = y + j;
  226. // Check if within bounds
  227. if (nx >= 0 && nx < m_cols && ny >= 0 && ny < m_rows)
  228. {
  229. // If cell is not opened and not a bomb, open it
  230. if (!isOpened(nx, ny) && !isBomb(nx, ny))
  231. {
  232. setOpenCell(nx, ny);
  233. // If no bombs nearby, recursively open surrounding cells
  234. if (bombsNearby(nx, ny) == 0)
  235. {
  236. openNeighboorhood(nx, ny);
  237. }
  238. }
  239. }
  240. }
  241. }
  242. }
  243. bool MineField::isOpened(int x, int y)
  244. {
  245. return m_cells.at(x + y * m_cols)->isCleared;
  246. }
  247. bool MineField::isFlagged(int x, int y)
  248. {
  249. return m_cells.at(x + y * m_cols)->isFlagged;
  250. }
  251. bool MineField::isBomb(int x, int y)
  252. {
  253. return m_cells.at(x + y * m_cols)->isBomb;
  254. }
  255. int MineField::bombsNearby(int x, int y)
  256. {
  257. // Calculate bombs nearby if not already calculated
  258. if (m_cells.at(x + y * m_cols)->bombsNearby == -1)
  259. {
  260. computeBombsNearby(x, y);
  261. }
  262. return m_cells.at(x + y * m_cols)->bombsNearby;
  263. }
  264. void MineField::setOpenCell(int x, int y)
  265. {
  266. m_cells.at(x + y * m_cols)->isCleared = true;
  267. openCellSignal.emit(x, y);
  268. ++m_openCells;
  269. checkGameWon();
  270. }
  271. void MineField::checkGameWon()
  272. {
  273. // Win condition: All non-bomb cells are opened
  274. if (m_openCells == (m_cols * m_rows - m_totalMines) && m_gameState == GameState::PLAYING)
  275. {
  276. m_gameState = GameState::WON;
  277. stopTimer();
  278. // Auto-flag all remaining bombs
  279. for (int i = 0; i < m_cols * m_rows; i++)
  280. {
  281. int x = i % m_cols;
  282. int y = i / m_cols;
  283. if (isBomb(x, y) && !isFlagged(x, y))
  284. {
  285. m_cells.at(i)->isFlagged = true;
  286. }
  287. }
  288. m_remainingFlags = 0;
  289. remainingFlagsSignal.emit(m_remainingFlags);
  290. // Emit game won signal with elapsed time
  291. gameWonSignal.emit(getElapsedTime());
  292. }
  293. }
  294. bool MineField::toggleFlag(int x, int y)
  295. {
  296. // Ignore if game is over or cell is already open
  297. if (m_gameState != GameState::PLAYING && m_gameState != GameState::READY)
  298. {
  299. return false;
  300. }
  301. if (isOpened(x, y))
  302. {
  303. return false;
  304. }
  305. if (m_gameState == GameState::READY)
  306. {
  307. // Start timer on first action
  308. startTimer();
  309. m_gameState = GameState::PLAYING;
  310. }
  311. // Toggle flag state
  312. if (m_cells.at(x + y * m_cols)->isFlagged)
  313. {
  314. m_cells.at(x + y * m_cols)->isFlagged = false;
  315. ++m_remainingFlags;
  316. }
  317. else if (m_remainingFlags > 0)
  318. {
  319. m_cells.at(x + y * m_cols)->isFlagged = true;
  320. --m_remainingFlags;
  321. }
  322. else
  323. {
  324. // No remaining flags
  325. return false;
  326. }
  327. remainingFlagsSignal.emit(m_remainingFlags);
  328. return true;
  329. }