-
Notifications
You must be signed in to change notification settings - Fork 2
/
game.cpp
1951 lines (1753 loc) · 62.7 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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "game.h"
#include "pieces.cpp"
#define SETTINGS_FILE "testris.conf"
#define HIGHSCORES_FILE "testris.highscores"
#define MIN_TICK 100
uint8_t *ubuntu_ttf_buffer;
FontAtlas ubuntu_m16;
FontAtlas ubuntu_m32;
uint8_t *mono_ttf_buffer;
FontAtlas mono_m18;
/* int32_t sound_ready; */
ShaderProgram titleShader;
ShaderProgram titleBGShader;
ShaderProgram vhsShader;;
static App *app = NULL;
float scale() {
float x = app->width/600.0f;
float y = app->height/800.0f;
return MIN(x, y);
}
float blockSide(GameState *st) {
return scale()*BLOCK_SIDE;
}
float blockPad(GameState *st) {
return scale()*BLOCK_PAD;
}
DrawOpts2d scaleOpts() {
DrawOpts2d opts = {};
opts.scale.x = opts.scale.y = scale();
return opts;
}
bool inBounds(int x, int y) {
return x >= 0 && x < BOARD_WIDTH && y < BOARD_HEIGHT; // y >= 0
}
int rotate(Piece *p, RotationDir dir) {
switch (dir) {
case CW:
p->orientation = (p->orientation + 1) % NUM_ORIENTATIONS;
break;
case CCW:
if (p->orientation == 0) {
p->orientation = NUM_ORIENTATIONS;
}
p->orientation--;
break;
}
// TODO: check orientation && pos against piece extent, shift as needed
return p->orientation;
}
bool pieceFits(GameState *st, int type, int o, int x, int y, Vec2 *nudge) {
for (int ix = 0; ix < 4; ix++) {
int iy = 0;
int i = ix + iy * 4;
if (y + iy < 0) continue;
if (!pieces[type][o][i]) continue;
if (st->inRound.board[y+iy][x+ix].full) {
return false;
}
if (!inBounds(x+ix, y+iy)) {
if (nudge) {
if (x+ix < 0) *nudge = vec2(-(x+ix), 0);
else if (x+ix >= BOARD_WIDTH) *nudge = vec2(x+ix-BOARD_WIDTH-1, 0);
//else if (y+iy < 0) *nudge = vec2(0, -(y+iy));
else if (y+iy >= BOARD_HEIGHT) *nudge = vec2(0, y+iy-BOARD_HEIGHT-1);
}
return false;
}
}
for (int ix = 0; ix < 4; ix++) {
int iy = 3;
int i = ix + iy * 4;
if (y + iy < 0) continue;
if (!pieces[type][o][i]) continue;
if (st->inRound.board[y+iy][x+ix].full) {
return false;
}
if (!inBounds(x+ix, y+iy)) {
if (nudge) {
if (x+ix < 0) *nudge = vec2(-(x+ix), 0);
else if (x+ix >= BOARD_WIDTH) *nudge = vec2(BOARD_WIDTH-1-x-ix, 0);
//else if (y+iy < 0) *nudge = vec2(0, -(y+iy));
else if (y+iy >= BOARD_HEIGHT) *nudge = vec2(0, BOARD_HEIGHT-1-y-iy);
}
return false;
}
}
for (int jx = 3; jx < 3+4; jx++) {
int ix = jx % 4;
for (int iy = 1; iy < 3; iy++) {
if (y + iy < 0) continue;
int i = ix + iy * 4;
if (!pieces[type][o][i]) continue;
if (st->inRound.board[y+iy][x+ix].full) {
return false;
}
if (!inBounds(x+ix, y+iy)) {
if (nudge) {
if (x+ix < 0) *nudge = vec2(-(x+ix), 0);
else if (x+ix >= BOARD_WIDTH) *nudge = vec2(BOARD_WIDTH-1-x-ix, 0);
//else if (y+iy < 0) *nudge = vec2(0, -(y+iy));
else if (y+iy >= BOARD_HEIGHT) *nudge = vec2(0, BOARD_HEIGHT-1-y-iy);
}
return false;
}
}
}
return true;
}
bool pieceFits(GameState *st, int type, int o, int x, int y) {
return pieceFits(st, type, o, x, y, NULL);
}
bool pieceFits(GameState *st, Piece *p) {
return pieceFits(st, p->type, p->orientation, p->x, p->y, NULL);
}
bool pieceFits(GameState *st, Piece *p, Vec2 *nudge) {
return pieceFits(st, p->type, p->orientation, p->x, p->y, nudge);
}
bool tryMove(GameState *st, Piece *p, int dx, int dy) {
if (!pieceFits(st, p->type, p->orientation, p->x + dx, p->y + dy))
return false;
p->x += dx;
p->y += dy;
return true;
}
bool tryRotate(GameState *st, Piece *p, RotationDir dir) {
int o = p->orientation;
switch (dir) {
case CW:
o = (p->orientation + 1) % NUM_ORIENTATIONS;
break;
case CCW:
if (p->orientation == 0) {
o = NUM_ORIENTATIONS;
}
o--;
break;
}
Vec2 nudge = {};
if (pieceFits(st, p->type, o, p->x, p->y, &nudge)) {
p->orientation = o;
return true;
}
if (nudge.x != 0 || nudge.y != 0) {
if (!pieceFits(st, p->type, o, p->x+nudge.x, p->y+nudge.y)) {
return false;
}
p->x += nudge.x;
p->y += nudge.y;
} else {
Vec2 cwtries[] = {
{-1, 0},
{0, -1},
{-2, 0},
{0, -2},
{1, 0},
{0, 1},
{2, 0},
{0, 2},
};
Vec2 ccwtries[] = {
{1, 0},
{0, -1},
{2, 0},
{0, -2},
{-1, 0},
{0, 1},
{-2, 0},
{0, 2},
};
for (int i = 0; i < (int)(sizeof(cwtries)/sizeof(Vec2)); i++) {
Vec2 v = (dir == CW ? cwtries : ccwtries)[i];
if (pieceFits(st, p->type, o, p->x+v.x, p->y+v.y)) {
p->x += v.x;
p->y += v.y;
goto hooray;
}
}
return false;
}
hooray:
p->orientation = o;
return true;
}
struct {
int32_t bloop;
int32_t drop1;
int32_t drop2;
int32_t drop3;
int32_t menu;
int32_t smallExplosion;
int32_t explosion;
int32_t gameover;
int32_t highscore;
int32_t back;
int32_t select;
int32_t whooop;
} sounds;
DEFINE_BUTTON(MainMenu_StartGameButton);
DEFINE_BUTTON(MainMenu_WatchReplayButton);
DEFINE_BUTTON(MainMenu_OptionsButton);
DEFINE_BUTTON(MainMenu_HighScoresButton);
DEFINE_BUTTON(MainMenu_CreditsButton);
DEFINE_BUTTON(MainMenu_QuitButton);
void initTitleMenu(GameState *st) {
MenuContext *menu = &st->titleMenu;
menu->font = &ubuntu_m32;
menu->soundHover = sounds.menu;
menu->soundSelect = sounds.select;
menu->soundCancel = sounds.back;
menu->lines = 0;
menu->alignWidth = 24;
menu->topCenter = vec2(app->width/2, app->height/2 + 140*scale());
addMenuLine(menu, (char *)"start a game", MainMenu_StartGameButton);
addMenuLine(menu, (char *)"watch a replay", MainMenu_WatchReplayButton);
addMenuLine(menu, (char *)"options", MainMenu_OptionsButton);
addMenuLine(menu, (char *)"high scores", MainMenu_HighScoresButton);
addMenuLine(menu, (char *)"credits", MainMenu_CreditsButton);
#ifndef __EMSCRIPTEN__
addMenuLine(menu, (char *)"quit", MainMenu_QuitButton);
#endif
menu->hotIndex = 0;
}
DEFINE_BUTTON(OptionsMenu_ResumeButton);
DEFINE_BUTTON(OptionsMenu_ControlsButton);
DEFINE_BUTTON(OptionsMenu_SettingsButton);
DEFINE_BUTTON(OptionsMenu_BackButton);
DEFINE_BUTTON(OptionsMenu_QuitButton);
DEFINE_BUTTON(OptionsMenu_MainMenuButton);
DEFINE_BUTTON(OptionsMenu_ResetDefaults);
DEFINE_BUTTON(OptionsMenu_ScaleUpButton);
DEFINE_BUTTON(OptionsMenu_ScaleDownButton);
void initOptionsMenu(GameState *st) {
MenuContext *menu = &st->options;
menu->font = &mono_m18;
menu->soundHover = sounds.menu;
menu->soundSelect = sounds.select;
menu->soundCancel = sounds.back;
menu->lines = 0;
menu->alignWidth = 24;
menu->topCenter = vec2(app->width/2, 200*scale());
addMenuLine(menu, (char *)"[ options ]");
addMenuLine(menu, (char *)"resume", OptionsMenu_ResumeButton);
addMenuLine(menu, (char *)"controls", OptionsMenu_ControlsButton);
addMenuLine(menu, (char *)"settings", OptionsMenu_SettingsButton);
addMenuLine(menu, (char *)"main menu", OptionsMenu_MainMenuButton);
#ifndef __EMSCRIPTEN__
addMenuLine(menu, (char *)"quit", OptionsMenu_QuitButton);
#endif
menu->hotIndex = 1;
menu = &st->controlsMenu;
menu->font = &mono_m18;
menu->soundHover = sounds.menu;
menu->soundSelect = sounds.select;
menu->soundCancel = sounds.back;
menu->lines = 0;
menu->alignWidth = 24;
menu->topCenter = vec2(app->width/2, 200*scale());
addMenuLine(menu, (char *)"[ controls ]");
addMenuLine(menu, (char *)"left", &st->settings.controls.left);
addMenuLine(menu, (char *)"right", &st->settings.controls.right);
addMenuLine(menu, (char *)"down", &st->settings.controls.down);
addMenuLine(menu, (char *)"drop", &st->settings.controls.drop);
addMenuLine(menu, (char *)"store", &st->settings.controls.store);
addMenuLine(menu, (char *)"rotate cw", &st->settings.controls.rotateCW);
addMenuLine(menu, (char *)"rotate ccw", &st->settings.controls.rotateCCW);
addMenuLine(menu, (char *)"");
addMenuLine(menu, (char *)"pause", &st->settings.controls.pause);
addMenuLine(menu, (char *)"rewind", &st->settings.controls.rewind);
addMenuLine(menu, (char *)"mute", &st->settings.controls.mute);
addMenuLine(menu, (char *)"quick reset", &st->settings.controls.reset);
addMenuLine(menu, (char *)"save", &st->settings.controls.save);
addMenuLine(menu, (char *)"restore", &st->settings.controls.restore);
addMenuLine(menu, (char *)"");
addMenuLine(menu, (char *)"reset defaults", OptionsMenu_ResetDefaults);
addMenuLine(menu, (char *)"back", OptionsMenu_BackButton);
menu->hotIndex = 1;
menu = &st->settingsMenu;
menu->font = &mono_m18;
menu->soundHover = sounds.menu;
menu->soundSelect = sounds.select;
menu->soundCancel = sounds.back;
menu->lines = 0;
menu->alignWidth = 30;
menu->topCenter = vec2(app->width/2, 200*scale());
addMenuLine(menu, (char *)"[ settings ]");
addMenuLine(menu, (char *)"sounds effects", &st->settings.soundEffects);
addMenuLine(menu, (char *)"rewind sound", &st->settings.rewindSound);
addMenuLine(menu, (char *)"ghost", &st->settings.showGhost);
addMenuLine(menu, (char *)"screen shake", &st->settings.screenShake);
addMenuLine(menu, (char *)"move delay (ms)", &st->settings.moveDelayMillis);
addMenuLine(menu, (char *)"move start delay (ms)", &st->settings.moveStartDelayMillis);
addMenuLine(menu, (char *)"");
addMenuLine(menu, (char *)"scale up", OptionsMenu_ScaleUpButton);
addMenuLine(menu, (char *)"scale down", OptionsMenu_ScaleDownButton);
addMenuLine(menu, (char *)"");
addMenuLine(menu, (char *)"reset defaults", OptionsMenu_ResetDefaults);
addMenuLine(menu, (char *)"back", OptionsMenu_BackButton);
menu->hotIndex = 1;
}
#define KEY_FIELD(key) FIELD_FN(controls.key, "%s", SDL_GetKeyName, SDL_GetKeyFromName)
DEFINE_SERDE(Settings,
KEY_FIELD(left),
KEY_FIELD(right),
KEY_FIELD(down),
KEY_FIELD(drop),
KEY_FIELD(store),
KEY_FIELD(rotateCW),
KEY_FIELD(rotateCCW),
KEY_FIELD(pause),
KEY_FIELD(rewind),
KEY_FIELD(reset),
KEY_FIELD(mute),
KEY_FIELD(save),
KEY_FIELD(restore),
BOOL_FIELD(soundEffects),
BOOL_FIELD(rewindSound),
BOOL_FIELD(showGhost),
BOOL_FIELD(screenShake),
INT_FIELD(moveDelayMillis),
INT_FIELD(moveStartDelayMillis)
)
void saveHighScores(GameState *st, const char *filename) {
uint8_t *inPtr = (uint8_t*)&st->highScores[0];
uint32_t inSize = sizeof(st->highScores);
#ifdef __EMSCRIPTEN__
EM_ASM({
var a = Module.HEAPU8.subarray($0, $0+$1);
var data = String.fromCharCode.apply(null, a);
localStorage.setItem("highscores", data);
}, inPtr, inSize);
#else
char *expanded = expandPath(filename);
if (expanded) {
filename = expanded;
}
FILE *f = fopen(filename, "wb");
if (!f) {
fprintf(stderr, (char*)"error writing to file %s: %d\n", filename, errno);
free(expanded);
return;
}
fwrite(inPtr, sizeof(uint8_t), inSize, f);
fclose(f);
free(expanded);
#endif
}
bool loadHighScores(GameState *st, const char *filename) {
uint8_t *buf = NULL;
#ifdef __EMSCRIPTEN__
buf = (uint8_t*)EM_ASM_INT({
try {
var jsString = localStorage.getItem("highscores");
var lengthBytes = jsString.length+1;
var stringOnWasmHeap = _malloc(lengthBytes);
stringToAscii(jsString, stringOnWasmHeap, lengthBytes);
return stringOnWasmHeap;
} catch (e) {
console.error(e);
return null;
}
});
#else
buf = readFile(filename);
#endif
if (!buf) {
return false;
}
HighScore *src = (HighScore*)buf;
for (int i = 0; i < HIGH_SCORE_LIST_LENGTH; i++)
st->highScores[i] = *src++;
free(buf);
return true;
}
bool loadSettings(Settings *s, const char *filename) {
uint8_t *buf = NULL;
#ifdef __EMSCRIPTEN__
buf = (uint8_t*)EM_ASM_INT({
try {
var jsString = localStorage.getItem("settings");
var lengthBytes = jsString.length+1;
var stringOnWasmHeap = _malloc(lengthBytes);
stringToAscii(jsString, stringOnWasmHeap, lengthBytes);
return stringOnWasmHeap;
} catch (e) {
console.error(e);
return null;
}
});
#else
buf = readFile(filename);
#endif
if (!buf) {
return false;
}
deserializeSettings(s, buf);
free(buf);
return true;
}
bool saveSettings(Settings *s, const char *filename) {
bool result;
uint8_t *buf = serializeSettings(s);
#ifdef __EMSCRIPTEN__
EM_ASM({
localStorage.setItem("settings", AsciiToString($0));
}, buf);
result = true;
#else
result = writeFile(filename, buf);
#endif
free(buf);
return result;
}
bool compileExtraShaders(Renderer *r) {
uint8_t *shaderBuf = readFile("assets/shaders/title.vs");
if (!shaderBuf) {
return false;
}
if (!compileShader(&titleShader.vert, shaderBuf, GL_VERTEX_SHADER)) {
return false;
}
shaderBuf = readFile("assets/shaders/title.fs");
if (!shaderBuf) {
return false;
}
if (!compileShader(&titleShader.frag, shaderBuf, GL_FRAGMENT_SHADER)) {
return false;
}
if (!compileShaderProgram(&titleShader)) {
return false;
}
shaderBuf = readFile("assets/shaders/bg.fs");
if (!shaderBuf) {
return false;
}
titleBGShader.vert = r->defaultShader.vert;
if (!compileShader(&titleBGShader.frag, shaderBuf, GL_FRAGMENT_SHADER)) {
return false;
}
if (!compileShaderProgram(&titleBGShader)) {
return false;
}
shaderBuf = readFile("assets/shaders/vhs.fs");
if (!shaderBuf) {
return false;
}
vhsShader.vert = r->defaultShader.vert;
if (!compileShader(&vhsShader.frag, shaderBuf, GL_FRAGMENT_SHADER)) {
return false;
}
if (!compileShaderProgram(&vhsShader)) {
return false;
}
return true;
}
bool startGame(GameState *st, Renderer *r, App *a) {
assert(a);
app = a;
if (!(ubuntu_ttf_buffer = readFile("./assets/fonts/Ubuntu-M.ttf"))) {
return false;
}
loadFontAtlas(&ubuntu_m32, ubuntu_ttf_buffer, 32.0f);
ubuntu_m32.padding = 10.0f;
loadFontAtlas(&ubuntu_m16, ubuntu_ttf_buffer, 16.0f);
ubuntu_m16.padding = 10.0f;
if (!(mono_ttf_buffer = readFile("./assets/fonts/DejaVuSansMono-Bold.ttf"))) {
return false;
}
loadFontAtlas(&mono_m18, mono_ttf_buffer, 18.0f);
mono_m18.padding = 10.0f;
{
sounds.bloop = loadAudioAndConvert("./assets/sounds/bloop.wav");
if (sounds.bloop == -1) return false;
sounds.drop1 = loadAudioAndConvert("./assets/sounds/drop1.wav");
if (sounds.drop1 == -1) return false;
sounds.drop2 = loadAudioAndConvert("./assets/sounds/drop2.wav");
if (sounds.drop2 == -1) return false;
sounds.drop3 = loadAudioAndConvert("./assets/sounds/drop3.wav");
if (sounds.drop3 == -1) return false;
sounds.menu = loadAudioAndConvert("./assets/sounds/menu.wav");
if (sounds.menu == -1) return false;
sounds.smallExplosion = loadAudioAndConvert("./assets/sounds/small-explosion.wav");
if (sounds.smallExplosion == -1) return false;
sounds.explosion = loadAudioAndConvert("./assets/sounds/explosion.wav");
if (sounds.explosion == -1) return false;
sounds.gameover = loadAudioAndConvert("./assets/sounds/gameover.wav");
if (sounds.gameover == -1) return false;
sounds.back = loadAudioAndConvert("./assets/sounds/back.wav");
if (sounds.back == -1) return false;
sounds.select = loadAudioAndConvert("./assets/sounds/select.wav");
if (sounds.select == -1) return false;
sounds.whooop = loadAudioAndConvert("./assets/sounds/whooop.wav");
if (sounds.whooop == -1) return false;
}
loadHighScores(st, HIGHSCORES_FILE);
if (!loadSettings(&st->settings, SETTINGS_FILE)) {
log("settings not found, saving defaults");
if (!saveSettings(&st->settings, SETTINGS_FILE)) {
log("settings save failed");
}
loadSettings(&st->settings, SETTINGS_FILE);
}
setMuted(!st->settings.soundEffects);
st->scenes[st->currentScene] = TITLE;
//int32_t sound_hiscore = loadAudioAndConvert("assets/sounds/hiscore.wav");
//if (sound_hiscore == -1) { return NULL; }
initTitleMenu(st);
initOptionsMenu(st);
if (!compileExtraShaders(r))
return false;
return true;
}
int firstFilled(int type, int o) {
for (int i = 0; i < PIECE_BLOCK_TOTAL; i++) {
if (pieces[type][o][i])
return i;
}
return -1;
}
int firstFilledRow(int type, int o) {
return firstFilled(type, o)/4;
}
#define swap(a, b) { int _x = *a; *a = *b; *b = _x; }
bool spawnFaller(GameState *st) {
st->inRound.faller.orientation = 0;
st->inRound.faller.type = st->inRound.queue[0];
st->inRound.faller.x = 3;
st->inRound.faller.y = -(firstFilledRow(st->inRound.faller.type, st->inRound.faller.orientation));
for (int i = 0; i < QUEUE_SIZE-1; i++)
st->inRound.queue[i] = st->inRound.queue[i+1];
st->inRound.queueRemaining--;
if (st->inRound.queueRemaining <= 2*NUM_PIECES) {
int base[NUM_PIECES];
int n = NUM_PIECES;
for (int i = 0; i < n; i++) {
base[i] = i;
}
// fill the back half of the queue
for (int x = 0; x < 2; x++) {
// fisher-yates shuffle
for (int i = n-1; i > 0; i--) {
int j = randn(i+1);
swap(&base[i], &base[j]);
}
// copy in
for (int i = 0; i < n; i++) {
st->inRound.queue[st->inRound.queueRemaining++] = base[i];
}
}
}
if (!pieceFits(st, &st->inRound.faller)) {
return false;
}
return true;
}
void setScene(GameState *st, Scene s) {
st->scenes[st->currentScene] = s;
}
void pushScene(GameState *st, Scene s) {
assert(st->currentScene+1 < (int)(sizeof(st->scenes)/sizeof(Scene)));
st->scenes[++st->currentScene] = s;
}
void popScene(GameState *st) {
assert(st->currentScene > 0);
st->currentScene--;
}
Transition no_transition;
Transition *transition(GameState *st, Transition::Type tp, Scene to, float duration) {
Transition t = {};
t.type = tp;
t.to = to;
t.duration = duration;
st->transition = t;
return &st->transition;
}
Rect border(GameState *st) {
int board_width_px = (BOARD_WIDTH * blockSide(st) + (BOARD_WIDTH + 1) * blockPad(st));
int board_height_px = (BOARD_HEIGHT * blockSide(st) + (BOARD_HEIGHT + 1) * blockPad(st));
Vec2 ul_corner = {
.x = app->width/2.0f - board_width_px / 2.0f,
.y = app->height/2.0f - board_height_px / 2.0f,
};
return Rect{
.pos = ul_corner,
.box = vec2(board_width_px, board_height_px),
};
}
bool replaying = false;
int cursor = 0;
struct {
uint32_t seed;
uint32_t cap = 0, len = 0;
InputData *replayInputs;
} replayData;
void startRound(GameState *st) {
/* playSound(sound_ready); */
st->rw.cursor = 0;
st->rw.size = 0;
st->rw.rewindCount = 0;
st->inRound.score = 0;
st->inRound.stored = -1;
st->inRound.canStore = true;
st->inRound.roundInProgress = true;
if (!replaying) {
replayData.len = 0;
replayData.cap = 0;
if (replayData.replayInputs) free(replayData.replayInputs);
replayData.replayInputs = NULL;
}
log("setting seed %u", replayData.seed);
srand(replayData.seed);
for (int y = 0; y < BOARD_HEIGHT; y++)
for (int x = 0; x < BOARD_WIDTH; x++)
st->inRound.board[y][x] = (Cell){.full = false};
for (int i = 0; i < MAX_BLOCKS; i++)
st->inRound.blocks[i].inUse = false;
int base[NUM_PIECES];
int n = NUM_PIECES;
for (int i = 0; i < n; i++) {
base[i] = i;
}
// fill the entire queue
st->inRound.queueRemaining = 0;
for (int x = 0; x < 4; x++) {
// fisher-yates shuffle
for (int i = n-1; i > 0; i--) {
int j = randn(i+1);
swap(&base[i], &base[j]);
}
// copy in
for (int i = 0; i < n; i++) {
st->inRound.queue[st->inRound.queueRemaining++] = base[i];
}
}
assert(spawnFaller(st));
}
void transitionStartRound(GameState *st) {
transition(st, Transition::CHECKER_IN_OUT, IN_ROUND, 1500);
st->transition.fn = startRound;
}
float tickInterval = 1200.0f;
Vec2 gridBlockPos(GameState *st, Vec2 ul, int x, int y) {
return vec2(
(x + 0.5) * blockSide(st) + (x + 1) * blockPad(st) + ul.x,
(y + 0.5) * blockSide(st) + (y + 1) * blockPad(st) + ul.y
);
}
void tryClearingLine(GameState *st, int line) {
Vec2 ul = border(st).pos;
Cell *row = st->inRound.board[line];
for (int x = 0; x < BOARD_WIDTH; x++) {
assert(row[x].full);
row[x].full = false;
Block *b = &st->inRound.blocks[row[x].blockIndex];
// fly off board
b->onBoard = false;
b->timeLeft = 3200.0f;
b->rotv = randf(8.0f) - 4.0f;
b->vel.x = randf(9.0f) - 4.5f;
b->vel.y = randf(-7.5f) - 0.5f;
for (int y = line-1; y >= 0; y--) {
st->inRound.board[y+1][x] = st->inRound.board[y][x];
if (!st->inRound.board[y][x].full) continue;
st->inRound.blocks[st->inRound.board[y+1][x].blockIndex].y = y + 1;
st->inRound.blocks[st->inRound.board[y+1][x].blockIndex].tweenStep = 0;
}
st->inRound.board[0][x].full = false;
}
}
void clearLines(GameState *st) {
int cleared = 0;
for (int y = 0; y < BOARD_HEIGHT; y++) {
bool all = true;
for (int x = 0; x < BOARD_WIDTH; x++) {
if (!st->inRound.board[y][x].full) {
all = false;
break;
}
}
if (!all) {
continue;
}
tryClearingLine(st, y);
cleared++;
st->inRound.shaking += st->inRound.shaking > 1 ? 250.0f : 600.0f;
}
if (cleared > 0) {
if (cleared > 2) playSound(sounds.explosion);
else playSound(sounds.smallExplosion);
st->inRound.combo++;
st->inRound.score += cleared * st->inRound.combo;
} else {
st->inRound.combo = 0;
}
}
int placeBlock(GameState *st, Block b) {
int idx;
for (int i = 0; i < MAX_BLOCKS; i++) {
idx = (i + st->inRound.lastBlockInUse) % MAX_BLOCKS;
if (!st->inRound.blocks[idx].inUse)
break;
// fall through if we run out
}
st->inRound.blocks[idx] = b;
st->inRound.lastBlockInUse = idx;
return idx;
}
FlashMessage *freeMessageSlot(GameState *st) {
for (int i = 0; i < FLASH_MESSAGE_COUNT; i++) {
FlashMessage *msg = &st->inRound.messages[i];
if (msg->active) continue;
return msg;
}
return &st->inRound.messages[0];
}
FlashMessage *flashMessage(GameState *st, const char *text, Vec2 pos) {
FlashMessage *msg = freeMessageSlot(st);
msg->active = true;
int i = 0;
while ((msg->text[i] = text[i]) && ++i < sizeof(msg->text));
msg->totalLifetime = 2000.0f;
msg->lifetime = msg->totalLifetime;
msg->pos = pos;
msg->vel = {};
return msg;
}
FlashMessage *flashMessage(GameState *st, const char *text) {
return flashMessage(st, text, vec2(0, 0));
}
void placePiece(GameState *st, Piece *p) {
Vec2 ul = border(st).pos;
for (int i = 0; i < PIECE_BLOCK_TOTAL; i++) {
if (!pieces[p->type][p->orientation][i]) continue;
Block b = {0};
b.inUse = true;
b.onBoard = true;
b.color = colors[p->type];
int x = p->x+i%4;
int y = p->y+i/4;
b.x = x;
b.y = y;
b.targetPos = gridBlockPos(st, ul, x, y);
b.pos = b.targetPos;
st->inRound.board[y][x].full = true;
st->inRound.board[y][x].blockIndex = placeBlock(st, b);
//int idx = placeBlock(st, b);
//st->board[y][x].block = &st->inRound.blocks[idx];
}
clearLines(st);
if (st->inRound.combo > 1) {
char buf[64];
snprintf(buf, sizeof(buf), "%dx", st->inRound.combo);
int x = p->x+1;
int y = p->y-2;
FlashMessage *msg = flashMessage(st, buf, gridBlockPos(st, ul, x, y));
msg->vel = vec2(0, -1);
}
st->inRound.canStore = true;
}
// old == false, new == true
bool updateTransition(Transition *t, InputData in) {
t->t += in.dt;
t->z = t->t/t->duration;
// TODO:
//t->z = t->easing(t->z);
switch (t->type) {
case Transition::FADE_IN_OUT:
case Transition::ROWS_ACROSS:
case Transition::CHECKER_IN_OUT:
case Transition::CHECKER_IN_OUT_ROTATE:
t->z = t->z;
break;
default:
break;
}
if (t->z >= 1)
*t = no_transition;
return t->z > 0.5f;
}
bool updateGameState(GameState *st, InputData in) {
// only update the fps once a second so it's (slightly) smoother
static float acc = 0;
acc += in.dt;
if (acc > 1000.0f) {
acc = 0;
st->fps = 1000.0f/in.dt;
}
st->inRound.elapsed += in.dt;
if (in.quit) {
return false;
}
Transition *t = &st->transition;
if (t->type == Transition::NONE) {
return updateScene(st, in, st->scenes[st->currentScene]);
} else {
if (updateTransition(t, in)) {
if (t->fn) {
t->fn(st);
t->fn = NULL;
}
setScene(st, t->to);
}
}
return true;
}
void renderBoard(Renderer *r, GameState *st) {
Vec2 ul = border(st).pos;
for (int i = 0; i < MAX_BLOCKS; i++) {
if (!st->inRound.blocks[i].inUse) continue;
Block *b = &st->inRound.blocks[i];
// fix for scaling while in-round scene is visible but not updating
if (b->onBoard) {
b->targetPos = gridBlockPos(st, ul, b->x, b->y);
b->pos = b->targetPos;
}
DrawOpts2d opts;
Rect rx = rect(b->pos, blockSide(st), blockSide(st));
opts.origin = scaled(rx.box, 0.5);
opts.tint = b->color;
opts.rotation = b->rotation;
drawRect(r, rx, opts);
}
// faller
for (int i = 0; i < PIECE_BLOCK_TOTAL; i++) {
if (!pieces[st->inRound.faller.type][st->inRound.faller.orientation][i]) {
continue;
}
int x = i % 4;
int y = i / 4;
if (!inBounds(st->inRound.faller.x+x, st->inRound.faller.y+y) || st->inRound.faller.y+y < 0) {
continue;
}
Rect rx = rect(gridBlockPos(st, ul, st->inRound.faller.x+x, st->inRound.faller.y+y), blockSide(st), blockSide(st));
rx.pos.x -= blockSide(st)/2;
rx.pos.y -= blockSide(st)/2;
drawRect(r, rx, colors[st->inRound.faller.type]);
}
if (st->inRound.stored != -1) {
bool anyInRow = false;
float side = blockSide(st) * 0.7f;
float pad = blockPad(st) * 0.7f;
Vec2 v = vec2(16, 200);
Vec2 box = vec2(side, side);
int y = 0;
for (int i = 0; i < PIECE_BLOCK_TOTAL; i++) {
int x = i % 4;
if (x == 0 && anyInRow) {
y++;
}
if (!pieces[st->inRound.stored][0][i]) {
continue;
}
anyInRow = true;
Vec2 p = vec2(
(x * (side + pad) + v.x),
(y * (side + pad) + v.y)
);
drawRect(r, rect(p, box), colors[st->inRound.stored]);
}
}
}
void renderGhost(Renderer *r, GameState *st) {
Piece cp = st->inRound.faller;
//Color c = multiply(colors[cp.type], 1.70);
Color c = colors[cp.type];
while (tryMove(st, &cp, 0, 1));
Vec2 ul = border(st).pos;
for (int i = 0; i < PIECE_BLOCK_TOTAL; i++) {
if (!pieces[cp.type][cp.orientation][i]) {
continue;
}
int x = i % 4;
int y = i / 4;
if (!inBounds(cp.x+x, cp.y+y) || cp.y+y < 0) {
continue;
}
Rect rx = rect(gridBlockPos(st, ul, cp.x+x, cp.y+y), blockSide(st), blockSide(st));
rx.pos.x -= blockSide(st)/2;
rx.pos.y -= blockSide(st)/2;
drawRectOutline(r, rx, c, 2.0f);
}
}
void updateFlashMessages(GameState *st, InputData in) {
for (int i = 0; i < FLASH_MESSAGE_COUNT; i++) {