aboutsummaryrefslogtreecommitdiff
path: root/src/game/commands.c
blob: 7e0e865ce3eaa4796504604bfd33f4368a797394 (plain)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include "commands.h"
#include <string.h>

static struct cmd_res command_switch(struct game_state *state, int argc, char **argv);

struct cmd_res run_command(struct game_state *state, char *command)
{
    int argc = 0;
    char *argv[MAX_ARGS_COUNT];
    char *arg = command;
    char *space;
    int arg_length;
    while ((space = strchr(arg, ' ')) != NULL)
    {
        if (*arg != ' ')
        {
            arg_length = space - arg;
            argv[argc] = malloc(arg_length + 1);
            strncpy(argv[argc], arg, arg_length);
            argv[argc][arg_length] = 0;
            arg = space + 1;
            argc++;
        }
    }
    //Last arg
    arg_length = strlen(arg);
    argv[argc] = malloc(arg_length + 1);
    strncpy(argv[argc], arg, arg_length);
    argv[argc][arg_length] = 0;
    argc++;

    struct cmd_res response = command_switch(state, argc, argv);
    for (int i = 0; i < argc; i++)
        free(argv[i]);
    return response;
}

static struct cmd_res nothing(struct game_state *state, int argc, char **argv)
{
    struct cmd_res response;
    response.type = CRT_FAIL;
    strncpy(response.text, "There is no command you entered!", MAX_CR_TEXT_LENGTH);
    return response;
}

static struct cmd_res quit(struct game_state *state, int argc, char **argv)
{
    state->result = GR_QUIT;
    struct cmd_res response;
    response.type = CRT_QUIT;
    *(response.text) = 0;
    return response;
}

static struct cmd_res command_switch(struct game_state *state, int argc, char **argv)
{
    if (!strcmp("", *argv))
        return nothing(state, argc, argv);
    else if (!strcmp("q", *argv))
        return quit(state, argc, argv);
}