diff --git a/01_text_adventure/game.c b/01_text_adventure/game.c index ed5ac9d..8c9d8b6 100644 --- a/01_text_adventure/game.c +++ b/01_text_adventure/game.c @@ -3,6 +3,7 @@ #include #include #include "game.h" +#include "transition.h" #include "input.h" #include "log.h" @@ -74,6 +75,22 @@ Command command_from_string(const char *string) { return COMMAND_UNKNOWN; } +#define INVALID_DIRECTIONAL_COMMAND "I can't go %s from here" +void game_handle_directional_command(Game *g, const char *c) { + Room *r = g->current_room; + Transition *transition = find_transition(g->transitions, r, command_from_string(c)); + + if (transition) { + push_line_to_log(g->input->log, transition->description); + g->current_room = transition->to; + } else { + char *response = malloc(strlen(INVALID_DIRECTIONAL_COMMAND) + strlen(c) + 1); + sprintf(response, INVALID_DIRECTIONAL_COMMAND, c); + push_line_to_log(g->input->log, response); + free(response); + } +} + #define INVALID_COMMAND "I don't know how to " void game_handle_command(Game *g, const char *command) { Input *input = g->input; @@ -85,6 +102,12 @@ void game_handle_command(Game *g, const char *command) { case COMMAND_LOOK: push_line_to_log(input->log, g->current_room->description); break; + case COMMAND_NORTH: + case COMMAND_SOUTH: + case COMMAND_EAST: + case COMMAND_WEST: + game_handle_directional_command(g, command); + break; default: char *response = malloc(strlen(INVALID_COMMAND) + strlen(command) + 1); sprintf(response, INVALID_COMMAND "%s", command); diff --git a/01_text_adventure/main.c b/01_text_adventure/main.c index d037e9a..618899d 100644 --- a/01_text_adventure/main.c +++ b/01_text_adventure/main.c @@ -15,6 +15,7 @@ int main(void) { Game *g = game_create(); game_load_rooms(g); + game_load_transitions(g); game_run_until_close(g); CloseWindow(); diff --git a/01_text_adventure/transition.c b/01_text_adventure/transition.c index 3508aff..9656666 100644 --- a/01_text_adventure/transition.c +++ b/01_text_adventure/transition.c @@ -30,3 +30,12 @@ void game_load_transitions(Game *g) { fclose(transitions_file); } + +Transition *find_transition(Transitions *t, Room *from, Command via) { + for (int i = 0; i < t->count; i++) { + Transition *candidate = &t->transitions[i]; + if (candidate->from == from && candidate->via == via) return candidate; + } + + return NULL; +} diff --git a/01_text_adventure/transition.h b/01_text_adventure/transition.h index 9955c5b..f92d5f0 100644 --- a/01_text_adventure/transition.h +++ b/01_text_adventure/transition.h @@ -20,5 +20,6 @@ struct Transitions { }; void game_load_transitions(Game *g); +Transition *find_transition(Transitions *t, Room *from, Command via); #endif