-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGame.cpp
549 lines (520 loc) · 16.6 KB
/
Game.cpp
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//
// Created by kali on 2/28/22.
//
#include "Game.h"
#include <SDL2/SDL.h>
#include <iostream>
#include "arduino/controller.h"
void fatalError(std::string errorString)
{
std::cout << errorString << std::endl;
std::cout << "Enter any key to quit...";
int tmp;
std::cin >> tmp;
SDL_Quit();
}
const Game* gameInstance;
arduino::Controller* pc;
Game::Game(int screenWidth, int screenHeight)
: window(nullptr)
, screenWidth(screenWidth)
, screenHeight(screenHeight)
, gameState(GameState::START)
{
gameInstance = this;
// for pi, port must be manually specified to be "/dev/ttyACM0"
pc = new arduino::Controller();
int scoreMult = HIGH_SCORES;
for(int& highScore : highScores) highScore = pow(10,--scoreMult);
}
// sigh...
Game::Rect::Rect(int x, int y, int w, int h) : SDL_Rect({
gameInstance->tileLength() * (GRID_LEFT + x),
gameInstance->tileLength() * (PADDING + y),
gameInstance->tileLength() * w,
gameInstance->tileLength() * h,
}){}
bool Shape::isInvalidPosition(int x,int y)
{
return x < 0
|| y < 0
|| x >= Game::COLS
|| y >= Game::ROWS
|| !(gameInstance->grid[x][y] == Color());
}
Game::~Game()
{
destructScene();
}
void Game::run() {
initScene();
gameLoop();
}
int curPiece = 0;
Shape* cyclePiece(int inc) {
int N = Shape::T+1;
curPiece = (curPiece + N + inc) % N;
return new Shape(static_cast<Shape::Piece>(curPiece));
}
void Game::setCurShape(Shape *shape) {
// todo it might be nice to make curShape a reference rather than a pointer, but it would require either a getter method that autocalls this one or more delicate handling of the curShape variable to ensure it never holds a null pointer.
shape->setPos(0);
shape->x = 5; // move roughly to the center of the grid
if(shape->isInvalidState()) {
// this is when the game terminates
gameState = GameState::GAME_OVER;
// todo in the future this should probably manually set lights to be off to remove the need to manually reset the tower lights.
pc->playAnimation(arduino::Controller::Animation::FLATLINE);
// record high score
int toAdd = this->score;
bool added = false;
for(int &highScore : highScores) {
// this is lazy since after the first substitution the next ones will all be shifted.
if(toAdd > highScore) {
added = true;
int temp = highScore;
highScore = toAdd;
toAdd = temp;
}
}
return; // terminate logic
}
pc->setKeyLights(shape->color);
delete curShape;
curShape = shape;
// reset fall-related variables
time = dropDelay();
locked = false;
fastFall = false;
}
bool holdUsed = false;
void Game::holdShape() {
if(holdUsed) return;
auto tmp = heldShape;
heldShape = new Shape(curShape->piece);
if(tmp == nullptr) {
loadNewShape();
} else {
holdUsed = true;
setCurShape(tmp);
}
}
void Game::loadNewShape() {
holdUsed = false;
setCurShape(nxtShape);
nxtShape = new Shape(bag.draw());
}
bool Game::moveCurShapeDown() {
if(curShape->moveDown()) return true;
placeShape();
return false;
}
void Game::incLevel() {
//std::cout << "level: " << ++level << " (speed = " << DELAY/(time = dropDelay()) << "G/" << dropDelay() << "ms)" << std::endl;
++level;
pc->playAnimation(arduino::Controller::Animation::TOWER_LIGHT);
toNextLevel = LEVEL_CLEAR;
}
// the lowest y value containing a color (in other words the one closest to the top).
// used with tower light tracking, unused otherwise.
int progress;
// todo wonder if I should add a sleep call to give it some time to execute
void updateProgress() {
switch (progress*3/Game::ROWS) {
case 0: pc->setTowerLights(false,false,true,false); break;
case 1: pc->setTowerLights(false,true,false,false); break;
case 2: pc->setTowerLights(true,false,false,false); break;
}
}
// whether to enable progress lights
bool towerLightProgressTracking = false;
void Game::placeShape() {
Shape& s = *curShape;
int rowsComplete = 0;
int lY=ROWS,hY=-1; // range of rows to check
for(int i=0; i < Shape::N_SQUARES; i++) {
int y = s[i].y + s.y;
if(y < lY) lY = y;
if(y > hY) hY = y;
grid[s[i].x+s.x][y] = curShape->color;
}
int y = hY;
while(y >= lY)
{
if(rowComplete(y))
{
moveRows(y);
rowsComplete++;
// rows have been moved, everything is shifted one "down"
lY++;
}
else y--;
}
progress = std::min(lY, progress+rowsComplete);
// this is explicitly opt-in given its general tendency to ruin the arduino.
calcScore(rowsComplete);
// todo move before tower light directive, creates increased consistency in key-light colors
loadNewShape();
// update tower lights in accordance to progress
if(gameState == GameState::PLAY && towerLightProgressTracking) updateProgress();
}
#include<chrono>
using ms = std::chrono::milliseconds;
using sc = std::chrono::steady_clock;
auto curTime = sc::now();
auto getDuration()
{
auto now = sc::now();
auto r = std::chrono::duration_cast<ms>(now - curTime);
curTime = now;
return r.count();
}
void Game::play() {
if(gameState == GameState::GAME_OVER) {
for (auto &col: grid)
for (auto &cell: col)
cell = Color();
}
gameState = GameState::PLAY;
level=0; incLevel();
score = 0;
bag = Bag(); // refresh the bag
// gravity logic
getDuration(); // reset reference time
delete heldShape;
heldShape = nullptr;
delete nxtShape;
nxtShape = new Shape(bag.draw());
progress = ROWS; // lowest Y is at the bottom of the board now.
loadNewShape();
}
struct {
int move=0, rotate=0;
bool instantDrop=false,fastDrop=false;
bool holdPiece=false;
} cur, prev;
bool held = true; // press a button to start the game.
bool handleArduinoCommands(SDL_Keysym key, bool enable) {
switch (key.scancode) {
// 1-3 are green/yellow/red respectively. 0 is buzzer.
case SDL_SCANCODE_KP_0:
pc->towerLights.buzzer = enable;
pc->updateTowerLights();
break;
case SDL_SCANCODE_KP_1:
pc->towerLights.green = enable;
pc->updateTowerLights();
break;
case SDL_SCANCODE_KP_2:
pc->towerLights.yellow = enable;
pc->updateTowerLights();
break;
case SDL_SCANCODE_KP_3:
pc->towerLights.red = enable;
pc->updateTowerLights();
break;
case SDL_SCANCODE_KP_DIVIDE: if(enable) {
// toggle tower light progress tracking. Disabled by default due to being unstable and breaking things.
towerLightProgressTracking = !towerLightProgressTracking;
if (towerLightProgressTracking) {
updateProgress();
} else {
pc->setTowerLights(false,false,false,false);
}
break;
}
// after this point everything only happens if enabled.
case SDL_SCANCODE_KP_MULTIPLY: if(enable) {
if(pc->nunchuckEnabled) pc->disableNunchuck();
else pc->enableNunchuck();
break;
}
case SDL_SCANCODE_KP_PLUS: if(enable) {
pc->playAnimation(arduino::Controller::Animation::TOWER_LIGHT);
break;
}
// fall into next
case SDL_SCANCODE_KP_ENTER: if(enable) {
pc->playAnimation(arduino::Controller::Animation::FLATLINE);
break;
}
default: return false;
}
return true;
}
int map(int val, int l1, int l2, int r1, int r2) {
if(val > l1 && val < l2) return -1;
if(val > r1 && val < r2) return 1;
return 0;
}
void Game::processInput()
{
// fixme there is massive duplication here
SDL_Event evnt;
while(SDL_PollEvent(&evnt))
{
switch(evnt.type)
{
case SDL_WINDOWEVENT:
switch(evnt.window.event) {
case SDL_WINDOWEVENT_RESIZED:
screenWidth = evnt.window.data1;
screenHeight = evnt.window.data2;
break;
};
break;
case SDL_QUIT:
gameState = GameState::EXIT;
break;
// case SDL_MOUSEMOTION:
// //prepareScene(/*evnt.motion.x * 255 / screenWidth, evnt.motion.y * 255 / screenHeight, 255*/);
// std::cout << evnt.motion.x << " " << evnt.motion.y << std::endl;
// break;
case SDL_KEYUP:
if(handleArduinoCommands(evnt.key.keysym, false)) continue;
held = false;
if(gameState != GameState::PLAY) break;
if(evnt.key.keysym.scancode == SDL_SCANCODE_S) {
toggleFastDrop(false);
//std::cout << "fast fall off" << std::endl;
}
break;
case SDL_KEYDOWN:
if(handleArduinoCommands(evnt.key.keysym, true)) continue;
if(held) break; else held = true;
if(gameState == GameState::START || gameState == GameState::GAME_OVER) {
if(evnt.key.keysym.scancode == 40) {
play();
}
return;
}
// interact with our piece
// break locks, continue does not.
bool resetTime = false;
switch (evnt.key.keysym.scancode) {
case SDL_SCANCODE_W:
curShape->y--;
break;
case SDL_SCANCODE_S:
toggleFastDrop(true);
//std::cout << "fast fall on" << std::endl;
break; // already reset timer.
case SDL_SCANCODE_A:
resetTime = curShape->moveL();
break;
case SDL_SCANCODE_D:
resetTime = curShape->moveR();
break;
case SDL_SCANCODE_Q:
resetTime = curShape->rotateL();
break;
case SDL_SCANCODE_E:
resetTime = curShape->rotateR();
break;
case SDL_SCANCODE_TAB:
holdShape();
continue; // timer handled.
case SDL_SCANCODE_EQUALS:
incLevel();
break;
case SDL_SCANCODE_MINUS:
std::cout << "level: " << --level << " --- speed=" << (time = dropDelay()) << std::endl;
break;
// worth noting this cycles draw, so if you want it to start cycling you need to do it twice.
case SDL_SCANCODE_RIGHT:
loadNewShape();
nxtShape = cyclePiece(+1);
break;
case SDL_SCANCODE_LEFT:
loadNewShape();
nxtShape = cyclePiece(-1);
break;
case 40:
instantDrop();
break;
case SDL_SCANCODE_DELETE:
loadNewShape();
continue;
default:
continue;
}
if(locked && resetTime) time = LOCK_DELAY;
return; // don't check arduino
//std::cout << evnt.key.keysym.scancode << std::endl;
}
}
// ARDUINO CONTROLS
if(gameState == GameState::START || gameState == GameState::GAME_OVER) {
if(pc->startButton || pc->nunchuckEnabled && pc->nunchuck.btnC) play(); else return;
}
prev = cur;
cur = {
(int)pc->moveRight - pc->moveLeft,
pc->rotateLeft - (int)pc->rotateRight,
pc->instantDrop,
pc->fastDrop,
pc->selectButton,
};
if(pc->nunchuckEnabled) {
// nunchuck controls
auto &n = pc->nunchuck;
int move = map(n.joyX,32,100,165,225);
if(move != cur.move) cur.move += move;
if(map(n.joyY,35,80,165,225) == -1) cur.fastDrop |= true;
cur.holdPiece |= n.btnC;
cur.instantDrop |= n.btnZ;
// apparently reversed?
int roll = map(pc->nunchuck.accel.roll,40,100,150,220);
if(roll != cur.rotate) cur.rotate += roll;
}
if(cur.holdPiece && !prev.holdPiece) holdShape();
bool resetLock = false;
if(cur.move != prev.move) resetLock = curShape->move(cur.move);
if(cur.rotate != prev.rotate) resetLock = curShape-> rotate(cur.rotate) || resetLock;
if(cur.fastDrop != prev.fastDrop) {
resetLock = false;
toggleFastDrop(cur.fastDrop);
}
if(cur.instantDrop && !prev.instantDrop) {
resetLock = false;
instantDrop();
}
if(locked && resetLock) time = LOCK_DELAY;
}
// /(^ㅅ^)\ Checks if a given row y is complete
bool Game::rowComplete(int y) const {
// /(^ㅅ^)\ Loop through columns in the row
for(int i = 0; i < COLS; i++)
{
// /(^ㅅ^)\ If a square in the row is equal to the default, the row is incomplete
if(grid[i][y] == Color())
{
return false;
}
}
// /(^ㅅ^)\ If no squares in the row are equal to default, the row is complete
return true;
}
// /(^ㅅ^)\ Move all rows above y down a single row
bool Game::moveRows(int y)
{
// /(^ㅅ^)\ Loop from y to 1
for(int i = y; i > 0; i--)
{
// /(^ㅅ^)\ Move the row above to the current row
for(int j = 0; j < COLS; j++)
{
grid[j][i] = grid[j][i - 1];
}
}
// /(^ㅅ^)\ Clear row 0
return clearRow(0);
}
// /(^ㅅ^)\ Clears a given row y
bool Game::clearRow(int y)
{
// /(^ㅅ^)\ Loops through all columns in the row and sets each square to default
for(int i = 0; i < COLS; i++)
{
grid[i][y] = Color();
}
// /(^ㅅ^)\ Increment level if required
if(--toNextLevel == 0) incLevel();
return true;
}
void Game::calcScore(int rowsCleared)
{
if(rowsCleared == 0)
{
return;
}
else if(boardClear())
{
switch(rowsCleared)
{
case 1:
score += 800 * level;
break;
case 2:
score += 1200 * level;
break;
case 3:
score += 1800 * level;
break;
case 4:
score += 2000 * level;
break;
default:
std::cout << "score calculation error" << std::endl;
}
}
else
{
switch(rowsCleared)
{
case 1:
score += 100 * level;
break;
case 2:
score += 300 * level;
break;
case 3:
score += 500 * level;
break;
case 4:
score += 800 * level;
break;
default:
std::cout << "score calculation error" << std::endl;
}
}
}
bool Game::boardClear()
{
for(int i = 0; i < ROWS; ++i)
{
if(!(grid[i][COLS] == Color()))
return false;
}
return true;
}
void Game::gameLoop()
{
while (true)
{
prepareScene();
presentScene();
if(pc->connected) pc->refreshArduinoStatus();
processInput();
if(gameState == GameState::EXIT) break;
if(gameState == GameState::PLAY) applyGravity();
}
}
void Game::applyGravity()
{
time -= getDuration();
while(time <= 0) {
if(curShape->moveDown()) {
time += dropDelay();
if(fastFall){
score += 1;
}
locked = false;
} else {
// shape cannot move down anymore.
fastFall = false;
if(locked) {
// lock delay has been spent, place the shape.
placeShape();
// placeShape can change the gameState if it was unable to place the new shape.
if(gameState == GameState::GAME_OVER) return;
}
else
{
// this prevents the shape from being placed instantly
locked = true;
time = LOCK_DELAY;
}
}
}
}