-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathxjump.c
1342 lines (1118 loc) · 41.6 KB
/
xjump.c
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
// Copyright 1997-1999 Tatsuya Kudoh
// Copyright 1997-1999 Masato Taruishi
// Copyright 2015-2021 Hugo Gualandi
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#define _POSIX_C_SOURCE 200112L
#include <SDL.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <inttypes.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/random.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "config.h"
#define XJUMP_FONTDIR XJUMP_DATADIR "/xjump"
#define XJUMP_THEMEDIR XJUMP_DATADIR "/xjump/themes"
//
// Helper functions
// ----------------
static int min(int x, int y)
{
return (x < y ? x : y);
}
static int max(int x, int y)
{
return (x > y ? x : y);
}
static int mod(int n, int m)
{
assert(m > 0);
int r = n % m;
return (r >= 0 ? r : r + m);
}
static bool isNullOrEmpty(const char *s)
{
return (s == NULL) || (*s == '\0');
}
static char *concat(const char **strs)
{;
size_t len = 0;
for (const char **s = strs; *s != NULL; s++) {
len += strlen(*s);
}
char *res = malloc(len+1);
res[0] = '\0';
for (const char **s = strs; *s != NULL; s++) {
strcat(res, *s); // O(N^2) but should not matter
}
return res;
}
//
// Error handling
// --------------
static void panic(const char *what, const char *fullError)
{
if (fullError == NULL) fullError = "";
fprintf(stderr, "Internal error! %s. %s\n", what, fullError);
exit(1);
}
//
// Command-line arguments & config
// -------------------------------
int isSoftScroll = 1;
char *themePath = XJUMP_THEMEDIR "/jumpnbump.bmp";
static void print_usage(const char * progname)
{
printf("Usage: %s [OPTIONS]...\n"
"A jumping game for X.\n"
"\n"
" -h --help show this help message and exit\n"
" -v --version show version information and exit\n"
" --soft-scroll use Xjump 3.0 scrolling behavior (default)\n"
" --hard-scroll use Xjump 1.0 scrolling behavior\n"
" --theme NAME use a pre-installed sprite theme (eg. --theme=classic)\n"
" --graphic FILE use a custom sprite theme (path to a bitmap file)\n"
"\n"
"Alternate themes can be found under %s.\n",
progname, XJUMP_THEMEDIR);
}
static void print_version()
{
printf("Xjump version %s\n", XJUMP_VERSION);
}
static void parseCommandLine(int argc, char **argv)
{
static struct option long_options[] = {
/* These options set a flag. */
{"soft-scroll", no_argument, &isSoftScroll, 1},
{"hard-scroll", no_argument, &isSoftScroll, 0},
/* These options don’t set a flag */
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'v'},
{"theme", required_argument, 0, 't'},
{"graphic", required_argument, 0, 'g'},
{0, 0, 0, 0}
};
while (1) {
int option_index = 0;
int c = getopt_long (argc, argv, "hvt:", long_options, &option_index);
if (c == -1) break;
switch (c) {
case 0:
// Set a flag
break;
case 'h':
print_usage(argv[0]);
exit(0);
case 'v':
print_version();
exit(0);
case 't': {
const char *ss[] = { XJUMP_THEMEDIR, "/", optarg, ".bmp", NULL };
themePath = concat(ss);
break;
}
case 'g':
themePath = optarg;
break;
case '?':
// getopt_long already printed an error message
exit(1);
default:
abort(); // Shoulr never happen
}
}
}
//
// Random Number Generator
// -----------------------
//
// References:
// https://www.pcg-random.org
// https://www.pcg-random.org/posts/bounded-rands.html
static uint64_t pcgState = 0x853c49e6748fea9bULL; // Mutable state of the RNG
static uint64_t pcgSeq = 0xda3e39cb94b95bdbULL; // PCG "sequence" parameter
static void pcg32_init(int64_t seed[2])
{
pcgState = seed[0];
pcgSeq = (seed[1] << 1) | 1;
}
static uint32_t pcg32_next()
{
pcgState = pcgState * 6364136223846793005ULL + pcgSeq;
uint32_t xorshifted = ((pcgState >> 18u) ^ pcgState) >> 27u;
uint32_t rot = pcgState >> 59u;
return (xorshifted >> rot) | (xorshifted << ((-rot) & 31));
}
// Returns an uniformly distributed integer in the range [0,a)
static uint32_t pcg32_bounded(uint32_t n)
{
uint32_t x, r;
do {
x = pcg32_next();
r = x % n;
} while (x - r > (-n));
return r;
}
// Returns an uniformly distributed integer in the range [a, b], inclusive
static uint32_t rnd(uint32_t a, uint32_t b)
{
return a + pcg32_bounded(b-a+1);
}
//
// Highscores
// ----------
int64_t bestScoreEver = 0;
int64_t bestScoreToday = 0;
time_t bestScoreExpiration = 0;
FILE *highscoreFile = NULL;
static void highscore_init()
{
char *highscorePath = NULL;
// Locate the local highscore file, following the XDG spec
// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
const char *fileName = "xjump-highscores";
const char *HOME = getenv("HOME");
const char *XDG_DATA_HOME = getenv("XDG_DATA_HOME");
if (!isNullOrEmpty(XDG_DATA_HOME)) {
const char *ss[] = { XDG_DATA_HOME, "/", fileName, NULL };
highscorePath = concat(ss);
} else if (!isNullOrEmpty(HOME)) {
const char *ss[] = { HOME, "/.local/share/", fileName, NULL };
highscorePath = concat(ss);
} else {
fprintf(stderr, "Could not find highscore directory. $HOME is not set.\n");
goto done;
}
// Open the local highscore file or create it if it does not already exist.
// We need to use low level open() to this precise combination of RW plus
// file creation. If we get an error, it's better to get it now than after
// a long game.
int flags = O_RDWR | O_CREAT;
int fd = open(highscorePath, flags, 0666);
if (fd < 0) {
perror("Could not open highscore file");
goto done;
}
// Create a more convenient FILE* handle for the highscores.
highscoreFile = fdopen(fd, "r+");
if (!highscoreFile) {
perror("Could not create highscore file handle");
goto done;
}
done:
if (!highscoreFile) {
fprintf(stderr, "Highscores will not be recorded\n");
}
free(highscorePath);
}
static void highscore_read()
{
rewind(highscoreFile);
if (1 != fscanf(highscoreFile, "best %ld\n", &bestScoreEver)) { return; }
if (2 != fscanf(highscoreFile, "today %ld %ld\n", &bestScoreToday, &bestScoreExpiration)) { return; }
}
static void highscore_write()
{
rewind(highscoreFile);
if (0 != ftruncate(fileno(highscoreFile), 0)) {
panic("Could not reset highscore file", strerror(errno));
}
fprintf(highscoreFile, "best %ld\n", bestScoreEver);
fprintf(highscoreFile, "today %ld %ld\n", bestScoreToday, bestScoreExpiration);
fflush(highscoreFile);
}
static time_t end_of_day(time_t now)
{
struct tm *date = localtime(&now);
date->tm_mday += 1;
date->tm_hour = 0;
date->tm_min = 0;
date->tm_sec = 0;
return mktime(date);
}
static void highscore_update(int64_t newScore)
{
time_t now = time(NULL);
if (highscoreFile) {
if (0 != flock(fileno(highscoreFile), LOCK_EX)) {
panic("Could not acquire file lock", strerror(errno));
}
highscore_read();
if (newScore > bestScoreEver) {
bestScoreEver = newScore;
}
if (newScore > bestScoreToday || bestScoreExpiration < now) {
bestScoreToday = newScore;
bestScoreExpiration = end_of_day(now);
}
highscore_write();
if (0 != flock(fileno(highscoreFile), LOCK_UN)) {
panic("Could not release file lock", strerror(errno));
}
}
}
//
// Joystick state
// --------------
// This component keeps track of the "joystick" state.
// If both LEFT and RIGHT a pressed at the same time, the most recent one wins.
typedef enum {
LR_NEUTRAL,
LR_LEFT,
LR_RIGHT
} LeftRight;
typedef enum {
INPUT_JUMP,
INPUT_LEFT,
INPUT_RIGHT,
INPUT_OTHER,
} Input;
static struct {
LeftRight horizDirection;
bool isPressing[INPUT_OTHER+1];
} K;
static Input translateHotkey(SDL_Keysym key)
{
switch (key.scancode) {
case SDL_SCANCODE_UP:
case SDL_SCANCODE_DOWN:
case SDL_SCANCODE_W:
case SDL_SCANCODE_S:
case SDL_SCANCODE_I:
case SDL_SCANCODE_K:
case SDL_SCANCODE_SPACE:
case SDL_SCANCODE_KP_8:
case SDL_SCANCODE_KP_5:
case SDL_SCANCODE_KP_2:
return INPUT_JUMP;
case SDL_SCANCODE_LEFT:
case SDL_SCANCODE_A:
case SDL_SCANCODE_J:
case SDL_SCANCODE_KP_4:
return INPUT_LEFT;
case SDL_SCANCODE_RIGHT:
case SDL_SCANCODE_D:
case SDL_SCANCODE_L:
case SDL_SCANCODE_KP_6:
return INPUT_RIGHT;
default:
return INPUT_OTHER;
}
}
static void init_input()
{
K.horizDirection = LR_NEUTRAL;
for (int i = 0; i < INPUT_OTHER; i++) {
K.isPressing[i] = false;
}
}
static void input_keydown(const SDL_Keysym key)
{
Input input = translateHotkey(key);
if (input != INPUT_OTHER) {
K.isPressing[input] = true;
switch (input) {
case INPUT_LEFT:
K.horizDirection = LR_LEFT;
break;
case INPUT_RIGHT:
K.horizDirection = LR_RIGHT;
break;
default:
break;
}
}
}
static void input_keyup(const SDL_Keysym key)
{
Input input = translateHotkey(key);
if (input != INPUT_OTHER) {
K.isPressing[input] = false;
switch (input) {
case INPUT_LEFT:
K.horizDirection = (K.isPressing[INPUT_RIGHT] ? LR_RIGHT : LR_NEUTRAL);
break;
case INPUT_RIGHT:
K.horizDirection = (K.isPressing[INPUT_LEFT] ? LR_LEFT : LR_NEUTRAL);
break;
default:
break;
}
}
}
//
// Game Logic
// ----------
// HERE BE DRAGONS (SHOULD THIS BE REFACTORED?)
// The game logic that I am using is taken almost directly from the original
// XJump source code, with soft scrolling bolted on top. This causes the soft
// scrolling parts to be a bit unnatural. The original logic is heavily tied
// to the idea that the hero position is it's position in pixels. However, in
// soft scrolling mode this is no longer true because the screen can scroll
// between frames. The end result is stuff like forcedScroll and interpScroll.
//
// Part of me really wants to rewrite this code so that the hero coordinates
// are relative to the bottom of the tower. That would greatly simplify the
// scrolling logic, because that way the scrolling becomes mostly about the
// camera position, not the hero position. But that will wait for another day
// because I don't want to break working code.
//
// We should also consider if we really want to keep supporting the legacy
// --hard-scroll mode. It took a lot of effort to stamp out all the scrolling
// bugs and in the end the hard scroll logic was completely different than the
// --soft-scroll one...
#define S 16 /* Size of a sprite tile, in pixels */
#define R 32 /* Size of the player sprite, in pixels */
#define FIELD_W 32 /* Width of playing field, in tiles */
#define FIELD_H 24 /* Height of playing field, in tiles */
#define FIELD_EXTRA 3 /* Number of extra rows that we have to draw, to support scrolling */
#define NFLOORS 64 /* Number of floors held in memory */
#define GAME_SPEED 25 /* (40 FPS) Time per simulation frame, in milliseconds */
#define MAX_SCROLL_SPEED 5000 /* scrollCount increment per frame, at max speed */
#define SCROLL_THRESHOLD 20000 /* scrollCount that triggers a frame change */
static const int leftLimit = S; // x coordinate that collides with left
static const int rightLimit = (FIELD_W-1)*S - R; // x coordinate that collides with right
static const int topLimit = 5*S; // y coordinate that triggers a forced scroll
static const int botLimit = FIELD_H*S; // y coordinate that triggers a game over
typedef struct {
int left;
int right;
} Floor;
static struct {
int64_t score;
// Physics
int x, y; // Top-left of the hero sprite, relative to top-left of screen.
int vx, vy; // Speed. vy is in pixels per frame but vx is in half-pixels.
int jump; // Lowers the gravity during the rising arc of jump, if JUMP button is held.
// Animations
int isStanding;
int isFacingRight;
int isIdleVariant;
int idleCount;
// Scrolling
int hasStarted; // Don't start scrolling until we jump for the first time
int floorOffset; // Tile height of the row at the top of the screen
int forcedScroll; // Additional scroll distance in pixels. Happens when you get close to the top.
int scrollCount;
int scrollSpeed;
// Floors
int fpos;
int next_floor;
Floor floors[NFLOORS];
} G;
static Floor *get_floor(int n)
{
return &G.floors[mod(n, NFLOORS)];
}
static void generate_floor()
{
// Floor positions are measured in tiles and are stored in a circular
// buffer. The left and right positions are inclusive, ranging [1,30].
// The left and right walls are in positions 0 and 31, respectively.
// The "origin" of each floor ranges [5,26] and is encoded by the fpos
// variable, which can range between [0,21]. There can be between 2-4
// tiles to the left and to the right of the origin, totaling 5-9 tiles.
int n = G.next_floor++;
Floor *floor = get_floor(n);
if (n % 250 == 0) {
floor->left = 1;
floor->right = 30;
} else if (n % 5 == 0) {
int sign = (rnd(0,1) ? +1 : -1);
int magnitude = rnd(5,9);
G.fpos = mod(G.fpos + sign*magnitude, 22);
floor->left = G.fpos+5 - rnd(2,4);
floor->right = G.fpos+5 + rnd(2,4);
} else {
floor->left = -10;
floor->right = -20;
}
}
static void init_game()
{
G.score = 0;
G.x = (FIELD_W/2)*S - R/2;
G.y = (FIELD_H-4)*S - R;
G.vx = 0;
G.vy = 0;
G.jump = 0;
G.isStanding = true;
G.isFacingRight = false;
G.isIdleVariant = false;
G.idleCount = 0;
G.hasStarted = false;
G.floorOffset = 20;
G.forcedScroll = 0;
G.scrollCount = 0;
G.scrollSpeed = 0;
G.fpos = rnd(0,21);
G.next_floor = -3;
for (int i=0; i < NFLOORS; i++) {
generate_floor();
}
}
static void scroll()
{
generate_floor();
G.floorOffset += 1;
G.y += S;
if (G.forcedScroll >= S) {
G.forcedScroll -= S;
}
}
static bool isStanding(int hx, int hy)
{
if (G.vy < 0) {
return false;
}
int y = (hy + R)/S;
if (y >= FIELD_H) {
return false;
}
// We're standing as long as 8/32 pixels touch the ground.
const Floor *fl = get_floor(G.floorOffset - y);
return (fl->left*S - 24 <= hx && hx <= fl->right*S + 8);
}
static int collideWithFloor(int hy) {
return (hy / S) * S;
}
static bool updateGame()
{
G.x += G.vx / 2;
G.y += G.vy;
// First we collide with the walls, setting the x coordinate.
// The original version of xjump just set the x coordinate glued to the wall. This version makes
// the walls subtly bouncier by taking into account the X velocity after the bounce. It's subtle
// but feels better, IMO, specially if you are just bouncing off the walls before the game
// starts. The "-2" in the formula is a dampening factor to avoid "flickering" 1px bounces.
if (G.x < leftLimit && G.vx <= 0) {
G.x = leftLimit + max(0, leftLimit - G.x - 2)/2;
G.vx = -G.vx/2;
}
if (G.x > rightLimit && G.vx >= 0) {
G.x = rightLimit - max(0, G.x - rightLimit - 2)/2;
G.vx = -G.vx/2;
}
// Next we collide with the floors, setting the y coordinate.
// This must be after the wall collisions because it depends on the x.
G.isStanding = isStanding(G.x, G.y);
if (G.isStanding) {
G.y = collideWithFloor(G.y);
G.vy = 0;
int n = (G.floorOffset - (G.y + R)/S) / 5;
if (n > G.score) {
G.score = n;
}
if (++G.idleCount >= 5) {
G.isIdleVariant = !G.isIdleVariant;
G.idleCount = 0;
}
if (K.isPressing[INPUT_JUMP]) {
G.jump = abs(G.vx)/4+7;
G.vy = -G.jump/2-12;
G.isStanding = true;
if (!G.hasStarted) {
G.hasStarted = true;
G.scrollSpeed = 200;
}
}
}
int accelx = (G.isStanding ? 3 : 2);
switch (K.horizDirection) {
case LR_LEFT:
G.vx = max(G.vx - accelx, -32);
G.isFacingRight = false;
break;
case LR_RIGHT:
G.vx = min(G.vx + accelx, 32);
G.isFacingRight = true;
break;
case LR_NEUTRAL:
if (G.isStanding) {
if (G.vx < -2) G.vx += 3;
else if (G.vx > 2) G.vx -= 3;
else G.vx = 0;
}
break;
}
if (!G.isStanding) {
if (G.jump > 0) {
G.vy = -G.jump/2 - 12;
G.jump = (K.isPressing[INPUT_JUMP] ? G.jump-1 : 0);
} else {
G.vy = min(G.vy + 2, 16);
G.jump = 0;
}
}
// Now we scroll the screen.
// This must be after we know the x and y.
if (G.hasStarted) {
G.scrollSpeed = min(MAX_SCROLL_SPEED, G.scrollSpeed + 1);
G.scrollCount += G.scrollSpeed;
}
while (G.scrollCount > SCROLL_THRESHOLD) {
G.scrollCount -= SCROLL_THRESHOLD;
scroll();
}
// Force scroll if too close to the top. But only if we are in the air, to
// avoid big jumps in the scroll due to collideWithFloor. (For softscroll
// mode, we do this in the rendering loop)
if (!isSoftScroll && !G.isStanding) {
while (G.y < topLimit) {
scroll();
}
}
if (G.y + G.forcedScroll >= botLimit) {
return true;
}
return false;
}
//
// Colors
//
static const SDL_Color backgroundColor = { 0, 0, 0, 255 };
static const SDL_Color textColor = { 255, 255, 255, 255 };
static const SDL_Color copyrightColor = { 0, 255, 0, 255 };
static const SDL_Color boxBorderColor = { 0, 0, 128, 255 };
static const SDL_Color boxColor = { 0, 0, 255, 255 };
static const SDL_Color scoreBorderColor = { 255, 255, 255, 255 };
//
// Text rendering
// --------------
//
// To preserve the classic Xjump look, we ship with a copies of the fonts that
// the original used. On Fedora you needed package xorg-x11-fonts-100dpi.
//
// - Courrier Bold Oblique 18pt, 100dpi variant (courBO18)
// - FixedMedim 10x20
//
// To accurately emulate the classic Xjump look we need to use bitmapped fonts.
// I experimented with using the SDL_TTF library to render the text but the
// True Type fonts only looked nice if we used antialiasing and that doesn't
// match the look that we want... Not to mention that the fonts are not the
// same as the original and that locating system fonts on Linux is a pain.
// The big downside of bitmapped fonts is that they can't represent special
// characters. We are effectively restricted to ACII.
//
// On the matter of font dimensions, both of our fonts are monospaced, where
// the text is arranged in a rectangular grid. However, one subtlety is that in
// the oblique font each letter might reach into the text box for the glyph to
// their right. For this reason, the glyphs in the font file might be arranged
// farther apart than they are in the text.
typedef struct {
int w, h; // Dimensions in the text
int ow, oh; // Dimentions in the sprite file
} FontSize;
static void text_draw_line(
SDL_Renderer *renderer,
SDL_Texture *font,
const FontSize *fz,
const char *message,
const SDL_Rect *where)
{
int w = fz->w;
int h = fz->h;
int ow = fz->ow;
int oh = fz->oh;
int x = where->x;
int y = where->y;
for (int i = 0; message[i] != '\0'; i++) {
char c = message[i];
if (c < ' ' || '~' < c) { c = 127; } // Default glyph
int oi = (c - ' ') % 16;
int oj = (c - ' ') / 16;
const SDL_Rect src = { oi*ow, oj*oh, ow, oh };
const SDL_Rect dst = { x + i*w, y + 0*h, ow, oh };
SDL_RenderCopy(renderer, font, &src, &dst);
}
}
static void text_set_color(SDL_Texture *font, SDL_Color color)
{
// This method of setting colors assumes that the original texture has
// white text on a transparent background.
SDL_SetTextureColorMod(font, color.r, color.g, color.b);
}
// Boxes around text
// -------------------------
#define boxBorder 4
#define boxPadding 4
static void text_draw_box(SDL_Renderer *renderer, const SDL_Rect *content)
{
const SDL_Rect padding = {
content->x - boxPadding,
content->y - boxPadding,
content->w + 2*boxPadding,
content->h + 2*boxPadding,
};
const SDL_Rect border = {
padding.x - boxBorder,
padding.y - boxBorder,
padding.w + 2*boxBorder,
padding.h + 2*boxBorder,
};
SDL_SetRenderDrawColor(renderer, boxBorderColor.r, boxBorderColor.g, boxBorderColor.b, boxBorderColor.a);
SDL_RenderFillRect(renderer, &border);
SDL_SetRenderDrawColor(renderer, boxColor.r, boxColor.g, boxColor.b, boxColor.a);
SDL_RenderFillRect(renderer, &padding);
}
//
// Window placement
//
// Parameters
static const int windowMarginTop = 24;
static const int windowMarginLeft = 24;
static const int windowMarginInner = 24;
static const int windowMarginBottom = windowMarginTop;
static const int windowMarginRight = windowMarginLeft;
char titleBuf[] = "FALLING TOWER ver " XJUMP_VERSION;
static const char *titleMsg = titleBuf;
static const char *scoreLabelMsg = "Floor";
static const char *copyrightMsg = "(C) 1997 ROYALPANDA";
static const char *gameOverMsg = "Game Over";
static const char *pauseMsg = "Pause";
static const char *highscoreMsg1 = "High Score";
static const char *highscoreMsg2 = "Today "; // Please make these two strings have the same length
static const int NscoreDigits = 10;
// Game spritesheet
static const SDL_Rect skySprite = { 4*R, 0*S, S, S};
static const SDL_Rect LWallSprite = { 4*R, 1*S, S, S};
static const SDL_Rect RWallSprite = { 4*R, 2*S, S, S};
static const SDL_Rect floorSprite = { 4*R, 3*S, S, S};
static const SDL_Rect heroSprite[8] = {
{ 0*R, 0*R, R, R}, // Stand L (1/2)
{ 1*R, 0*R, R, R}, // Stand R (1/2)
{ 2*R, 0*R, R, R}, // Stand L (2/2)
{ 3*R, 0*R, R, R}, // Stand R (2/2)
{ 0*R, 1*R, R, R}, // Jump L
{ 1*R, 1*R, R, R}, // Jump R
{ 2*R, 1*R, R, R}, // Fall L
{ 3*R, 1*R, R, R}, // Fall R
};
void init_title()
{
// Hide the minor version number from the app title
int n = 0;
for (char *p = titleBuf; *p != 0; p++) {
if (*p == '.') {
if (++n == 2) {
*p = '\0';
break;
}
}
}
}
SDL_Surface *loadThemeFile(const char *filename)
{
SDL_Surface *surface = SDL_LoadBMP(filename);
if (!surface) {
fprintf(stderr, "Error loading theme file. %s\n.", SDL_GetError());
return NULL;
}
if (surface->w != 4*R + S || surface->h != 2*R) {
fprintf(stderr, "Theme spritesheet has the wrong dimensions.\n");
return NULL;
}
return surface;
}
//
// App State
//
typedef enum {
STATE_RUNNING,
STATE_PAUSED,
STATE_GAMEOVER,
STATE_HIGHSCORES,
} GameState;
GameState currState; // Current screen
GameState lastDrawn; // CPU optimization: don't redraw static screens.
uint32_t currTime; // Current time
uint32_t frameTime; // (if RUNNING) Moment when we ran the last simulation frame.
uint32_t pauseTime; // (if PAUSED) Remaining time difference when we paused (avoids jerky scrolling when unpausing)
uint32_t deathTime; // (if GAMEOVER) Moment when when we entered the game over screen
static void state_set(GameState state)
{
switch (state) {
case STATE_RUNNING:
if (currState == STATE_PAUSED) {
frameTime = currTime - pauseTime;
} else {
frameTime = currTime;
}
break;
case STATE_PAUSED:
assert(currState == STATE_RUNNING);
pauseTime = (currTime - frameTime);
break;
case STATE_GAMEOVER:
deathTime = currTime;
highscore_update(G.score);
break;
case STATE_HIGHSCORES:
break;
}
currState = state;
}
int main(int argc, char **argv)
{
// Configuration
parseCommandLine(argc, argv);
// This is necessary for correct app icon (must be before SDL_Init)
setenv("SDL_VIDEO_WAYLAND_WMCLASS", XJUMP_APPNAME, 0);
setenv("SDL_VIDEO_X11_WMCLASS", XJUMP_APPNAME, 0);
// Initialize subsystems
if (0 != SDL_Init(SDL_INIT_VIDEO))
panic("Could not initialize SDL", SDL_GetError());
atexit(SDL_Quit);
int64_t seed[2];
ssize_t nread = getrandom(seed, sizeof(seed), GRND_NONBLOCK);
if (nread == -1) panic("Could not initialize RNG", strerror(errno));
pcg32_init(seed);
highscore_init();
init_input();
init_game();
init_title();
// Widths and Heights
static const FontSize uiFZ = { 15, 28, 20, 28 };
static const FontSize hsFZ = { 10, 20, 10, 20 };
const int titleW = uiFZ.w * strlen(titleMsg);
const int scoreLabelW = uiFZ.w * strlen(scoreLabelMsg);
const int copyrightW = uiFZ.w * strlen(copyrightMsg);
const int gameOverW = uiFZ.w * strlen(gameOverMsg);
const int pauseW = uiFZ.w * strlen(pauseMsg);
const int textBoxH = uiFZ.h + boxBorder + 2*boxPadding + boxBorder;
const int gameW = S * FIELD_W;
const int gameH = S * FIELD_H;
const int backgroundW = S * FIELD_W;
const int backgroundH = S * (FIELD_H + FIELD_EXTRA);
const int scoreDigitsW = uiFZ.w * NscoreDigits;
const int scoreW = scoreLabelW + uiFZ.w + scoreDigitsW;
const int windowW = windowMarginLeft + gameW + windowMarginRight;
const int windowH = windowMarginTop + 3*windowMarginInner + textBoxH + 2*uiFZ.h + + gameH + windowMarginBottom;
// Screen positions
const int titleX = (windowW - titleW)/2;
const int scoreX = (windowW - scoreW)/2;
const int gameX = (windowW - gameW)/2;
const int copyrightX = (windowW - copyrightW)/2;
const int titleY = windowMarginTop + boxBorder + boxPadding;
const int scoreY = titleY + uiFZ.h + boxPadding + boxBorder + windowMarginInner;
const int gameY = scoreY + uiFZ.h + windowMarginInner;
const int copyrightY = gameY + gameH + windowMarginInner;
const int scoreLabelX = scoreX;
const int scoreDigitsX = scoreX + scoreLabelW + uiFZ.w;
const int gameOverX = gameX + (gameW - gameOverW)/2;
const int gameOverY = gameY + (gameH - uiFZ.h)*2/5;
const int pauseX = gameX + (gameW - pauseW)/2;
const int pauseY = gameY + (gameH - uiFZ.h)*2/5;
const SDL_Rect titleDst = { titleX, titleY, titleW, uiFZ.h };
const SDL_Rect scoreLabelDst = { scoreLabelX, scoreY, scoreLabelW, uiFZ.h };
const SDL_Rect scoreDigitsDst = { scoreDigitsX, scoreY, scoreDigitsW, uiFZ.h };
const SDL_Rect copyrightDst = { copyrightX, copyrightY, copyrightW, uiFZ.h };
const SDL_Rect gameOverDst = { gameOverX, gameOverY, gameOverW, uiFZ.h };
const SDL_Rect pauseDst = { pauseX, pauseY, pauseW, uiFZ.h };
const SDL_Rect gameDst = { gameX, gameY, gameW, gameH };
// Load SDL resources
SDL_Surface *spritesSurface = loadThemeFile(themePath);
if (!spritesSurface) { exit(1); }
SDL_Surface *uiFontSurface = SDL_LoadBMP(XJUMP_FONTDIR "/font-ui.bmp");
if (!uiFontSurface) panic("Could not load font file", SDL_GetError());
SDL_Surface *hsFontSurface = SDL_LoadBMP(XJUMP_FONTDIR "/font-hs.bmp");
if (!hsFontSurface) panic("Could not load font file", SDL_GetError());