summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFrederick Yin <fkfd@fkfd.me>2022-05-31 19:29:57 +0800
committerFrederick Yin <fkfd@fkfd.me>2022-05-31 19:29:57 +0800
commit137de73dd908602b3879d29abd67ee96007cf2ee (patch)
treeb982874a86c2ebefd03a5208b9133bb30352cea6
parent5b9a799146f25dd23d108b01abed72dc50556076 (diff)
Circulate pieces at hand, game over calculation
-rw-r--r--sirtet.c54
1 files changed, 46 insertions, 8 deletions
diff --git a/sirtet.c b/sirtet.c
index 94ca5a1..b09c316 100644
--- a/sirtet.c
+++ b/sirtet.c
@@ -26,6 +26,9 @@ void printmap(char** map, int nrow, int ncol) {
void printpieces(struct piece** hand, int nhand) {
for (int i = 0; i < nhand; i++) {
+ if (hand[i] == NULL)
+ continue;
+
printf("Piece %d\n", i);
struct piece* pc = hand[i];
for (int r = 0; r < pc->h; r++) {
@@ -71,11 +74,9 @@ void place(char** map, struct piece* pc, int row, int col) {
}
}
-void freepieces(struct piece** hand, int nhand) {
- for (int i = 0; i < nhand; i++) {
- free(hand[i]->blocks);
- free(hand[i]);
- }
+void freepiece(struct piece* pc) {
+ free(pc->blocks);
+ free(pc);
}
void refillpieces(struct piece** hand, int nhand) {
@@ -97,7 +98,6 @@ void sirtet() {
map[r] = malloc(W * sizeof(char));
}
struct piece** hand = malloc(P * sizeof(struct piece*));
- int pieces_left = P;
srand(time(NULL));
clearmap(map, H, W);
@@ -114,19 +114,57 @@ void sirtet() {
int col;
printf("Input [piece #] [row #] [col #]: ");
scanf("%d %d %d", &pc_idx, &row, &col);
- while (pc_idx < 0 || pc_idx >= P || !placeable(map, hand[pc_idx], row, col, H, W)) {
+ while (
+ pc_idx < 0 || pc_idx >= P || hand[pc_idx] == NULL ||
+ !placeable(map, hand[pc_idx], row, col, H, W)
+ ) {
printf("You cannot do that. Try again: ");
scanf("%d %d %d", &pc_idx, &row, &col);
}
place(map, hand[pc_idx], row, col);
+ freepiece(hand[pc_idx]);
+ hand[pc_idx] = NULL;
+
+ // if player has no piece left, refill
+ bool pieces_left = false;
+ for (int i = 0; i < P; i++) {
+ if (hand[i] != NULL) {
+ pieces_left = true;
+ break;
+ }
+ }
+ if (!pieces_left)
+ refillpieces(hand, P);
+
+ // game over if none of the pieces are placeable
+ bool has_placeable = false;
+ for (int i = 0; i < P; i++) {
+ if (hand[i] == NULL)
+ continue;
+
+ for (int r = 0; r <= H - hand[i]->h; r++) {
+ for (int c = 0; c <= W - hand[i]->w; c++) {
+ if (placeable(map, hand[i], r, c, H, W))
+ has_placeable = true;
+ }
+ }
+ }
+ if (!has_placeable) {
+ // game over
+ printf("Game over\n");
+ over = true;
+ }
}
// free memory
- freepieces(hand, P);
for (int r = 0; r < H; r++) {
free(map[r]);
}
free(map);
+ for (int i = 0; i < P; i++) {
+ if (hand[i] != NULL)
+ freepiece(hand[i]);
+ }
free(hand);
}