Contents

1. Introduction
2. The main loop
3. Locations
4. Objects
5. Inventory
6. Passages
7. Distance
8. North, east, south, west
9. Code generation
10. More attributes
11. Conditions
12. Open and close
13. The parser
14. Multiple nouns
15. Light and dark
16. Savegame
17. Test automation
18. Abbreviations
19. Conversations
20. Combat
21. Multi-player
22. Client-server
23. Database
24. Speech
25. JavaScript

How to program a text adventure in C

by Ruud Helderman <r.helderman@hccnet.nl>

Licensed under MIT License

16. Savegame

An adventure with any degree of difficulty should give the player the opportunity to save his progress, so he can resume the game at a later time.

Typically, adventure games simply save their state to a file on disk. Basically this means: write every (relevant) variable to a file, and read them back in again to resume the game. For reasons of portability and security, it would be wise to serialize the data.

For a traditional single-player adventure, an alternative would be for the game to log the player’s input. When the player wants to resume, do a ‘roll-forward’; starting from the initial game state, replay every command. Unusual as it may be, it brings along a few nice advantages.

Of course, this technique also comes with some challenges:

main.c
  1. #include <stdbool.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include "parsexec.h"
  5. static char input[100] = "look around";
  6. static bool getFromFP(FILE *fp)
  7. {
  8. bool ok = fgets(input, sizeof input, fp) != NULL;
  9. if (ok) input[strcspn(input, "\n")] = '\0';
  10. return ok;
  11. }
  12. static bool getInput(const char *filename)
  13. {
  14. static FILE *fp = NULL;
  15. bool ok;
  16. if (fp == NULL)
  17. {
  18. if (filename != NULL) fp = fopen(filename, "rt");
  19. if (fp == NULL) fp = stdin;
  20. }
  21. else if (fp == stdin && filename != NULL)
  22. {
  23. FILE *out = fopen(filename, "at");
  24. if (out != NULL)
  25. {
  26. fprintf(out, "%s\n", input);
  27. fclose(out);
  28. }
  29. }
  30. printf("\n--> ");
  31. ok = getFromFP(fp);
  32. if (fp != stdin)
  33. {
  34. if (ok)
  35. {
  36. printf("%s\n", input);
  37. }
  38. else
  39. {
  40. fclose(fp);
  41. ok = getFromFP(fp = stdin);
  42. }
  43. }
  44. return ok;
  45. }
  46. int main(int argc, char *argv[])
  47. {
  48. (void)argc;
  49. printf("Welcome to Little Cave Adventure.\n");
  50. while (parseAndExecute(input) && getInput(argv[1]));
  51. printf("\nBye!\n");
  52. return 0;
  53. }

Explanation:

And in case you hadn't noticed: this is the first time since chapter 2, that we are making changes to main.c!


⭳   Download source code 🌀   Run on Repl.it

Next chapter: 17. Test automation