commit eb62c95a9b3fe3e9c35fe27bdc5996b391ffff5a
parent 5b57a73784bc434851d1f4a3a3aed7436fd12567
Author: Matsuda Kenji <info@mtkn.jp>
Date: Thu, 5 Jan 2023 19:23:57 +0900
make collision handler an array of function pointers
Diffstat:
3 files changed, 21 insertions(+), 9 deletions(-)
diff --git a/ex9/main.c b/ex9/main.c
@@ -46,7 +46,8 @@ enum next_menu {
struct Object *player;
int player_is_falling;
enum next_menu next_menu = START_MENU;
-
+void (* col_func[NUM_OBJ_TYPE][NUM_OBJ_TYPE])(struct Object *,
+ struct Object *);
/* function prototypes */
/* menus */
@@ -114,14 +115,19 @@ start_menu(void)
}
}
-/*
- * this function should be moved to other file
- */
-void handle_collision_pf(struct Object *o0, struct Object *o1) {
+void col_pf(struct Object *o0, struct Object *o1) {
handle_collision_mf(o0, o1);
next_menu = GAME_CLEAR;
}
+void col_pb(struct Object *op, struct Object *ob) {
+ if (op->type != TPLAYER || ob->type != TBLOCK) {
+ fprintf(stderr, "col_pb: invalid object type\n");
+ return;
+ }
+ handle_collision_mf(op, ob);
+}
+
void
game_play(void)
{
@@ -136,8 +142,6 @@ game_play(void)
struct OH *flh; // flag
struct OL *flc;
int scroll_dst = 0;
- void (* col_func[NUM_OBJ_TYPE][NUM_OBJ_TYPE])(struct Object *,
- struct Object *);
for (int xi = 0; xi < WORLD_WIDTH; xi++)
@@ -147,7 +151,8 @@ game_play(void)
for (int i = 0; i < NUM_OBJ_TYPE; i++)
for (int j = 0; j < NUM_OBJ_TYPE; j++)
col_func[i][j] = &handle_collision_mf;
- col_func[TPLAYER][TFLAG] = col_func[TFLAG][TPLAYER] = &handle_collision_pf;
+ col_func[TPLAYER][TFLAG] = col_func[TFLAG][TPLAYER] = &col_pf;
+ col_func[TPLAYER][TBLOCK] = col_func[TFLAG][TPLAYER] = &col_pb;
for (int i = 0; i < WORLD_WIDTH * WORLD_HEIGHT; i++) {
if (world_map[i] == 'b') {
@@ -230,7 +235,7 @@ game_play(void)
if (collidings->first != NULL) {
sort_ol(collidings, player);
for (blc = collidings->first; blc != NULL; blc = blc->next) {
- handle_collision_mf(player, blc->o);
+ handle_collision(player, blc->o);
}
}
free_ol(collidings);
diff --git a/ex9/main.h b/ex9/main.h
@@ -63,6 +63,9 @@ struct OL {
struct OL *next;
};
+extern void (* col_func[NUM_OBJ_TYPE][NUM_OBJ_TYPE])(struct Object *, struct Object *);
+
+void handle_collision(struct Object *, struct Object *);
struct OH *create_ol(void);
void free_ol(struct OH *);
void free_obj_and_ol(struct OH *);
diff --git a/ex9/util.c b/ex9/util.c
@@ -260,3 +260,7 @@ is_on_floor_before(struct Object *player, struct Object *floor)
int col = test_collision(&o, floor);
return col;
}
+
+void handle_collision(struct Object *o0, struct Object *o1) {
+ (* col_func[o0->type][o1->type])(o0, o1);
+}