Files
tetris_clone/src/game/tetromino/placing.c

96 lines
2.6 KiB
C

#include "placing.h"
#include <stdint.h>
#include <string.h>
#include <sys/cdefs.h>
#include "../../io/audio.h"
#include "../../io/input.h"
#include "../../util/types.h"
#include "../../util/vec.h"
#include "../game.h"
#include "shapes.h"
static int clear_rows(u8* restrict* restrict rows) {
int count = 0;
u8* cache[4]; /* the maximum amount of rows the user can clear at once is four */
for (int y = ROWS - 1; y >= 0; y--) {
int x = 0;
while (x < COLUMNS && rows[y][x] && count < 4) x++;
if (x >= COLUMNS) cache[count++] = rows[y];
else rows[y + count] = rows[y];
}
if (count) {
for (int i = 0; i < count; i++) {
memset(cache[i], 0, COLUMNS);
rows[i] = cache[i];
}
}
return count;
}
/* writes a shape to the screen */
static void plcmnt_place(u8* restrict const* restrict row, u8 id, i8vec2 pos) {
u8 colour = colour_from_id(id);
i8vec2 bpos[4];
shape_getblocks(id, bpos);
bpos[0] += pos;
bpos[1] += pos;
bpos[2] += pos;
bpos[3] += pos;
row[bpos[0][VY]][bpos[0][VX]] = colour;
row[bpos[1][VY]][bpos[1][VX]] = colour;
row[bpos[2][VY]][bpos[2][VX]] = colour;
row[bpos[3][VY]][bpos[3][VX]] = colour;
}
static int plcmnt_valid(u8* restrict const* restrict const rows, i8vec2 pos) {
return pos[VX] >= 0 && pos[VX] < COLUMNS &&
pos[VY] >= 0 && pos[VY] < ROWS &&
!rows[pos[VY]][pos[VX]];
}
static int plcmnt_intersect(u8* restrict const* restrict const rows, u8 const id, i8vec2 pos) {
i8vec2 bpos[4];
shape_getblocks(id, bpos);
return !(plcmnt_valid(rows, pos + bpos[0]) &&
plcmnt_valid(rows, pos + bpos[1]) &&
plcmnt_valid(rows, pos + bpos[2]) &&
plcmnt_valid(rows, pos + bpos[3]));
}
int place_update(struct gamedata* gdat, int movdat) {
// store the current index and ID, only changes when placed (which yields no movement) and rotation (which occurs last)
int tmp;
u8 id = gdat->pdat.cur;
// update Y axis
tmp = !!(movdat & MOVD);
gdat->pdat.sel[VY] += tmp;
tmp = tmp && plcmnt_intersect(gdat->rows, id, gdat->pdat.sel);
if (tmp) {
gdat->pdat.sel[VY]--;
plcmnt_place(gdat->rows, id, gdat->pdat.sel);
gdat->pnts += clear_rows(gdat->rows) << 4; // clear the rows that have been completed
next_shape();
audio_play(AUDIO_ID_PLACE);
if (plcmnt_intersect(gdat->rows, gdat->pdat.cur, gdat->pdat.sel))
return 1;
}
// update X axis
tmp = !!(movdat & MOVR) - !!(movdat & MOVL);
gdat->pdat.sel[VX] += (tmp && !plcmnt_intersect(gdat->rows, id, (i8vec2){gdat->pdat.sel[VX] + tmp, gdat->pdat.sel[VY]})) * tmp;
// update roll
tmp = id ^ (((!!(movdat & MOVRR) - !!(movdat & MOVRL)) * 8 + id) & 31);
gdat->pdat.cur ^= (tmp && !plcmnt_intersect(gdat->rows, id ^ tmp, gdat->pdat.sel)) * tmp;
return 0;
}