Creating the timer functions
This commit is contained in:
@@ -16,8 +16,8 @@ void MineField::timerTick() {
|
||||
|
||||
auto start = std::chrono::system_clock::now();
|
||||
|
||||
while((m_exploded == false) && (m_gameWon == false)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(200));
|
||||
while(m_timerRunning) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
auto now = std::chrono::system_clock::now();
|
||||
const auto duration = now - start;
|
||||
std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
|
||||
@@ -25,7 +25,17 @@ void MineField::timerTick() {
|
||||
timerSignal.emit(m_time);
|
||||
start = std::chrono::system_clock::now();
|
||||
}
|
||||
//I should use std::duration to represent the time instead
|
||||
}
|
||||
|
||||
void MineField::startTimer() {
|
||||
m_time = 0;
|
||||
m_timerRunning = true;
|
||||
m_timerThread = std::thread(&MineField::timerTick, this);
|
||||
}
|
||||
|
||||
void MineField::stopTimer() {
|
||||
m_timerRunning = false;
|
||||
m_timerThread.join();
|
||||
}
|
||||
|
||||
void MineField::initBombs(int x, int y) {
|
||||
@@ -44,16 +54,19 @@ void MineField::initBombs(int x, int y) {
|
||||
--remainingMines;
|
||||
}
|
||||
|
||||
startTimer();
|
||||
|
||||
//init the timer to zero and start the timer thread
|
||||
m_time = 0;
|
||||
timerThread = std::thread(&MineField::timerTick, this);
|
||||
timerThread.detach(); //not sure if this is okay (better to call join() when I set the condition to stop the thread)
|
||||
// m_time = 0;
|
||||
//timerThread = std::thread(&MineField::timerTick, this);
|
||||
//timerThread.detach(); //not sure if this is okay (better to call join() when I set the condition to stop the thread)
|
||||
}
|
||||
|
||||
bool MineField::openCell(int x, int y) {
|
||||
if(isBomb(x, y)) {
|
||||
m_exploded = true;
|
||||
gameOverSignal.emit();
|
||||
stopTimer();
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -120,6 +133,7 @@ void MineField::setOpenCell(int x, int y) {
|
||||
openCellSignal.emit(x, y);
|
||||
if((++m_openCells == (m_cols * m_rows - m_totalMines)) && (m_exploded == false)) {
|
||||
m_gameWon = true;
|
||||
stopTimer();
|
||||
gameWonSignal.emit();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,12 +26,15 @@ class MineField {
|
||||
int m_openCells;
|
||||
bool m_exploded;
|
||||
bool m_gameWon;
|
||||
bool m_timerRunning;
|
||||
size_t m_time;
|
||||
std::thread timerThread;
|
||||
std::thread m_timerThread;
|
||||
void computeBombsNearby(int x, int y);
|
||||
void openNeighboorhood(int x, int y);
|
||||
void setOpenCell(int x, int y);
|
||||
void timerTick();
|
||||
void startTimer();
|
||||
void stopTimer();
|
||||
|
||||
public:
|
||||
MineField(int cols, int rows, int mines);
|
||||
|
||||
Reference in New Issue
Block a user