Let's bring some basic interaction into our program!
The basic principle of a text adventure is simple:
This program, however short it may be, already responds to commands like look around, go north and quit. But of course, it is not much of a game. It has no locations, no items; all there is, is darkness. So in the next chapter, we will begin adding locations.
Sample output |
Welcome to Little Cave Adventure. It's very dark in here. --> look around It's too dark to see. --> go north It's too dark to go anywhere. --> eat sandwich I don't know how to 'eat'. --> quit Bye! |
main.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 | #include <stdio.h> #include <string.h> static char input[100]; static int getInput() { printf("\n--> "); return fgets(input, sizeof(input), stdin) != NULL; } static int parseAndExecute() { char *verb = strtok(input, " \n"); char *noun = strtok(NULL, " \n"); if (verb != NULL) { if (strcmp(verb, "quit") == 0) { return 0; } else if (strcmp(verb, "look") == 0) { printf("It's too dark to see.\n"); } else if (strcmp(verb, "go") == 0) { printf("It's too dark to go anywhere.\n"); } else { printf("I don't know how to '%s'.\n", verb); } } return 1; } int main() { printf("Welcome to Little Cave Adventure.\n"); printf("It's very dark in here.\n"); while (getInput() && parseAndExecute()); printf("\nBye!\n"); return 0; } |
Explanation:
Notice our program stops at nothing but a command from the player (either quit or end-of-file). So what about ‘game over’ situations, i.e. death and victory? Well, those are conditions that might end the game, but not necessarily end the program.
There is also a practical problem with terminating the program without the player's consent: in a windowing system, it is not unlikely for a text-based program to be running in an application window that immediately closes when the program ends, even before the player has had a chance to read the final message. We could delay this effect with “press any key to exit” or “wanna quit (y/n)”, but why bother when there is already a perfectly sane alternative? Just let the player type in ‘quit’ whenever he is ready to leave the imaginary world behind.
Naturally, all this is just an advice; you can take it or leave it. That's the great thing about writing an adventure in a general-purpose language: you can craft it any way you like.
Next chapter: 3. Locations