Skip to content

Game State ~ How to implement a new CLI mode

emiliolevinspage edited this page May 18, 2022 · 12 revisions

When working on our run_battle function, Emilio, Nafis, and I realized we would need to switch our mode into battle mode, but we were unsure how to do so and what exactly that meant. This document goes through how to switch to the desired mode and how CLI works in each mode. We will use the battle mode as an example.

What is a mode? Mode.h contains a definition of game_mode is a struct

How does the CLI use modes?

What is a mode operation? Mode.h contains a game_mode struct definition:

/* Mode data type */
typedef struct game_mode {
    mode_type_t curr_mode;
    mode_operation *run_mode; //the mode's run function
    char* mode_ctx; //for specifying mode's context, e.g. npc_id
} game_mode_t;

curr_mode specifies the mode with a mode_type_t enum, either NORMAL, CONVERSATION, or BATTLE. run_mode is a mode_operation function. mode.h also contains a typedef of a mode operation:

typedef int mode_operation(char *str, cli_callback callback_func, 
                           void *callback_args, chiventure_ctx_t *ctx);

What is a cli_callback function? A CLI callback function prints the given string to the CLI. A callback function takes in a pointer to a Chiventure context struct, a string to be printed as a result of running this command, and additional arguments. See cli/cmd.h for more information.

How to implement a mode:

The first step in the process is adding the desired entry to the normal mode. The add_entry function will take in a command name, operation of added entry, an action type, and a lookup table.

For example, this is what adding the entry for the fight operation would look like:

add_entry("FIGHT", fight_operation, NULL, ctx->cli_ctx->table);

Now, the CLI knows to switch to battle mode when a player inputs "FIGHT <enemy". It does so with the fight operation. The fight operation is a CLI operation for starting a fight, and it will check if the enemy name that was inputting is valid. If it is, the CLI will print the beginning string of the battle and start the first turn of the battle. For different modes, the keyword will be different--for example, you can enter NPC conversation mode by typing "TALK ".

Now that the CLI has switched to the desired mode, it will run the mode with the run functions found in game-state/mode.h. For example, the run_battle_mode will now parse user input and run another turn of the fight. Once the fight is over, the mode will be switched back to regular mode.

While the battle mode was used in this example, this may be applied to all modes, such as the NPC conversation mode.

Clone this wiki locally