-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
452 lines (378 loc) · 12.4 KB
/
mainwindow.cpp
File metadata and controls
452 lines (378 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QDebug>
#include <QTimer>
#include <QTime>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent),
ui(new Ui::MainWindow),
cameraHandler(nullptr),
game(nullptr),
gameScore(0),
m_showingScoreboard(false),
m_showingInstructions(false),
m_standardMode(true) // Default to Standard Mode
{
ui->setupUi(this);
// Create scoreboard
m_scoreboard = new Scoreboard(this);
// Initialize status timer for temporary messages
m_statusTimer = new QTimer(this);
m_statusTimer->setSingleShot(true);
connect(m_statusTimer, &QTimer::timeout, [this]()
{ ui->statusLabel->clear(); });
// Initialize game timer
m_gameTimer = new QTimer(this);
connect(m_gameTimer, &QTimer::timeout, this, &MainWindow::updateGameTimeDisplay);
// Hide the scoreboard and instructions overlays initially
ui->scoreboardOverlay->hide();
ui->instructionsOverlay->hide();
// Configure splitter proportions (80% game view, 20% control panel)
QList<int> sizes;
sizes << (width() * 0.8) << (width() * 0.2);
ui->mainSplitter->setSizes(sizes);
// Connect action signals
connect(ui->actionNew_Game, &QAction::triggered, this, &MainWindow::startNewGame);
connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAboutDialog);
// Setup camera handler
cameraHandler = new CameraHandler();
ui->cameraLayout->insertWidget(0, cameraHandler);
ui->cameraView->hide();
ui->cameraStatus->hide();
// Initialize UI states
ui->countdownLabel->hide();
// Get the OpenGL widget to access the player and projectile manager
MyGLWidget *glWidget = qobject_cast<MyGLWidget *>(ui->glWidget);
// Create the Game instance
if (glWidget)
{
game = new Game(glWidget->getPlayer(),
cameraHandler,
glWidget->getKeyboardHandler(),
glWidget->getProjectileManager(),
this);
// Connect game signals to UI slots
connect(game, &Game::scoreChanged, this, &MainWindow::updateScoreLabel);
connect(game, &Game::livesChanged, this, &MainWindow::updateLivesLabel);
connect(game, &Game::countdownUpdated, this, &MainWindow::updateCountdownLabel);
connect(game, &Game::gameEnded, this, &MainWindow::showStartButton);
// Connect player position changes to the GL widget
connect(game, &Game::playerPositionChanged, glWidget, &MyGLWidget::positionPlayerOnGrid);
// Connect keyboard speed changes
connect(glWidget->getKeyboardHandler(), &KeyboardHandler::speedMultiplierChanged,
this, &MainWindow::updateSpeedIndicator);
// Set the game update function in the GL widget
glWidget->setGameUpdateFunction([this]()
{
if (game) {
game->update();
} });
}
updateScoreDisplay();
// Set default button text to show what mode will be switched to if clicked
ui->modeSwitchButton->setText("Original Mode");
}
MainWindow::~MainWindow()
{
// Stop the timer if it's running
if (m_gameTimer->isActive())
{
m_gameTimer->stop();
}
delete cameraHandler;
delete m_scoreboard;
delete ui;
}
void MainWindow::startNewGame()
{
// If scoreboard or instructions is showing, hide it first
if (m_showingScoreboard)
{
toggleScoreboard();
}
else if (m_showingInstructions)
{
toggleInstructions();
}
startGame();
}
void MainWindow::showAboutDialog()
{
QMessageBox::about(this, tr("About Slice Defender"),
tr("Slice Defender v1.0\n\n"
"A game that uses computer vision to detect and track hand movements.\n\n"
"Created with Qt and OpenCV."));
}
void MainWindow::startGame()
{
if (game)
{
// Hide scoreboard or instructions if it's visible
if (m_showingScoreboard)
{
toggleScoreboard();
}
else if (m_showingInstructions)
{
toggleInstructions();
}
// Reset the game state
game->resetGame();
// Ensure the game uses the correct mode
game->setStandardMode(m_standardMode);
// Hide the start button and show the countdown
ui->startButton->hide();
ui->countdownLabel->show();
// Disable save button during gameplay
ui->saveButton->setEnabled(false);
// Release focus from name input to prevent accidental keyboard input capture
ui->nameInput->clearFocus();
ui->nameInput->clear();
// Start the countdown
game->startCountdown();
// Set focus explicitly to the OpenGL widget for immediate keyboard control
ui->glWidget->setFocus();
// Force the widget to get focus
ui->glWidget->grabKeyboard();
// Reset game timer with centisecond precision
m_gameStartTime = QTime::currentTime();
ui->gameTimeLabel->setText("00:00:00");
}
}
void MainWindow::updateScoreDisplay()
{
ui->scoreValue->setText(QString("POINTS:\n%1").arg(gameScore));
}
void MainWindow::updateScoreboardDisplay()
{
QStringList scores = m_scoreboard->loadTopScores();
if (scores.isEmpty())
{
ui->scoreText->setText("No scores yet. Play a game!");
}
else
{
ui->scoreText->setText(scores.join("\n"));
}
}
void MainWindow::updateScoreLabel(int score)
{
gameScore = score;
updateScoreDisplay();
}
void MainWindow::updateLivesLabel(int lives)
{
ui->livesLabel->setText(QString("Lives:\n%1").arg(lives));
}
void MainWindow::updateCountdownLabel(int value)
{
if (value <= 0)
{
ui->countdownLabel->hide();
// Start the game timer
m_gameStartTime = QTime::currentTime();
m_gameTimer->start(10);
}
else
{
ui->countdownLabel->setText(QString::number(value));
}
}
void MainWindow::showStartButton()
{
ui->startButton->setText("Restart Game");
ui->startButton->show();
// Always enable the input field and save button
// regardless of high score status
ui->saveButton->setEnabled(true);
ui->nameInput->setEnabled(true);
// Release keyboard focus from the GL widget
ui->glWidget->releaseKeyboard();
// Give focus to name input field for immediate typing
ui->nameInput->clear();
ui->nameInput->setFocus();
// Stop the game timer
m_gameTimer->stop();
// Show Game Over message in red
showStatusMessage("Game Over", false);
}
/**
* @brief Updates the game timer display with centisecond precision
*
* Calculates elapsed time between current time and game start time,
* displaying it in mm:ss:XX format (minutes:seconds:centiseconds).
*/
void MainWindow::updateGameTimeDisplay()
{
// Calculate elapsed time since game start
QTime currentTime = QTime::currentTime();
int elapsedMs = m_gameStartTime.msecsTo(currentTime);
// Convert to minutes, seconds, centiseconds
int minutes = (elapsedMs / 60000) % 60;
int seconds = (elapsedMs / 1000) % 60;
int centiseconds = (elapsedMs / 10) % 100;
// Create formatted string with leading zeros
QString timeString = QString("%1:%2:%3")
.arg(minutes, 2, 10, QChar('0'))
.arg(seconds, 2, 10, QChar('0'))
.arg(centiseconds, 2, 10, QChar('0'));
// Update the display
ui->gameTimeLabel->setText(timeString);
}
void MainWindow::updateSpeedIndicator(float speedMultiplier)
{
ui->speedLabel->setText(QString("Speed: %1x").arg(speedMultiplier, 0, 'f', 1));
}
void MainWindow::showStatusMessage(const QString &message, bool success)
{
ui->statusLabel->setText(message);
ui->statusLabel->setStyleSheet(success ? "color: #4CAF50; font-weight: bold;" : "color: #F44336; font-weight: bold;");
// Auto-clear message after 3 seconds
m_statusTimer->start(3000);
}
void MainWindow::toggleInstructions()
{
m_showingInstructions = !m_showingInstructions;
if (m_showingInstructions)
{
// Hide scoreboard if it's visible
if (m_showingScoreboard)
{
m_showingScoreboard = false;
ui->scoreboardOverlay->hide();
ui->scoreboardButton->setText("Scoreboard");
}
// Show instructions overlay
ui->instructionsButton->setText("Back to Game");
ui->instructionsOverlay->show();
}
else
{
// Hide instructions overlay
ui->instructionsButton->setText("Instructions");
ui->instructionsOverlay->hide();
// Make sure game controls are in the correct state
if (game && game->isGameStarted())
{
ui->startButton->hide();
}
else
{
ui->startButton->show();
}
}
}
void MainWindow::toggleScoreboard()
{
m_showingScoreboard = !m_showingScoreboard;
if (m_showingScoreboard)
{
// Hide instructions if it's visible
if (m_showingInstructions)
{
m_showingInstructions = false;
ui->instructionsOverlay->hide();
ui->instructionsButton->setText("Instructions");
}
// Show scoreboard overlay
updateScoreboardDisplay();
ui->scoreboardButton->setText("Back to Game");
ui->scoreboardOverlay->show();
}
else
{
// Hide scoreboard overlay
ui->scoreboardButton->setText("Scoreboard");
ui->scoreboardOverlay->hide();
// Make sure game controls are in the correct state
if (game && game->isGameStarted())
{
ui->startButton->hide();
}
else
{
ui->startButton->show();
}
}
}
void MainWindow::savePlayerScore()
{
// Get the player name, default to "No Name" if empty
QString playerName = ui->nameInput->text().trimmed();
if (playerName.isEmpty())
{
playerName = "No Name";
}
// Save the score
bool success = m_scoreboard->saveScore(playerName, gameScore);
// Show success/failure message
showStatusMessage(
success ? "Score saved successfully!" : "Failed to save score",
success);
// Update the scoreboard display
if (success)
{
updateScoreboardDisplay();
// Clear the input field
ui->nameInput->clear();
// Disable save button to prevent multiple saves
ui->saveButton->setEnabled(false);
}
}
void MainWindow::toggleGameMode()
{
// Only allow mode change when not in active gameplay
if (game && game->isGameStarted())
{
showStatusMessage("Impossible during game", false);
return;
}
// Toggle the mode
m_standardMode = !m_standardMode;
// Update button text
if (m_standardMode)
{
ui->modeSwitchButton->setText("Original Mode");
}
else
{
ui->modeSwitchButton->setText("Standard Mode");
}
// Update game settings
if (game)
{
game->setStandardMode(m_standardMode);
}
// Show confirmation message
QString message = QString("Switched to %1").arg(m_standardMode ? "Standard Mode" : "Original Mode");
showStatusMessage(message, true);
}
/**
* @brief Toggles between internal (0) and external (1) camera sources
*
* This method:
* 1. Toggles the camera index between 0 (internal) and 1 (external)
* 2. Releases the current camera and attempts to open the new one
* 3. Updates the button text to reflect the next camera to switch to
* 4. Handles failure to open camera gracefully without crashing
*
* Even if camera switching fails, the button text is updated to maintain
* UI consistency with the stored camera index.
*/
void MainWindow::toggleCameraSource()
{
// Toggle camera index between 0 (internal) and 1 (external)
cameraIndex_ = (cameraIndex_ == 0) ? 1 : 0;
// Release the current camera before opening a new one
if (cameraHandler)
{
cameraHandler->releaseCamera();
// Try to open the new camera
cameraHandler->openCamera(cameraIndex_);
// Update button text based on which camera will be switched to next
// If current is internal (0), button shows "External Cam" (next click = 1)
// If current is external (1), button shows "Internal Cam" (next click = 0)
ui->cameraSwitchButton->setText(cameraIndex_ == 0 ? "External Cam" : "Internal Cam");
}
}