1TBS reflow with clang-format.

This commit is contained in:
Eric S. Raymond 2024-01-27 06:17:02 -05:00
parent c11938aed5
commit be429016af
9 changed files with 4137 additions and 3936 deletions

View file

@ -68,6 +68,9 @@ cheat: $(CHEAT_OBJS) dungeon.o
check: advent cheat check: advent cheat
cd tests; $(MAKE) --quiet cd tests; $(MAKE) --quiet
reflow:
@clang-format --style="{IndentWidth: 8, UseTab: ForIndentation}" -i $$(find . -name "*.[ch]")
# Requires gcov, lcov, libasan6, and libubsan1 # Requires gcov, lcov, libasan6, and libubsan1
# The last two are Ubuntu names, might vary on other distributions. # The last two are Ubuntu names, might vary on other distributions.
# After this, run your browser on coverage/open-adventure/index.html # After this, run your browser on coverage/open-adventure/index.html

2920
actions.c

File diff suppressed because it is too large Load diff

393
advent.h
View file

@ -4,11 +4,11 @@
* SPDX-FileCopyrightText: (C) 1977, 2005 by Will Crowther and Don Woods * SPDX-FileCopyrightText: (C) 1977, 2005 by Will Crowther and Don Woods
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <inttypes.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdbool.h>
#include <stdarg.h>
#include <inttypes.h>
#include "dungeon.h" #include "dungeon.h"
@ -18,29 +18,30 @@
#define LCG_C 221587L #define LCG_C 221587L
#define LCG_M 1048576L #define LCG_M 1048576L
#define LINESIZE 1024 #define LINESIZE 1024
#define TOKLEN 5 // # outputting characters in a token */ #define TOKLEN 5 // # outputting characters in a token */
#define PIRATE NDWARVES // must be NDWARVES-1 when zero-origin #define PIRATE NDWARVES // must be NDWARVES-1 when zero-origin
#define DALTLC LOC_NUGGET // alternate dwarf location #define DALTLC LOC_NUGGET // alternate dwarf location
#define INVLIMIT 7 // inventory limit (# of objects) #define INVLIMIT 7 // inventory limit (# of objects)
#define INTRANSITIVE -1 // illegal object number #define INTRANSITIVE -1 // illegal object number
#define GAMELIMIT 330 // base limit of turns #define GAMELIMIT 330 // base limit of turns
#define NOVICELIMIT 1000 // limit of turns for novice #define NOVICELIMIT 1000 // limit of turns for novice
#define WARNTIME 30 // late game starts at game.limit-this #define WARNTIME 30 // late game starts at game.limit-this
#define FLASHTIME 50 // turns from first warning till blinding flash #define FLASHTIME 50 // turns from first warning till blinding flash
#define PANICTIME 15 // time left after closing #define PANICTIME 15 // time left after closing
#define BATTERYLIFE 2500 // turn limit increment from batteries #define BATTERYLIFE 2500 // turn limit increment from batteries
#define WORD_NOT_FOUND -1 // "Word not found" flag value for the vocab hash functions. #define WORD_NOT_FOUND \
#define WORD_EMPTY 0 // "Word empty" flag value for the vocab hash functions -1 // "Word not found" flag value for the vocab hash functions.
#define PIT_KILL_PROB 35 // Percentage probability of dying from fall in pit. #define WORD_EMPTY 0 // "Word empty" flag value for the vocab hash functions
#define CARRIED -1 // Player is toting it #define PIT_KILL_PROB 35 // Percentage probability of dying from fall in pit.
#define READ_MODE "rb" // b is not needed for POSIX but harmless #define CARRIED -1 // Player is toting it
#define WRITE_MODE "wb" // b is not needed for POSIX but harmless #define READ_MODE "rb" // b is not needed for POSIX but harmless
#define WRITE_MODE "wb" // b is not needed for POSIX but harmless
/* Special object-state values - integers > 0 are object-specific */ /* Special object-state values - integers > 0 are object-specific */
#define STATE_NOTFOUND -1 // 'Not found" state of treasures #define STATE_NOTFOUND -1 // 'Not found" state of treasures
#define STATE_FOUND 0 // After discovered, before messed with #define STATE_FOUND 0 // After discovered, before messed with
#define STATE_IN_CAVITY 1 // State value common to all gemstones #define STATE_IN_CAVITY 1 // State value common to all gemstones
/* Special fixed object-state values - integers > 0 are location */ /* Special fixed object-state values - integers > 0 are location */
#define IS_FIXED -1 #define IS_FIXED -1
@ -67,39 +68,45 @@
* and readable objects, notably the clam/oyster - but the code around * and readable objects, notably the clam/oyster - but the code around
* those test is difficult to read. * those test is difficult to read.
*/ */
#define PROP_STASHIFY(n) (-1 - (n)) #define PROP_STASHIFY(n) (-1 - (n))
#define PROP_IS_STASHED(obj) (game.objects[obj].prop < STATE_NOTFOUND) #define PROP_IS_STASHED(obj) (game.objects[obj].prop < STATE_NOTFOUND)
#define PROP_IS_NOTFOUND(obj) (game.objects[obj].prop == STATE_NOTFOUND) #define PROP_IS_NOTFOUND(obj) (game.objects[obj].prop == STATE_NOTFOUND)
#define PROP_IS_FOUND(obj) (game.objects[obj].prop == STATE_FOUND) #define PROP_IS_FOUND(obj) (game.objects[obj].prop == STATE_FOUND)
#define PROP_IS_STASHED_OR_UNSEEN(obj) (game.objects[obj].prop < 0) #define PROP_IS_STASHED_OR_UNSEEN(obj) (game.objects[obj].prop < 0)
#define PROP_SET_FOUND(obj) (game.objects[obj].prop = STATE_FOUND) #define PROP_SET_FOUND(obj) (game.objects[obj].prop = STATE_FOUND)
#define PROP_SET_NOT_FOUND(obj) (game.objects[obj].prop = STATE_NOTFOUND) #define PROP_SET_NOT_FOUND(obj) (game.objects[obj].prop = STATE_NOTFOUND)
#define PROP_IS_NOTFOUND2(g, o) (g.objects[o].prop == STATE_NOTFOUND) #define PROP_IS_NOTFOUND2(g, o) (g.objects[o].prop == STATE_NOTFOUND)
#define PROP_IS_INVALID(val) (val < -MAX_STATE - 1 || val > MAX_STATE) #define PROP_IS_INVALID(val) (val < -MAX_STATE - 1 || val > MAX_STATE)
#else #else
/* (ESR) Only the boldest of adventurers will explore here. This /* (ESR) Only the boldest of adventurers will explore here. This
* alternate set of definitions for the macros above was an attempt to * alternate set of definitions for the macros above was an attempt to
* break from out of the state encoding a per-object "found" member * break from out of the state encoding a per-object "found" member
* telling whether or not the player has seen the object. * telling whether or not the player has seen the object.
* *
* What's broken when you try to use thus is * What's broken when you try to use thus is
* PROP_IS_STASHED_OR_UNSEEN. The symptom is game.tally getting * PROP_IS_STASHED_OR_UNSEEN. The symptom is game.tally getting
* decremented on non-treasures. * decremented on non-treasures.
*/ */
#define PROP_STASHIFY(n) (-(n)) #define PROP_STASHIFY(n) (-(n))
#define PROP_IS_STASHED(obj) (game.objects[obj].prop < 0) #define PROP_IS_STASHED(obj) (game.objects[obj].prop < 0)
#define PROP_IS_NOTFOUND(obj) (!game.objects[obj].found) #define PROP_IS_NOTFOUND(obj) (!game.objects[obj].found)
#define PROP_IS_FOUND(obj) (game.objects[obj].found && game.objects[obj].prop == 0) #define PROP_IS_FOUND(obj) \
#define PROP_IS_STASHED_OR_UNSEEN(obj) (!game.objects[obj].found || game.objects[obj].prop < 0) (game.objects[obj].found && game.objects[obj].prop == 0)
#define PROP_SET_FOUND(obj) do {game.objects[obj].found = true; game.objects[obj].prop = STATE_FOUND;} while(0) #define PROP_IS_STASHED_OR_UNSEEN(obj) \
#define PROP_SET_NOT_FOUND(obj) game.objects[obj].found = false (!game.objects[obj].found || game.objects[obj].prop < 0)
#define PROP_IS_NOTFOUND2(g, o) (!g.objects[o].found) #define PROP_SET_FOUND(obj) \
#define PROP_IS_INVALID(val) (val < -MAX_STATE || val > MAX_STATE) do { \
#define PROP_SET_SEEN(obj) game.objects[object].found = true game.objects[obj].found = true; \
game.objects[obj].prop = STATE_FOUND; \
} while (0)
#define PROP_SET_NOT_FOUND(obj) game.objects[obj].found = false
#define PROP_IS_NOTFOUND2(g, o) (!g.objects[o].found)
#define PROP_IS_INVALID(val) (val < -MAX_STATE || val > MAX_STATE)
#define PROP_SET_SEEN(obj) game.objects[object].found = true
#endif #endif
#define PROP_STASHED(obj) PROP_STASHIFY(game.objects[obj].prop) #define PROP_STASHED(obj) PROP_STASHIFY(game.objects[obj].prop)
#define PROMPT "> " #define PROMPT "> "
/* /*
* DESTROY(N) = Get rid of an item by putting it in LOC_NOWHERE * DESTROY(N) = Get rid of an item by putting it in LOC_NOWHERE
@ -116,62 +123,72 @@
* GSTONE(OBJ) = true if OBJ is a gemstone * GSTONE(OBJ) = true if OBJ is a gemstone
* FOREST(LOC) = true if LOC is part of the forest * FOREST(LOC) = true if LOC is part of the forest
* OUTSID(LOC) = true if location not in the cave * OUTSID(LOC) = true if location not in the cave
* INSIDE(LOC) = true if location is in the cave or the building at the beginning of the game * INSIDE(LOC) = true if location is in the cave or the building at the
* INDEEP(LOC) = true if location is in the Hall of Mists or deeper * beginning of the game INDEEP(LOC) = true if location is in the Hall of Mists
* BUG(X) = report bug and exit * or deeper BUG(X) = report bug and exit
*/ */
#define DESTROY(N) move(N, LOC_NOWHERE) #define DESTROY(N) move(N, LOC_NOWHERE)
#define MOD(N,M) ((N) % (M)) #define MOD(N, M) ((N) % (M))
#define TOTING(OBJ) (game.objects[OBJ].place == CARRIED) #define TOTING(OBJ) (game.objects[OBJ].place == CARRIED)
#define AT(OBJ) (game.objects[OBJ].place == game.loc || game.objects[OBJ].fixed == game.loc) #define AT(OBJ) \
#define HERE(OBJ) (AT(OBJ) || TOTING(OBJ)) (game.objects[OBJ].place == game.loc || \
#define CNDBIT(L,N) (tstbit(conditions[L],N)) game.objects[OBJ].fixed == game.loc)
#define LIQUID() (game.objects[BOTTLE].prop == WATER_BOTTLE? WATER : game.objects[BOTTLE].prop == OIL_BOTTLE ? OIL : NO_OBJECT ) #define HERE(OBJ) (AT(OBJ) || TOTING(OBJ))
#define LIQLOC(LOC) (CNDBIT((LOC),COND_FLUID)? CNDBIT((LOC),COND_OILY) ? OIL : WATER : NO_OBJECT) #define CNDBIT(L, N) (tstbit(conditions[L], N))
#define FORCED(LOC) CNDBIT(LOC, COND_FORCED) #define LIQUID() \
#define DARK(DUMMY) (!CNDBIT(game.loc,COND_LIT) && (game.objects[LAMP].prop == LAMP_DARK || !HERE(LAMP))) (game.objects[BOTTLE].prop == WATER_BOTTLE ? WATER \
#define PCT(N) (randrange(100) < (N)) : game.objects[BOTTLE].prop == OIL_BOTTLE ? OIL \
#define GSTONE(OBJ) ((OBJ) == EMERALD || (OBJ) == RUBY || (OBJ) == AMBER || (OBJ) == SAPPH) : NO_OBJECT)
#define FOREST(LOC) CNDBIT(LOC, COND_FOREST) #define LIQLOC(LOC) \
#define OUTSID(LOC) (CNDBIT(LOC, COND_ABOVE) || FOREST(LOC)) (CNDBIT((LOC), COND_FLUID) ? CNDBIT((LOC), COND_OILY) ? OIL : WATER \
#define INSIDE(LOC) (!OUTSID(LOC) || LOC == LOC_BUILDING) : NO_OBJECT)
#define INDEEP(LOC) CNDBIT((LOC),COND_DEEP) #define FORCED(LOC) CNDBIT(LOC, COND_FORCED)
#define BUG(x) bug(x, #x) #define DARK(DUMMY) \
(!CNDBIT(game.loc, COND_LIT) && \
(game.objects[LAMP].prop == LAMP_DARK || !HERE(LAMP)))
#define PCT(N) (randrange(100) < (N))
#define GSTONE(OBJ) \
((OBJ) == EMERALD || (OBJ) == RUBY || (OBJ) == AMBER || (OBJ) == SAPPH)
#define FOREST(LOC) CNDBIT(LOC, COND_FOREST)
#define OUTSID(LOC) (CNDBIT(LOC, COND_ABOVE) || FOREST(LOC))
#define INSIDE(LOC) (!OUTSID(LOC) || LOC == LOC_BUILDING)
#define INDEEP(LOC) CNDBIT((LOC), COND_DEEP)
#define BUG(x) bug(x, #x)
enum bugtype { enum bugtype {
SPECIAL_TRAVEL_500_GT_L_GT_300_EXCEEDS_GOTO_LIST, SPECIAL_TRAVEL_500_GT_L_GT_300_EXCEEDS_GOTO_LIST,
VOCABULARY_TYPE_N_OVER_1000_NOT_BETWEEN_0_AND_3, VOCABULARY_TYPE_N_OVER_1000_NOT_BETWEEN_0_AND_3,
INTRANSITIVE_ACTION_VERB_EXCEEDS_GOTO_LIST, INTRANSITIVE_ACTION_VERB_EXCEEDS_GOTO_LIST,
TRANSITIVE_ACTION_VERB_EXCEEDS_GOTO_LIST, TRANSITIVE_ACTION_VERB_EXCEEDS_GOTO_LIST,
CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION, CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION,
LOCATION_HAS_NO_TRAVEL_ENTRIES, LOCATION_HAS_NO_TRAVEL_ENTRIES,
HINT_NUMBER_EXCEEDS_GOTO_LIST, HINT_NUMBER_EXCEEDS_GOTO_LIST,
SPEECHPART_NOT_TRANSITIVE_OR_INTRANSITIVE_OR_UNKNOWN, SPEECHPART_NOT_TRANSITIVE_OR_INTRANSITIVE_OR_UNKNOWN,
ACTION_RETURNED_PHASE_CODE_BEYOND_END_OF_SWITCH, ACTION_RETURNED_PHASE_CODE_BEYOND_END_OF_SWITCH,
}; };
enum speaktype {touch, look, hear, study, change}; enum speaktype { touch, look, hear, study, change };
enum termination {endgame, quitgame, scoregame}; enum termination { endgame, quitgame, scoregame };
enum speechpart {unknown, intransitive, transitive}; enum speechpart { unknown, intransitive, transitive };
typedef enum {NO_WORD_TYPE, MOTION, OBJECT, ACTION, NUMERIC} word_type_t; typedef enum { NO_WORD_TYPE, MOTION, OBJECT, ACTION, NUMERIC } word_type_t;
typedef enum scorebonus {none, splatter, defeat, victory} score_t; typedef enum scorebonus { none, splatter, defeat, victory } score_t;
/* Phase codes for action returns. /* Phase codes for action returns.
* These were at one time FORTRAN line numbers. * These were at one time FORTRAN line numbers.
*/ */
typedef enum { typedef enum {
GO_TERMINATE, GO_TERMINATE,
GO_MOVE, GO_MOVE,
GO_TOP, GO_TOP,
GO_CLEAROBJ, GO_CLEAROBJ,
GO_CHECKHINT, GO_CHECKHINT,
GO_WORD2, GO_WORD2,
GO_UNKNOWN, GO_UNKNOWN,
GO_DWARFWAKE, GO_DWARFWAKE,
} phase_codes_t; } phase_codes_t;
/* Use fixed-lwength types to make the save format moore portable */ /* Use fixed-lwength types to make the save format moore portable */
@ -183,75 +200,75 @@ typedef int32_t turn_t; // turn counter or threshold */
typedef int32_t bool32_t; // turn counter or threshold */ typedef int32_t bool32_t; // turn counter or threshold */
struct game_t { struct game_t {
int32_t lcg_x; int32_t lcg_x;
int32_t abbnum; // How often to print int descriptions int32_t abbnum; // How often to print int descriptions
score_t bonus; // What kind of finishing bonus we are getting score_t bonus; // What kind of finishing bonus we are getting
loc_t chloc; // pirate chest location loc_t chloc; // pirate chest location
loc_t chloc2; // pirate chest alternate location loc_t chloc2; // pirate chest alternate location
turn_t clock1; // # turns from finding last treasure to close turn_t clock1; // # turns from finding last treasure to close
turn_t clock2; // # turns from warning till blinding flash turn_t clock2; // # turns from warning till blinding flash
bool32_t clshnt; // has player read the clue in the endgame? bool32_t clshnt; // has player read the clue in the endgame?
bool32_t closed; // whether we're all the way closed bool32_t closed; // whether we're all the way closed
bool32_t closng; // whether it's closing time yet bool32_t closng; // whether it's closing time yet
bool32_t lmwarn; // has player been warned about lamp going dim? bool32_t lmwarn; // has player been warned about lamp going dim?
bool32_t novice; // asked for instructions at start-up? bool32_t novice; // asked for instructions at start-up?
bool32_t panic; // has player found out he's trapped? bool32_t panic; // has player found out he's trapped?
bool32_t wzdark; // whether the loc he's leaving was dark bool32_t wzdark; // whether the loc he's leaving was dark
bool32_t blooded; // has player drunk of dragon's blood? bool32_t blooded; // has player drunk of dragon's blood?
int32_t conds; // min value for cond[loc] if loc has any hints int32_t conds; // min value for cond[loc] if loc has any hints
int32_t detail; // level of detail in descriptions int32_t detail; // level of detail in descriptions
/* dflag controls the level of activation of dwarves: /* dflag controls the level of activation of dwarves:
* 0 No dwarf stuff yet (wait until reaches Hall Of Mists) * 0 No dwarf stuff yet (wait until reaches Hall Of Mists)
* 1 Reached Hall Of Mists, but hasn't met first dwarf * 1 Reached Hall Of Mists, but hasn't met first dwarf
* 2 Met first dwarf, others start moving, no knives thrown yet * 2 Met first dwarf, others start moving, no knives thrown
* 3 A knife has been thrown (first set always misses) *yet 3 A knife has been thrown (first set always misses) 3+
* 3+ Dwarves are mad (increases their accuracy) */ *Dwarves are mad (increases their accuracy) */
int32_t dflag; int32_t dflag;
int32_t dkill; // dwarves killed int32_t dkill; // dwarves killed
int32_t dtotal; // total dwarves (including pirate) in loc int32_t dtotal; // total dwarves (including pirate) in loc
int32_t foobar; // progress in saying "FEE FIE FOE FOO". int32_t foobar; // progress in saying "FEE FIE FOE FOO".
int32_t holdng; // number of objects being carried int32_t holdng; // number of objects being carried
int32_t igo; // # uses of "go" instead of a direction int32_t igo; // # uses of "go" instead of a direction
int32_t iwest; // # times he's said "west" instead of "w" int32_t iwest; // # times he's said "west" instead of "w"
loc_t knfloc; // knife location; LOC_NOWERE if none, -1 after caveat loc_t knfloc; // knife location; LOC_NOWERE if none, -1 after caveat
turn_t limit; // lifetime of lamp turn_t limit; // lifetime of lamp
loc_t loc; // where player is now loc_t loc; // where player is now
loc_t newloc; // where player is going loc_t newloc; // where player is going
turn_t numdie; // number of times killed so far turn_t numdie; // number of times killed so far
loc_t oldloc; // where player was loc_t oldloc; // where player was
loc_t oldlc2; // where player was two moves ago loc_t oldlc2; // where player was two moves ago
obj_t oldobj; // last object player handled obj_t oldobj; // last object player handled
int32_t saved; // point penalty for saves int32_t saved; // point penalty for saves
int32_t tally; // count of treasures gained int32_t tally; // count of treasures gained
int32_t thresh; // current threshold for endgame scoring tier int32_t thresh; // current threshold for endgame scoring tier
bool32_t seenbigwords; // have we red the graffiti in the Giant's Room? bool32_t seenbigwords; // have we red the graffiti in the Giant's Room?
turn_t trnluz; // # points lost so far due to turns used turn_t trnluz; // # points lost so far due to turns used
turn_t turns; // counts commands given (ignores yes/no) turn_t turns; // counts commands given (ignores yes/no)
char zzword[TOKLEN + 1]; // randomly generated magic word from bird char zzword[TOKLEN + 1]; // randomly generated magic word from bird
struct { struct {
int32_t abbrev; // has location been seen? int32_t abbrev; // has location been seen?
int32_t atloc; // head of object linked list per location int32_t atloc; // head of object linked list per location
} locs[NLOCATIONS + 1]; } locs[NLOCATIONS + 1];
struct { struct {
int32_t seen; // true if dwarf has seen him int32_t seen; // true if dwarf has seen him
loc_t loc; // location of dwarves, initially hard-wired in loc_t loc; // location of dwarves, initially hard-wired in
loc_t oldloc; // prior loc of each dwarf, initially garbage loc_t oldloc; // prior loc of each dwarf, initially garbage
} dwarves[NDWARVES + 1]; } dwarves[NDWARVES + 1];
struct { struct {
#ifdef FOUNDBOOL #ifdef FOUNDBOOL
bool32_t found; // has the location of this object been found? bool32_t found; // has the location of this object been found?
#endif #endif
loc_t fixed; // fixed location of object (if not IS_FREE) loc_t fixed; // fixed location of object (if not IS_FREE)
int32_t prop; // object state */ int32_t prop; // object state */
loc_t place; // location of object loc_t place; // location of object
} objects[NOBJECTS + 1]; } objects[NOBJECTS + 1];
struct { struct {
bool32_t used; // hints[i].used = true iff hint i has been used. bool32_t used; // hints[i].used = true iff hint i has been used.
int32_t lc; // hints[i].lc = show int at LOC with cond bit i int32_t lc; // hints[i].lc = show int at LOC with cond bit i
} hints[NHINTS]; } hints[NHINTS];
obj_t link[NOBJECTS * 2 + 1];// object-list links obj_t link[NOBJECTS * 2 + 1]; // object-list links
}; };
/* /*
@ -259,56 +276,64 @@ struct game_t {
* This data is not saved in a saved game. * This data is not saved in a saved game.
*/ */
struct settings_t { struct settings_t {
FILE *logfp; FILE *logfp;
bool oldstyle; bool oldstyle;
bool prompt; bool prompt;
char **argv; char **argv;
int argc; int argc;
int optind; int optind;
FILE *scriptfp; FILE *scriptfp;
int debug; int debug;
}; };
typedef struct { typedef struct {
char raw[LINESIZE]; char raw[LINESIZE];
vocab_t id; vocab_t id;
word_type_t type; word_type_t type;
} command_word_t; } command_word_t;
typedef enum {EMPTY, RAW, TOKENIZED, GIVEN, PREPROCESSED, PROCESSING, EXECUTED} command_state_t; typedef enum {
EMPTY,
RAW,
TOKENIZED,
GIVEN,
PREPROCESSED,
PROCESSING,
EXECUTED
} command_state_t;
typedef struct { typedef struct {
enum speechpart part; enum speechpart part;
command_word_t word[2]; command_word_t word[2];
verb_t verb; verb_t verb;
obj_t obj; obj_t obj;
command_state_t state; command_state_t state;
} command_t; } command_t;
/* /*
* Bump on save format change. * Bump on save format change.
* *
* Note: Verify that the tests run clean before bumping this, then rebuild the check * Note: Verify that the tests run clean before bumping this, then rebuild the
* files afterwards. Otherwise you will get a spurious failure due to the old version * check files afterwards. Otherwise you will get a spurious failure due to the
* having been generated into a check file. * old version having been generated into a check file.
*/ */
#define SAVE_VERSION 31 #define SAVE_VERSION 31
/* /*
* Goes at start of file so saves can be identified by file(1) and the like. * Goes at start of file so saves can be identified by file(1) and the like.
*/ */
#define ADVENT_MAGIC "open-adventure\n" #define ADVENT_MAGIC "open-adventure\n"
/* /*
* If you change the first three members, the resume function may not properly * If you change the first three members, the resume function may not properly
* reject saves from older versions. Later members can change, but bump the version * reject saves from older versions. Later members can change, but bump the
* when you do that. * version when you do that.
*/ */
struct save_t { struct save_t {
char magic[sizeof(ADVENT_MAGIC)]; char magic[sizeof(ADVENT_MAGIC)];
int32_t version; int32_t version;
int32_t canary; int32_t canary;
struct game_t game; struct game_t game;
}; };
extern struct game_t game; extern struct game_t game;
@ -318,13 +343,13 @@ extern struct settings_t settings;
extern char *myreadline(const char *); extern char *myreadline(const char *);
extern bool get_command_input(command_t *); extern bool get_command_input(command_t *);
extern void clear_command(command_t *); extern void clear_command(command_t *);
extern void speak(const char*, ...); extern void speak(const char *, ...);
extern void sspeak(int msg, ...); extern void sspeak(int msg, ...);
extern void pspeak(vocab_t, enum speaktype, bool, int, ...); extern void pspeak(vocab_t, enum speaktype, bool, int, ...);
extern void rspeak(vocab_t, ...); extern void rspeak(vocab_t, ...);
extern void echo_input(FILE*, const char*, const char*); extern void echo_input(FILE *, const char *, const char *);
extern bool silent_yes_or_no(void); extern bool silent_yes_or_no(void);
extern bool yes_or_no(const char*, const char*, const char*); extern bool yes_or_no(const char *, const char *, const char *);
extern void juggle(obj_t); extern void juggle(obj_t);
extern void move(obj_t, loc_t); extern void move(obj_t, loc_t);
extern void put(obj_t, loc_t, int); extern void put(obj_t, loc_t, int);

154
cheat.c
View file

@ -7,93 +7,90 @@
* SPDX-FileCopyrightText: (C) 1977, 2005 by Will Crowther and Don Woods * SPDX-FileCopyrightText: (C) 1977, 2005 by Will Crowther and Don Woods
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <getopt.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <editline/readline.h>
#include "advent.h" #include "advent.h"
#include <editline/readline.h>
#include <getopt.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) int main(int argc, char *argv[]) {
{ int ch;
int ch; char *savefilename = NULL;
char *savefilename = NULL; FILE *fp = NULL;
FILE *fp = NULL;
// Initialize game variables // Initialize game variables
initialise(); initialise();
/* we're generating a saved game, so saved once by default, /* we're generating a saved game, so saved once by default,
* unless overridden with command-line options below. * unless overridden with command-line options below.
*/ */
game.saved = 1; game.saved = 1;
/* Options. */ /* Options. */
const char* opts = "d:l:s:t:v:o:"; const char *opts = "d:l:s:t:v:o:";
const char* usage = "Usage: %s [-d numdie] [-s numsaves] [-v version] -o savefilename \n" const char *usage =
" -d number of deaths. Signed integer.\n" "Usage: %s [-d numdie] [-s numsaves] [-v version] -o savefilename "
" -l lifetime of lamp in turns. Signed integer.\n" "\n"
" -s number of saves. Signed integer.\n" " -d number of deaths. Signed integer.\n"
" -t number of turns. Signed integer.\n" " -l lifetime of lamp in turns. Signed integer.\n"
" -v version number of save format.\n" " -s number of saves. Signed integer.\n"
" -o required. File name of save game to write.\n"; " -t number of turns. Signed integer.\n"
" -v version number of save format.\n"
" -o required. File name of save game to write.\n";
while ((ch = getopt(argc, argv, opts)) != EOF) { while ((ch = getopt(argc, argv, opts)) != EOF) {
switch (ch) { switch (ch) {
case 'd': case 'd':
game.numdie = (turn_t)atoi(optarg); game.numdie = (turn_t)atoi(optarg);
printf("cheat: game.numdie = %d\n", game.numdie); printf("cheat: game.numdie = %d\n", game.numdie);
break; break;
case 'l': case 'l':
game.limit = (turn_t)atoi(optarg); game.limit = (turn_t)atoi(optarg);
printf("cheat: game.limit = %d\n", game.limit); printf("cheat: game.limit = %d\n", game.limit);
break; break;
case 's': case 's':
game.saved = (int)atoi(optarg); game.saved = (int)atoi(optarg);
printf("cheat: game.saved = %d\n", game.saved); printf("cheat: game.saved = %d\n", game.saved);
break; break;
case 't': case 't':
game.turns = (turn_t)atoi(optarg); game.turns = (turn_t)atoi(optarg);
printf("cheat: game.turns = %d\n", game.turns); printf("cheat: game.turns = %d\n", game.turns);
break; break;
case 'v': case 'v':
save.version = atoi(optarg); save.version = atoi(optarg);
printf("cheat: version = %d\n", save.version); printf("cheat: version = %d\n", save.version);
break; break;
case 'o': case 'o':
savefilename = optarg; savefilename = optarg;
break; break;
default: default:
fprintf(stderr, fprintf(stderr, usage, argv[0]);
usage, argv[0]); exit(EXIT_FAILURE);
exit(EXIT_FAILURE); break;
break; }
} }
}
// Save filename required; the point of cheat is to generate save file // Save filename required; the point of cheat is to generate save file
if (savefilename == NULL) { if (savefilename == NULL) {
fprintf(stderr, fprintf(stderr, usage, argv[0]);
usage, argv[0]); fprintf(stderr, "ERROR: filename required\n");
fprintf(stderr, exit(EXIT_FAILURE);
"ERROR: filename required\n"); }
exit(EXIT_FAILURE);
}
fp = fopen(savefilename, WRITE_MODE); fp = fopen(savefilename, WRITE_MODE);
if (fp == NULL) { if (fp == NULL) {
fprintf(stderr, fprintf(stderr, "Can't open file %s. Exiting.\n", savefilename);
"Can't open file %s. Exiting.\n", savefilename); exit(EXIT_FAILURE);
exit(EXIT_FAILURE); }
}
savefile(fp); savefile(fp);
fclose(fp); fclose(fp);
printf("cheat: %s created.\n", savefilename); printf("cheat: %s created.\n", savefilename);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
// LCOV_EXCL_START // LCOV_EXCL_START
@ -102,12 +99,7 @@ int main(int argc, char *argv[])
* See the actually useful version of this in main.c * See the actually useful version of this in main.c
*/ */
char *myreadline(const char *prompt) char *myreadline(const char *prompt) { return readline(prompt); }
{
return readline(prompt);
}
// LCOV_EXCL_STOP // LCOV_EXCL_STOP
/* end */ /* end */

141
init.c
View file

@ -5,97 +5,86 @@
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <assert.h> #include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "advent.h" #include "advent.h"
struct settings_t settings = { struct settings_t settings = {.logfp = NULL, .oldstyle = false, .prompt = true};
.logfp = NULL,
.oldstyle = false,
.prompt = true
};
struct game_t game = { struct game_t game = {
/* Last dwarf is special (the pirate). He always starts at his /* Last dwarf is special (the pirate). He always starts at his
* chest's eventual location inside the maze. This loc is saved * chest's eventual location inside the maze. This loc is saved
* in chloc for ref. The dead end in the other maze has its * in chloc for ref. The dead end in the other maze has its
* loc stored in chloc2. */ * loc stored in chloc2. */
.chloc = LOC_MAZEEND12, .chloc = LOC_MAZEEND12, .chloc2 = LOC_DEADEND13, .abbnum = 5,
.chloc2 = LOC_DEADEND13, .clock1 = WARNTIME, .clock2 = FLASHTIME, .newloc = LOC_START,
.abbnum = 5, .loc = LOC_START, .limit = GAMELIMIT, .foobar = WORD_EMPTY,
.clock1 = WARNTIME,
.clock2 = FLASHTIME,
.newloc = LOC_START,
.loc = LOC_START,
.limit = GAMELIMIT,
.foobar = WORD_EMPTY,
}; };
int initialise(void) int initialise(void) {
{ if (settings.oldstyle)
if (settings.oldstyle) printf("Initialising...\n");
printf("Initialising...\n");
srand(time(NULL)); srand(time(NULL));
int seedval = (int)rand(); int seedval = (int)rand();
set_seed(seedval); set_seed(seedval);
for (int i = 1; i <= NDWARVES; i++) { for (int i = 1; i <= NDWARVES; i++) {
game.dwarves[i].loc = dwarflocs[i-1]; game.dwarves[i].loc = dwarflocs[i - 1];
}
for (int i = 1; i <= NOBJECTS; i++) {
game.objects[i].place = LOC_NOWHERE;
}
for (int i = 1; i <= NLOCATIONS; i++) {
if (!(locations[i].description.big == 0 || tkey[i] == 0)) {
int k = tkey[i];
if (travel[k].motion == HERE) {
conditions[i] |= (1 << COND_FORCED);
}
}
}
/* Set up the game.locs atloc and game.link arrays.
* We'll use the DROP subroutine, which prefaces new objects on the
* lists. Since we want things in the other order, we'll run the
* loop backwards. If the object is in two locs, we drop it twice.
* Also, since two-placed objects are typically best described
* last, we'll drop them first. */
for (int i = NOBJECTS; i >= 1; i--) {
if (objects[i].fixd > 0) {
drop(i + NOBJECTS, objects[i].fixd);
drop(i, objects[i].plac);
}
}
for (int i = 1; i <= NOBJECTS; i++) {
int k = NOBJECTS + 1 - i;
game.objects[k].fixed = objects[k].fixd;
if (objects[k].plac != 0 && objects[k].fixd <= 0) {
drop(k, objects[k].plac);
} }
}
/* Treasure props are initially STATE_NOTFOUND, and are set to for (int i = 1; i <= NOBJECTS; i++) {
* STATE_FOUND the first time they are described. game.tally game.objects[i].place = LOC_NOWHERE;
* keeps track of how many are not yet found, so we know when to }
* close the cave. */
for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
if (objects[treasure].is_treasure) {
++game.tally;
if (objects[treasure].inventory != 0) {
PROP_SET_NOT_FOUND(treasure);
}
}
}
game.conds = setbit(COND_HBASE);
return seedval; for (int i = 1; i <= NLOCATIONS; i++) {
if (!(locations[i].description.big == 0 || tkey[i] == 0)) {
int k = tkey[i];
if (travel[k].motion == HERE) {
conditions[i] |= (1 << COND_FORCED);
}
}
}
/* Set up the game.locs atloc and game.link arrays.
* We'll use the DROP subroutine, which prefaces new objects on the
* lists. Since we want things in the other order, we'll run the
* loop backwards. If the object is in two locs, we drop it twice.
* Also, since two-placed objects are typically best described
* last, we'll drop them first. */
for (int i = NOBJECTS; i >= 1; i--) {
if (objects[i].fixd > 0) {
drop(i + NOBJECTS, objects[i].fixd);
drop(i, objects[i].plac);
}
}
for (int i = 1; i <= NOBJECTS; i++) {
int k = NOBJECTS + 1 - i;
game.objects[k].fixed = objects[k].fixd;
if (objects[k].plac != 0 && objects[k].fixd <= 0) {
drop(k, objects[k].plac);
}
}
/* Treasure props are initially STATE_NOTFOUND, and are set to
* STATE_FOUND the first time they are described. game.tally
* keeps track of how many are not yet found, so we know when to
* close the cave. */
for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
if (objects[treasure].is_treasure) {
++game.tally;
if (objects[treasure].inventory != 0) {
PROP_SET_NOT_FOUND(treasure);
}
}
}
game.conds = setbit(COND_HBASE);
return seedval;
} }

2570
main.c

File diff suppressed because it is too large Load diff

1220
misc.c

File diff suppressed because it is too large Load diff

View file

@ -8,243 +8,263 @@
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <ctype.h>
#include <inttypes.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <ctype.h>
#include <time.h> #include <time.h>
#include <inttypes.h>
#include "advent.h" #include "advent.h"
/* /*
* Use this to detect endianness mismatch. Can't be unchanged by byte-swapping. * Use this to detect endianness mismatch. Can't be unchanged by byte-swapping.
*/ */
#define ENDIAN_MAGIC 2317 #define ENDIAN_MAGIC 2317
struct save_t save; struct save_t save;
#define IGNORE(r) do{if (r){}}while(0) #define IGNORE(r) \
do { \
if (r) { \
} \
} while (0)
int savefile(FILE *fp) int savefile(FILE *fp) {
/* Save game to file. No input or output from user. */ /* Save game to file. No input or output from user. */
{ memcpy(&save.magic, ADVENT_MAGIC, sizeof(ADVENT_MAGIC));
memcpy(&save.magic, ADVENT_MAGIC, sizeof(ADVENT_MAGIC)); if (save.version == 0) {
if (save.version == 0) save.version = SAVE_VERSION;
save.version = SAVE_VERSION; }
if (save.canary == 0) if (save.canary == 0) {
save.canary = ENDIAN_MAGIC; save.canary = ENDIAN_MAGIC;
}
save.game = game; save.game = game;
IGNORE(fwrite(&save, sizeof(struct save_t), 1, fp)); IGNORE(fwrite(&save, sizeof(struct save_t), 1, fp));
return (0); return (0);
} }
/* Suspend and resume */ /* Suspend and resume */
static char *strip(char *name) static char *strip(char *name) {
{ // Trim leading whitespace
// Trim leading whitespace while (isspace((unsigned char)*name)) {
while(isspace((unsigned char)*name)) name++; // LCOV_EXCL_LINE
name++; // LCOV_EXCL_LINE }
if(*name != '\0') { if (*name != '\0') {
// Trim trailing whitespace; // Trim trailing whitespace;
// might be left there by autocomplete // might be left there by autocomplete
char *end = name + strlen(name) - 1; char *end = name + strlen(name) - 1;
while(end > name && isspace((unsigned char)*end)) while (end > name && isspace((unsigned char)*end)) {
end--; end--;
// Write new null terminator character }
end[1] = '\0'; // Write new null terminator character
} end[1] = '\0';
}
return name; return name;
} }
int suspend(void) int suspend(void) {
{ /* Suspend. Offer to save things in a file, but charging
/* Suspend. Offer to save things in a file, but charging * some points (so can't win by using saved games to retry
* some points (so can't win by using saved games to retry * battles or to start over after learning zzword).
* battles or to start over after learning zzword). * If ADVENT_NOSAVE is defined, gripe instead. */
* If ADVENT_NOSAVE is defined, gripe instead. */
#if defined ADVENT_NOSAVE || defined ADVENT_AUTOSAVE #if defined ADVENT_NOSAVE || defined ADVENT_AUTOSAVE
rspeak(SAVERESUME_DISABLED); rspeak(SAVERESUME_DISABLED);
return GO_TOP; return GO_TOP;
#endif #endif
FILE *fp = NULL; FILE *fp = NULL;
rspeak(SUSPEND_WARNING); rspeak(SUSPEND_WARNING);
if (!yes_or_no(arbitrary_messages[THIS_ACCEPTABLE], arbitrary_messages[OK_MAN], arbitrary_messages[OK_MAN])) if (!yes_or_no(arbitrary_messages[THIS_ACCEPTABLE],
return GO_CLEAROBJ; arbitrary_messages[OK_MAN],
game.saved = game.saved + 5; arbitrary_messages[OK_MAN])) {
return GO_CLEAROBJ;
}
game.saved = game.saved + 5;
while (fp == NULL) { while (fp == NULL) {
char* name = myreadline("\nFile name: "); char *name = myreadline("\nFile name: ");
if (name == NULL) if (name == NULL) {
return GO_TOP; return GO_TOP;
name = strip(name); }
if (strlen(name) == 0) name = strip(name);
return GO_TOP; // LCOV_EXCL_LINE if (strlen(name) == 0) {
fp = fopen(strip(name), WRITE_MODE); return GO_TOP; // LCOV_EXCL_LINE
if (fp == NULL) }
printf("Can't open file %s, try again.\n", name); fp = fopen(strip(name), WRITE_MODE);
free(name); if (fp == NULL) {
} printf("Can't open file %s, try again.\n", name);
}
free(name);
}
savefile(fp); savefile(fp);
fclose(fp); fclose(fp);
rspeak(RESUME_HELP); rspeak(RESUME_HELP);
exit(EXIT_SUCCESS);
}
int resume(void)
{
/* Resume. Read a suspended game back from a file.
* If ADVENT_NOSAVE is defined, gripe instead. */
#if defined ADVENT_NOSAVE || defined ADVENT_AUTOSAVE
rspeak(SAVERESUME_DISABLED);
return GO_TOP;
#endif
FILE *fp = NULL;
if (game.loc != LOC_START || game.locs[LOC_START].abbrev != 1) {
rspeak(RESUME_ABANDON);
if (!yes_or_no(arbitrary_messages[THIS_ACCEPTABLE], arbitrary_messages[OK_MAN], arbitrary_messages[OK_MAN]))
return GO_CLEAROBJ;
}
while (fp == NULL) {
char* name = myreadline("\nFile name: ");
if (name == NULL)
return GO_TOP;
name = strip(name);
if (strlen(name) == 0)
return GO_TOP; // LCOV_EXCL_LINE
fp = fopen(name, READ_MODE);
if (fp == NULL)
printf("Can't open file %s, try again.\n", name);
free(name);
}
return restore(fp);
}
int restore(FILE* fp)
{
/* Read and restore game state from file, assuming
* sane initial state.
* If ADVENT_NOSAVE is defined, gripe instead. */
#ifdef ADVENT_NOSAVE
rspeak(SAVERESUME_DISABLED);
return GO_TOP;
#endif
IGNORE(fread(&save, sizeof(struct save_t), 1, fp));
fclose(fp);
if (memcmp(save.magic, ADVENT_MAGIC, sizeof(ADVENT_MAGIC)) != 0 || save.canary != ENDIAN_MAGIC)
rspeak(BAD_SAVE);
else if (save.version != SAVE_VERSION) {
rspeak(VERSION_SKEW, save.version / 10, MOD(save.version, 10), SAVE_VERSION / 10, MOD(SAVE_VERSION, 10));
} else if (!is_valid(save.game)) {
rspeak(SAVE_TAMPERING);
exit(EXIT_SUCCESS); exit(EXIT_SUCCESS);
} else {
game = save.game;
}
return GO_TOP;
} }
bool is_valid(struct game_t valgame) int resume(void) {
{ /* Resume. Read a suspended game back from a file.
/* Save files can be roughly grouped into three groups: * If ADVENT_NOSAVE is defined, gripe instead. */
* With valid, reachable state, with valid, but unreachable
* state and with invalid state. We check that state is
* valid: no states are outside minimal or maximal value
*/
/* Prevent division by zero */ #if defined ADVENT_NOSAVE || defined ADVENT_AUTOSAVE
if (valgame.abbnum == 0) { rspeak(SAVERESUME_DISABLED);
return false; // LCOV_EXCL_LINE return GO_TOP;
} #endif
FILE *fp = NULL;
/* Check for RNG overflow. Truncate */ if (game.loc != LOC_START || game.locs[LOC_START].abbrev != 1) {
if (valgame.lcg_x >= LCG_M) { rspeak(RESUME_ABANDON);
valgame.lcg_x %= LCG_M; // LCOV_EXCL_LINE if (!yes_or_no(arbitrary_messages[THIS_ACCEPTABLE],
} arbitrary_messages[OK_MAN],
arbitrary_messages[OK_MAN])) {
return GO_CLEAROBJ;
}
}
/* Check for RNG underflow. Transpose */ while (fp == NULL) {
if (valgame.lcg_x < LCG_M) { char *name = myreadline("\nFile name: ");
valgame.lcg_x = LCG_M + (valgame.lcg_x % LCG_M); if (name == NULL)
} return GO_TOP;
name = strip(name);
if (strlen(name) == 0)
return GO_TOP; // LCOV_EXCL_LINE
fp = fopen(name, READ_MODE);
if (fp == NULL) {
printf("Can't open file %s, try again.\n", name);
}
free(name);
}
/* Bounds check for locations */ return restore(fp);
if ( valgame.chloc < -1 || valgame.chloc > NLOCATIONS || }
valgame.chloc2 < -1 || valgame.chloc2 > NLOCATIONS ||
valgame.loc < 0 || valgame.loc > NLOCATIONS ||
valgame.newloc < 0 || valgame.newloc > NLOCATIONS ||
valgame.oldloc < 0 || valgame.oldloc > NLOCATIONS ||
valgame.oldlc2 < 0 || valgame.oldlc2 > NLOCATIONS) {
return false; // LCOV_EXCL_LINE
}
/* Bounds check for location arrays */
for (int i = 0; i <= NDWARVES; i++) {
if (valgame.dwarves[i].loc < -1 || valgame.dwarves[i].loc > NLOCATIONS ||
valgame.dwarves[i].oldloc < -1 || valgame.dwarves[i].oldloc > NLOCATIONS) {
return false; // LCOV_EXCL_LINE
}
}
for (int i = 0; i <= NOBJECTS; i++) { int restore(FILE *fp) {
if (valgame.objects[i].place < -1 || valgame.objects[i].place > NLOCATIONS || /* Read and restore game state from file, assuming
valgame.objects[i].fixed < -1 || valgame.objects[i].fixed > NLOCATIONS) { * sane initial state.
return false; // LCOV_EXCL_LINE * If ADVENT_NOSAVE is defined, gripe instead. */
} #ifdef ADVENT_NOSAVE
} rspeak(SAVERESUME_DISABLED);
return GO_TOP;
#endif
/* Bounds check for dwarves */ IGNORE(fread(&save, sizeof(struct save_t), 1, fp));
if (valgame.dtotal < 0 || valgame.dtotal > NDWARVES || fclose(fp);
valgame.dkill < 0 || valgame.dkill > NDWARVES) { if (memcmp(save.magic, ADVENT_MAGIC, sizeof(ADVENT_MAGIC)) != 0 ||
return false; // LCOV_EXCL_LINE save.canary != ENDIAN_MAGIC) {
} rspeak(BAD_SAVE);
} else if (save.version != SAVE_VERSION) {
rspeak(VERSION_SKEW, save.version / 10, MOD(save.version, 10),
SAVE_VERSION / 10, MOD(SAVE_VERSION, 10));
} else if (!is_valid(save.game)) {
rspeak(SAVE_TAMPERING);
exit(EXIT_SUCCESS);
} else {
game = save.game;
}
return GO_TOP;
}
/* Validate that we didn't die too many times in save */ bool is_valid(struct game_t valgame) {
if (valgame.numdie >= NDEATHS) { /* Save files can be roughly grouped into three groups:
return false; // LCOV_EXCL_LINE * With valid, reachable state, with valid, but unreachable
} * state and with invalid state. We check that state is
* valid: no states are outside minimal or maximal value
*/
/* Recalculate tally, throw the towel if in disagreement */ /* Prevent division by zero */
int temp_tally = 0; if (valgame.abbnum == 0) {
for (int treasure = 1; treasure <= NOBJECTS; treasure++) { return false; // LCOV_EXCL_LINE
if (objects[treasure].is_treasure) { }
if (PROP_IS_NOTFOUND2(valgame, treasure)) {
++temp_tally;
}
}
}
if (temp_tally != valgame.tally) {
return false; // LCOV_EXCL_LINE
}
/* Check that properties of objects aren't beyond expected */ /* Check for RNG overflow. Truncate */
for (obj_t obj = 0; obj <= NOBJECTS; obj++) { if (valgame.lcg_x >= LCG_M) {
if (PROP_IS_INVALID(valgame.objects[obj].prop)) { valgame.lcg_x %= LCG_M; // LCOV_EXCL_LINE
return false; // LCOV_EXCL_LINE }
}
}
/* Check that values in linked lists for objects in locations are inside bounds */ /* Check for RNG underflow. Transpose */
for (loc_t loc = LOC_NOWHERE; loc <= NLOCATIONS; loc++) { if (valgame.lcg_x < LCG_M) {
if (valgame.locs[loc].atloc < NO_OBJECT || valgame.locs[loc].atloc > NOBJECTS * 2) { valgame.lcg_x = LCG_M + (valgame.lcg_x % LCG_M);
return false; // LCOV_EXCL_LINE }
}
}
for (obj_t obj = 0; obj <= NOBJECTS * 2; obj++ ) {
if (valgame.link[obj] < NO_OBJECT || valgame.link[obj] > NOBJECTS * 2) {
return false; // LCOV_EXCL_LINE
}
}
return true; /* Bounds check for locations */
if (valgame.chloc < -1 || valgame.chloc > NLOCATIONS ||
valgame.chloc2 < -1 || valgame.chloc2 > NLOCATIONS ||
valgame.loc < 0 || valgame.loc > NLOCATIONS || valgame.newloc < 0 ||
valgame.newloc > NLOCATIONS || valgame.oldloc < 0 ||
valgame.oldloc > NLOCATIONS || valgame.oldlc2 < 0 ||
valgame.oldlc2 > NLOCATIONS) {
return false; // LCOV_EXCL_LINE
}
/* Bounds check for location arrays */
for (int i = 0; i <= NDWARVES; i++) {
if (valgame.dwarves[i].loc < -1 ||
valgame.dwarves[i].loc > NLOCATIONS ||
valgame.dwarves[i].oldloc < -1 ||
valgame.dwarves[i].oldloc > NLOCATIONS) {
return false; // LCOV_EXCL_LINE
}
}
for (int i = 0; i <= NOBJECTS; i++) {
if (valgame.objects[i].place < -1 ||
valgame.objects[i].place > NLOCATIONS ||
valgame.objects[i].fixed < -1 ||
valgame.objects[i].fixed > NLOCATIONS) {
return false; // LCOV_EXCL_LINE
}
}
/* Bounds check for dwarves */
if (valgame.dtotal < 0 || valgame.dtotal > NDWARVES ||
valgame.dkill < 0 || valgame.dkill > NDWARVES) {
return false; // LCOV_EXCL_LINE
}
/* Validate that we didn't die too many times in save */
if (valgame.numdie >= NDEATHS) {
return false; // LCOV_EXCL_LINE
}
/* Recalculate tally, throw the towel if in disagreement */
int temp_tally = 0;
for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
if (objects[treasure].is_treasure) {
if (PROP_IS_NOTFOUND2(valgame, treasure)) {
++temp_tally;
}
}
}
if (temp_tally != valgame.tally) {
return false; // LCOV_EXCL_LINE
}
/* Check that properties of objects aren't beyond expected */
for (obj_t obj = 0; obj <= NOBJECTS; obj++) {
if (PROP_IS_INVALID(valgame.objects[obj].prop)) {
return false; // LCOV_EXCL_LINE
}
}
/* Check that values in linked lists for objects in locations are inside
* bounds */
for (loc_t loc = LOC_NOWHERE; loc <= NLOCATIONS; loc++) {
if (valgame.locs[loc].atloc < NO_OBJECT ||
valgame.locs[loc].atloc > NOBJECTS * 2) {
return false; // LCOV_EXCL_LINE
}
}
for (obj_t obj = 0; obj <= NOBJECTS * 2; obj++) {
if (valgame.link[obj] < NO_OBJECT ||
valgame.link[obj] > NOBJECTS * 2) {
return false; // LCOV_EXCL_LINE
}
}
return true;
} }
/* end */ /* end */

258
score.c
View file

@ -4,157 +4,159 @@
* SPDX-FileCopyrightText: (C) 1977, 2005 by Will Crowther and Don Woods * SPDX-FileCopyrightText: (C) 1977, 2005 by Will Crowther and Don Woods
* SPDX-License-Identifier: BSD-2-Clause * SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <stdlib.h>
#include "advent.h" #include "advent.h"
#include "dungeon.h" #include "dungeon.h"
#include <stdlib.h>
static int mxscor; /* ugh..the price for having score() not exit. */ static int mxscor; /* ugh..the price for having score() not exit. */
int score(enum termination mode) { int score(enum termination mode) {
/* mode is 'scoregame' if scoring, 'quitgame' if quitting, 'endgame' if died /* mode is 'scoregame' if scoring, 'quitgame' if quitting, 'endgame' if
* or won */ * died or won */
int score = 0; int score = 0;
/* The present scoring algorithm is as follows: /* The present scoring algorithm is as follows:
* Objective: Points: Present total possible: * Objective: Points: Present total possible:
* Getting well into cave 25 25 * Getting well into cave 25 25
* Each treasure < chest 12 60 * Each treasure < chest 12 60
* Treasure chest itself 14 14 * Treasure chest itself 14 14
* Each treasure > chest 16 224 * Each treasure > chest 16 224
* Surviving (MAX-NUM)*10 30 * Surviving (MAX-NUM)*10 30
* Not quitting 4 4 * Not quitting 4 4
* Reaching "game.closng" 25 25 * Reaching "game.closng" 25 25
* "Closed": Quit/Killed 10 * "Closed": Quit/Killed 10
* Klutzed 25 * Klutzed 25
* Wrong way 30 * Wrong way 30
* Success 45 45 * Success 45 45
* Came to Witt's End 1 1 * Came to Witt's End 1 1
* Round out the total 2 2 * Round out the total 2 2
* TOTAL: 430 * TOTAL: 430
* Points can also be deducted for using hints or too many turns, or for * Points can also be deducted for using hints or too many turns, or
* saving intermediate positions. */ * for saving intermediate positions. */
/* First tally up the treasures. Must be in building and not broken. /* First tally up the treasures. Must be in building and not broken.
* Give the poor guy 2 points just for finding each treasure. */ * Give the poor guy 2 points just for finding each treasure. */
mxscor = 0; mxscor = 0;
for (int i = 1; i <= NOBJECTS; i++) { for (int i = 1; i <= NOBJECTS; i++) {
if (!objects[i].is_treasure) { if (!objects[i].is_treasure) {
continue; continue;
}
if (objects[i].inventory != 0) {
int k = 12;
if (i == CHEST) {
k = 14;
}
if (i > CHEST) {
k = 16;
}
if (!PROP_IS_STASHED(i) && !PROP_IS_NOTFOUND(i)) {
score += 2;
}
if (game.objects[i].place == LOC_BUILDING &&
PROP_IS_FOUND(i)) {
score += k - 2;
}
mxscor += k;
}
} }
if (objects[i].inventory != 0) {
int k = 12;
if (i == CHEST) {
k = 14;
}
if (i > CHEST) {
k = 16;
}
if (!PROP_IS_STASHED(i) && !PROP_IS_NOTFOUND(i)) {
score += 2;
}
if (game.objects[i].place == LOC_BUILDING && PROP_IS_FOUND(i)) {
score += k - 2;
}
mxscor += k;
}
}
/* Now look at how he finished and how far he got. NDEATHS and /* Now look at how he finished and how far he got. NDEATHS and
* game.numdie tell us how well he survived. game.dflag will tell us * game.numdie tell us how well he survived. game.dflag will tell us
* if he ever got suitably deep into the cave. game.closng still * if he ever got suitably deep into the cave. game.closng still
* indicates whether he reached the endgame. And if he got as far as * indicates whether he reached the endgame. And if he got as far as
* "cave closed" (indicated by "game.closed"), then bonus is zero for * "cave closed" (indicated by "game.closed"), then bonus is zero for
* mundane exits or 133, 134, 135 if he blew it (so to speak). */ * mundane exits or 133, 134, 135 if he blew it (so to speak). */
score += (NDEATHS - game.numdie) * 10; score += (NDEATHS - game.numdie) * 10;
mxscor += NDEATHS * 10; mxscor += NDEATHS * 10;
if (mode == endgame) { if (mode == endgame) {
score += 4; score += 4;
}
mxscor += 4;
if (game.dflag != 0) {
score += 25;
}
mxscor += 25;
if (game.closng) {
score += 25;
}
mxscor += 25;
if (game.closed) {
if (game.bonus == none) {
score += 10;
} }
if (game.bonus == splatter) { mxscor += 4;
score += 25; if (game.dflag != 0) {
score += 25;
} }
if (game.bonus == defeat) { mxscor += 25;
score += 30; if (game.closng) {
score += 25;
} }
if (game.bonus == victory) { mxscor += 25;
score += 45; if (game.closed) {
if (game.bonus == none) {
score += 10;
}
if (game.bonus == splatter) {
score += 25;
}
if (game.bonus == defeat) {
score += 30;
}
if (game.bonus == victory) {
score += 45;
}
} }
} mxscor += 45;
mxscor += 45;
/* Did he come to Witt's End as he should? */ /* Did he come to Witt's End as he should? */
if (game.objects[MAGAZINE].place == LOC_WITTSEND) { if (game.objects[MAGAZINE].place == LOC_WITTSEND) {
score += 1; score += 1;
}
mxscor += 1;
/* Round it off. */
score += 2;
mxscor += 2;
/* Deduct for hints/turns/saves. Hints < 4 are special; see database desc. */
for (int i = 0; i < NHINTS; i++) {
if (game.hints[i].used) {
score = score - hints[i].penalty;
} }
} mxscor += 1;
if (game.novice) {
score -= 5;
}
if (game.clshnt) {
score -= 10;
}
score = score - game.trnluz - game.saved;
/* Return to score command if that's where we came from. */ /* Round it off. */
if (mode == scoregame) { score += 2;
rspeak(GARNERED_POINTS, score, mxscor, game.turns, game.turns); mxscor += 2;
}
return score; /* Deduct for hints/turns/saves. Hints < 4 are special; see database
* desc. */
for (int i = 0; i < NHINTS; i++) {
if (game.hints[i].used) {
score = score - hints[i].penalty;
}
}
if (game.novice) {
score -= 5;
}
if (game.clshnt) {
score -= 10;
}
score = score - game.trnluz - game.saved;
/* Return to score command if that's where we came from. */
if (mode == scoregame) {
rspeak(GARNERED_POINTS, score, mxscor, game.turns, game.turns);
}
return score;
} }
void terminate(enum termination mode) { void terminate(enum termination mode) {
/* End of game. Let's tell him all about it. */ /* End of game. Let's tell him all about it. */
int points = score(mode); int points = score(mode);
#if defined ADVENT_AUTOSAVE #if defined ADVENT_AUTOSAVE
autosave(); autosave();
#endif #endif
if (points + game.trnluz + 1 >= mxscor && game.trnluz != 0) { if (points + game.trnluz + 1 >= mxscor && game.trnluz != 0) {
rspeak(TOOK_LONG); rspeak(TOOK_LONG);
} }
if (points + game.saved + 1 >= mxscor && game.saved != 0) { if (points + game.saved + 1 >= mxscor && game.saved != 0) {
rspeak(WITHOUT_SUSPENDS); rspeak(WITHOUT_SUSPENDS);
} }
rspeak(TOTAL_SCORE, points, mxscor, game.turns, game.turns); rspeak(TOTAL_SCORE, points, mxscor, game.turns, game.turns);
for (int i = 1; i <= (int)NCLASSES; i++) { for (int i = 1; i <= (int)NCLASSES; i++) {
if (classes[i].threshold >= points) { if (classes[i].threshold >= points) {
speak(classes[i].message); speak(classes[i].message);
if (i < (int)NCLASSES) { if (i < (int)NCLASSES) {
int nxt = classes[i].threshold + 1 - points; int nxt = classes[i].threshold + 1 - points;
rspeak(NEXT_HIGHER, nxt, nxt); rspeak(NEXT_HIGHER, nxt, nxt);
} else { } else {
rspeak(NO_HIGHER); rspeak(NO_HIGHER);
} }
exit(EXIT_SUCCESS); exit(EXIT_SUCCESS);
} }
} }
rspeak(OFF_SCALE); rspeak(OFF_SCALE);
exit(EXIT_SUCCESS); exit(EXIT_SUCCESS);
} }
/* end */ /* end */