Vintage Computing
FIGURE 9. A “guess the number” game. FIGURE 8. Exercising the random function
with dice rolling.
conditional loop that executes (at most) once. The
function play_that_game() uses a few local variables. The
variables “number,” “tries,” and “answer” are all integer
variables. The variable “answerBuff” is an array of
characters. I left enough room in the buffer to hold up to
three digits of entered text, a linefeed, and a null byte as a
string terminator.
Note that we have created five global variables (r1, r2,
r3, r4, and the_exit). All of them are pointers to a data
structure named “room.”
In the init_rooms() function, we will allocate memory
for each of the above by invoking the malloc() function:
struct room {
struct room *north;
struct room *south;
struct room *east;
struct room *west;
char *description;
} *r1,*r2,*r3, *r4,*the exit;
the exit (struct room *) malloc(sizeof(struct
room));
the exit->description
“““““““““““““““““““““““““““““““““““““““““““““““““““““““““““““the outside of the building”;
The play_that_game() function uses a “forever” for
loop (one with no iteration condition specified). The code
explicitly uses the “break” verb to drop out of the loop
once the user guesses the correct number.
Compile guess.c and execute it:
r1 (struct room *) malloc(sizeof(struct
room));
r1->description
“““““““the main lobby”;
cc guess
Refer to Figure 9. Since the values chosen are
random, your game session will probably look a bit
different than the one here.
r2 (struct room *) malloc(sizeof(struct
room));
r2->description
“““““““the dining room”;
Later in the code after all are allocated, we
tie the directional pointers to the appropriate
Pointers, Data Structures,
and Dynamic Memory
CC65 allows for use of C data structures via the
r1->south the exit;
r1->north NULL;
r1->west r2;
r1->east r4;
“struct” keyword. Let’s consider using a struct to describe
a room in an adventure game. For our needs, a room will
simply have a description and will then have up to four
references (pointers) to other room structs. Each of the
pointers will refer to a direction to the North, South, East,
or West of the current room.
Our look() function displays the current room data
structure’s “description” string. The function then looks at
each of the four directional pointers. If any are not NULL,
that direction will show up as a visible “doorway” to
another room.
The struct definition in our program rooms.c will look
like this:
Jim Lawless has been programming professionally for
nearly 28 years. He wrote for mainstream magazines such
as Dr. Dobbs Journal and The C++ Users Journal. He has
been an adjunct faculty member of a local community
college, specializing in teaching computer programming
languages. His current specialty skills relate to JavaScript,
Java, and .NET technologies.
October 2015 57