-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtetris.c
725 lines (617 loc) · 16 KB
/
tetris.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
#include "tetris.h"
///// DEFINITIONS /////
// milliseconds, roughly
int const FRAME_TIME = 10;
// color of dead tetrominos in the grid
bgr const DEAD_COLOR = BGR(128, 128, 128);
// color of the player's tetromino
bgr const TETRO_COLOR = BGR(192, 96, 96);
// color of the boundary around the playfield
bgr const BOUNDARY_COLOR = BGR(192, 192, 192);
// dimensions of the tiles
INT32 const TILE_WIDTH = 16, TILE_HEIGHT = 16;
// empty tile and nonempty tile
tile const EMPTY = 0, NONEMPTY = 1;
///// LOGIC /////
UINT32 tick_period(game_state const * const s) {
return s->level >= LEVEL_MAX ? 1 : s->levels[s->level];
}
/**
* \brief
* Converts a grid-local position to an absolute screen position.
*/
vec2 grid_local_to_absolute(game_state const * const s, vec2 p) {
return (vec2) {
s->grid_origin.x + s->tile_size.x * p.x,
s->grid_origin.y + s->tile_size.y * p.y
};
}
/**
* \brief
* Converts an index into the grid array into a grid-local tile
* coordinate.
*
* This is the inverse of `tile_index`.
*/
vec2 grid_index_to_grid_local(vec2 grid_size, int i) {
return (vec2) { .x = i % grid_size.x, .y = i / grid_size.x };
}
/**
* \brief
* Converts a grid-local tile coordinate into a grid array index.
*
* This is the inverse of `grid_index_to_grid_local`.
*/
int tile_index(vec2 grid_size, vec2 p) {
return p.x + p.y * grid_size.x;
}
/**
* \brief
* Reads tile data from the grid at the given position.
*/
tile get_tile(game_state const * const s, vec2 p) {
return s->grid[tile_index(s->grid_size, p)];
}
/**
* \brief
* Obtains a reference to a tile in the grid at a given position.
*/
tile * ref_tile(game_state * const s, vec2 p) {
return &s->grid[tile_index(s->grid_size, p)];
}
/**
* \brief
* Decides whether the given point is in the grid's bounds.
*/
int grid_bounds_check(game_state const * const s, vec2 p) {
return 0 <= p.x && p.x < s->grid_size.x
&& 0 <= p.y && p.y < s->grid_size.y;
}
/**
* \brief
* Decides whether the given tetromino is valid in the game state, i.e.
* it is not out-of-bounds and does not overlap with any dead blocks.
*/
int is_tetromino_valid(game_state const * const s) {
//
for(int i = 0; i < TETROMINO_GRID_LENGTH; i++) {
// skip empty blocks
if(!s->current_tetromino.template->data[i])
continue;
// convert to grid coordinates and check if the grid cell is
// nonempty
vec2 p = tetro_index_to_tetro_local(i);
vec2 q = tetro_local_to_grid_local(&s->current_tetromino, p);
// check if out of bounds
if(!grid_bounds_check(s, q))
return 0;
if(get_tile(s, q))
// the tile is true => there is a dead block here, and we're
// overlapping it
return 0;
}
return 1;
}
/**
* \brief
* Gets the next tetromino.
* Should be called after the player's tetromino has fallen and been frozen.
*
* Copies the tetromino referred to by `next_tetromino` into
* `current_tetromino` and pumps the PRNG to get a new value for
* `next_tetromino`.
*/
void next_tetromino(game_state * const s) {
// get a random index
UINT32 i = next_uint32(s->rng) % TETROMINO_COUNT;
s->current_tetromino = (tetromino) {
.template = s->next_tetromino,
.rotation = ZERO_ROTATION,
.position = (vec2) { .x = 4, .y = 0 }
};
s->next_tetromino = TETROMINOES[i];
Print(L"DEBUG: next tetromino is %d\n", i);
}
game_state
make_initial_state(
int * const ok,
LFB * const lfb,
RNG * const rng,
input_manager_t * const input_manager) {
//
int _ok;
game_state s = {
.lfb = lfb,
.rng = rng,
.timer = make_timer(&_ok, FRAME_TIME),
.next_tetromino = &tetro_l,
.frame_number = 0,
.tile_size = (vec2) { .x = TILE_WIDTH, .y = TILE_HEIGHT },
.grid_size = (vec2) { .x = GRID_WIDTH, .y = GRID_HEIGHT },
// center the grid
.grid_origin = (vec2) {
.x = lfb->width / 2 - GRID_WIDTH * TILE_WIDTH / 2,
.y = lfb->height / 2 - GRID_HEIGHT * TILE_HEIGHT / 2
},
.last_tick = 0,
.eliminated_rows = 0,
.input_manager = input_manager,
.score_table = {
0, // no rows cleared -> no points added
SCORE_1, // see config.h
SCORE_2,
SCORE_3,
SCORE_4
},
.level = 0,
.levels = {
90, 80, 70, 60, 50,
45, 40, 35, 30, 25,
20, 18, 16, 14, 12,
10, 8, 5, 3, 2
},
.renderer_info = {
.text_scale = 1,
.color = WHITE,
.char_skip = 1,
.font = &default_font
}
};
Print(
L"DEBUG: grid origin is (0, 0)\n",
s.grid_origin.x,
s.grid_origin.y);
if(!_ok) {
*ok = _ok;
return s;
}
for(int i = 0; i < s.grid_size.x * s.grid_size.y; i++) {
s.grid[i] = EMPTY;
}
*ok = 1;
// skip the first two (bogus / default) values for the tetrominoes
next_tetromino(&s);
next_tetromino(&s);
return s;
}
/**
* \brief
* Freezes the player's tetromino into the grid.
*/
void freeze_tetromino(game_state * const s) {
for(UINT8 i = 0; i < TETROMINO_GRID_LENGTH; i++) {
// skip if there's no block at that index
if(!s->current_tetromino.template->data[i])
continue;
// otherwise, figure out what position in the grid that's supposed to be
vec2 p = tetro_index_to_tetro_local(i);
vec2 q = tetro_local_to_grid_local(&s->current_tetromino, p);
// q is a valid position into the grid
*ref_tile(s, q) = NONEMPTY;
}
}
/**
* \brief
* Freezes the current tetromino, spawns a new one, and checks for
* gameover.
*
* \returns
* - `0` if the game is over.
* - `1` if the game continues.
*/
int freeze_and_next_tetromino(game_state * const s) {
freeze_tetromino(s);
// if right after spawning the next tetromino, it is invalid, then
// we've hit gameover
next_tetromino(s);
return is_tetromino_valid(s);
}
/**
* \brief
* Moves the tetromino down, checking for collisions and freezing it
* if necessary.
*
* This function also detects the game over condition, and returns
* false if the game is over.
*/
int tick(game_state * const s) {
Print(L"DEBUG: tick!\n");
s->current_tetromino.position.y++;
if(!is_tetromino_valid(s)) {
Print(L"DEBUG: tetromino invalid; freezing and getting next\n");
s->current_tetromino.position.y--;
if(!freeze_and_next_tetromino(s))
return 0;
}
s->last_tick = s->frame_number;
return 1;
}
int should_tick(game_state * const s) {
return s->frame_number - s->last_tick >= tick_period(s);
}
/**
* \brief
* Removes row `y` from the grid, shifting earlier rows down.
*/
void eliminate_row(game_state * const s, int y) {
while(y --> 0) {
for(int x = 0; x < s->grid_size.x; x++) {
tile *src = ref_tile(s, (vec2) { x, y }),
*dst = ref_tile(s, (vec2) {x, y + 1});
*dst = *src;
}
}
}
void update_level(game_state * const s) {
s->level = s->eliminated_rows / LEVEL_BOUNDARY;
if(s->level >= LEVEL_MAX)
s->level = LEVEL_MAX;
}
void check_full_rows(game_state * const s) {
Print(L"DEBUG: check_full_rows\n");
int eliminated_rows = 0;
for(int y = 0; y < s->grid_size.y; y++) {
int ok = 1;
for(int x = 0; x < s->grid_size.x; x++) {
if(!get_tile(s, (vec2) { x, y })) {
ok = 0;
break;
}
}
if(!ok)
continue;
eliminated_rows++;
eliminate_row(s, y);
}
s->eliminated_rows += eliminated_rows;
s->score += s->score_table[eliminated_rows];
}
int on_move_left(game_state * const s) {
s->current_tetromino.position.x--;
if(!is_tetromino_valid(s))
s->current_tetromino.position.x++;
return 1;
}
int on_move_right(game_state * const s) {
s->current_tetromino.position.x++;
if(!is_tetromino_valid(s))
s->current_tetromino.position.x--;
return 1;
}
int on_rotate_ccw(game_state * const s) {
rotation r = s->current_tetromino.rotation;
s->current_tetromino.rotation = rot_inc(s->current_tetromino.rotation);
if(!is_tetromino_valid(s))
s->current_tetromino.rotation = r;
return 1;
}
int on_rotate_cw(game_state * const s) {
rotation r = s->current_tetromino.rotation;
s->current_tetromino.rotation = rot_dec(s->current_tetromino.rotation);
if(!is_tetromino_valid(s))
s->current_tetromino.rotation = r;
return 1;
}
int on_fall(game_state * const s) {
while(is_tetromino_valid(s)) {
s->current_tetromino.position.y++;
}
s->current_tetromino.position.y--;
if(!freeze_and_next_tetromino(s))
return 0;
check_full_rows(s);
return 1;
}
int on_quit(game_state * const s) {
return 0;
}
int on_unknown(game_state * const s) {
return 1;
}
/**
* \brief
* Type of a function that handles an input key.
*
* The returned integer indicates whether the game continues:
* - `0` indicates the game is over.
* - `1` indicates the game continues.
*/
typedef int (*input_handler)(game_state * const s);
/**
* \brief
* Table of function pointers that handle the input keys, precisely in
* the enum order of `INPUT_KEY`, so we can use the enum values as
* indices.
*/
input_handler input_handlers[INPUT_KEY_MAX] = {
// conveniently, tick has the right type for an input handler,
// so we use it directly to handle the down input
tick,
on_move_left,
on_move_right,
on_rotate_cw,
on_rotate_ccw,
on_fall,
on_quit,
on_unknown
};
int handle_input(game_state * const s, int * const redraw) {
INPUT_KEY key;
READ_INPUT_KEY_STATUS status;
// keep processing inputs until we run out or hit an error
// for each input, invoke its appropriate handler and eager-exit if
// it indicates game over.
while(INPUT_KEY_SUCCESS == (status = read_input_key(s->input_manager, &key))) {
Print(L"DEBUG: handling input %d\n", key);
if(!input_handlers[key](s)) {
Print(L"DEBUG: handle_input gameover detected\n");
return 0;
}
else
*redraw = 1;
}
if(status == INPUT_KEY_ERROR) {
Print(L"ERROR: failed to read input\n");
return 0;
}
return 1;
}
int update(game_state * const s, int * const redraw) {
s->frame_number++;
if(!handle_input(s, redraw))
return 0;
if(should_tick(s)) {
if(!tick(s))
return 0;
check_full_rows(s);
*redraw = 1;
}
update_level(s);
return 1;
}
///// DRAWING /////
/**
* \brief
* Draws a string at the specified location using the settings of the
* game_state.
*/
void draw_string(
game_state * const s,
vec2 const pos,
char const * const str,
UINT32 length) {
//
Print(L"DEBUG: drawing string\n", str);
bt_render_string(
s->lfb,
&s->renderer_info,
pos,
str,
length);
}
/**
* \brief
* Draws a string centered at the given position.
*/
void draw_string_centered(
game_state * const s,
vec2 const pos,
char const * const str,
UINT32 length) {
Print(L"DEBUG: drawing centered string\n");
bt_render_string_centered(
s->lfb,
&s->renderer_info,
pos,
str,
length);
}
/**
* \brief
* Draws a tile at grid-local position `pos` with the given color.
*/
void draw_tile(game_state * const s, vec2 pos, bgr color) {
// convert grid-local position to screen position
pos = grid_local_to_absolute(s, pos);
// pos = (vec2) { pos.x * s->tile_size.x, pos.y * s->tile_size.y };
// upgrade to rectangle
rect r = { pos.x, pos.y, s->tile_size.x, s->tile_size.y };
// fill the rectangle on screen
fill_rect(
s->lfb,
r,
color);
}
void draw_boundary(game_state * const s) {
for(int y = 0; y < s->grid_size.y; y++) {
draw_tile(s, (vec2) { .x = -1, .y = y }, BOUNDARY_COLOR);
draw_tile(s, (vec2) { .x = s->grid_size.x, .y = y }, BOUNDARY_COLOR);
}
for(int x = -1; x < s->grid_size.x + 1; x++) {
draw_tile(s, (vec2) { .x = x, .y = s->grid_size.y }, BOUNDARY_COLOR);
}
}
/**
* \brief
* Draws the given tetromino.
*
* The flag `black` controls whether the absent elements of the
* tetromino are drawn as black tiles.
*/
void draw_tetromino(game_state * const s, tetromino const * const t, int black) {
Print(L"DEBUG: drawing tetromino\n");
for(UINT8 i = 0; i < TETROMINO_GRID_LENGTH; i++) {
int has = t->template->data[i];
if(!has && !black) {
// Print(L"DEBUG: skipping component %d\n", i);
continue;
}
else {
// Print(L"DEBUG: drawing component %d\n", i);
}
vec2 p = tetro_index_to_tetro_local(i);
// Print(
// L"DEBUG: converted index %d to local position (%d, %d)\n",
// i,
// p.x,
// p.y);
vec2 q = tetro_local_to_grid_local(t, p);
// Print(
// L"DEBUG: converted local position (%d, %d) to grid position (%d, %d)\n",
// p.x,
// p.y,
// q.x,
// q.y);
draw_tile(
s,
q,
has ? TETRO_COLOR : BLACK);
}
}
void draw_dead_tiles(game_state * const s) {
for(int i = 0; i < s->grid_size.x; i++) {
for(int j = 0; j < s->grid_size.y; j++) {
vec2 const p = { i, j };
draw_tile(
s,
p,
get_tile(s, p) == EMPTY ? BLACK : DEAD_COLOR);
}
}
}
static char const text_next[] = "next",
text_score[] = "score",
text_cleared[] = "cleared",
text_controls[] = "controls",
text_move_help[] = "move: arrow keys",
text_rotate_help[] = "rotate: z and x",
text_fall_help[] = "fall: down and space",
text_quit_help[] = "quit: q";
typedef struct help_text {
UINT32 size;
char const * const text;
} help_text;
static help_text const help_entries[] = {
{ .text = text_controls, .size = sizeof(text_controls) },
{ .text = text_move_help, .size = sizeof(text_move_help) },
{ .text = text_rotate_help, .size = sizeof(text_rotate_help) },
{ .text = text_fall_help, .size = sizeof(text_fall_help) },
{ .text = text_quit_help, .size = sizeof(text_quit_help) }
};
/**
* \brief
* Draws the things that never change:
* - text (besides score value)
* - grid boundary
*/
void draw_static(game_state * const s) {
static char const pangram[] =
"tetrefis";
draw_string_centered(
s,
(vec2) { s->lfb->width / 2, 50 },
pangram,
sizeof(pangram));
draw_boundary(s);
vec2 const p1 = { s->grid_size.x + 4, -1 };
draw_string(
s,
grid_local_to_absolute(s, p1),
text_next,
sizeof(text_next));
vec2 const p2 = { s->grid_size.x + 4, 4 };
draw_string(
s,
grid_local_to_absolute(s, p2),
text_score,
sizeof(text_score));
vec2 const p3 = { s->grid_size.x + 4, 7 };
draw_string(
s,
grid_local_to_absolute(s, p3),
text_cleared,
sizeof(text_cleared));
INT32 y = 300;
INT32 y_space = 20;
INT32 const x = 50;
for(int i = 0; i < sizeof(help_entries) / sizeof(help_entries[0]); i++) {
draw_string(
s,
(vec2) { x, y },
help_entries[i].text,
help_entries[i].size);
y += y_space;
}
}
void draw(game_state * const s) {
// used to draw the next tetromino
static tetromino t = {
.template = NULL,
.position = (vec2) { .x = 0, .y = 0 },
.rotation = ZERO_ROTATION
};
// clear the screen buffer to black
// screen_buffer_clear(s->lfb, BLACK);
// do all draws to the buffer
draw_dead_tiles(s);
draw_tetromino(s, &s->current_tetromino, 0);
t.position.x = s->grid_size.x + 4;
t.template = s->next_tetromino;
draw_tetromino(s, &t, 1);
{
char text_score_value[] = "000000000";
uint32_to_str(
s->score,
text_score_value,
sizeof(text_score_value) - 1);
vec2 p =
grid_local_to_absolute(
s,
(vec2) { s->grid_size.x + 4, 5 });
fill_rect(
s->lfb,
(rect) { p.x, p.y - 11, 57, 12 },
BLACK);
draw_string(
s,
p,
text_score_value,
sizeof(text_score_value));
}
{
char text_lines_value[] = "00000";
uint32_to_str(
s->eliminated_rows,
text_lines_value,
sizeof(text_lines_value) - 1);
vec2 p =
grid_local_to_absolute(
s,
(vec2) { s->grid_size.x + 4, 8 });
fill_rect(
s->lfb,
(rect) { p.x, p.y - 11, 32, 12 },
BLACK);
draw_string(
s,
p,
text_lines_value,
sizeof(text_lines_value));
}
// copy the buffer to the vram
screen_buffer_copy(s->lfb);
}
///// MAIN LOOP /////
int game(game_state * const s) {
int ok = 1, redraw = 0;
// draw the static screen elements before the loop to avoid checking
// whether we did it already
draw_static(s);
while(ok) {
ok = update(s, &redraw);
if(redraw)
draw(s);
await_timer(&s->timer);
}
return 1;
}