elemental-on-terminal/src/main.c

145 lines
No EOL
3.3 KiB
C

#include "command.h"
#include "loader.h"
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "main.h"
// todo: spacing in combos, clean init_tables
void init_tables(hashmap *elements, hashmap *inv, hashmap *polls, int do_inv) {
load_elements(elements, "../elem_data/" combo_file, 0);
load_elements(elements, combo_file, 0) ||
load_elements(elements, "bin/" combo_file, 0);
load_elements(polls, "../elem_data/" poll_file, 2);
if (!do_inv)
return;
load_elements(inv, "../elem_data/" inv_base_file, 1) ||
load_elements(inv, inv_base_file, 1) ||
load_elements(inv, "bin/" inv_base_file, 1);
load_elements(inv, inv_file, 1);
}
int main(int argc, char *argv[]) {
char *name;
if (argc < 2) {
name = "guest";
} else {
name = argv[1];
}
hashmap *elements = hashmap_create();
hashmap *inv = hashmap_create();
hashmap *polls = hashmap_create();
char *command = calloc(MAX_BUF_LENGTH, sizeof(char));
char *command_re = calloc(MAX_BUF_LENGTH, sizeof(char));
char **sort_tmp = calloc(MAX_COMBO_LENGTH, sizeof(char **));
int wasCombination = 0;
init_tables(elements, inv, polls, 1);
printf("user:%s, welcome to Elemental on Command Line!\nType /help for commands.\n", name);
int newline = 1;
while (1) {
// todo: separate into functions
fflush(stdout);
if (newline) {
printf("\n");
}
fgets(command, MAX_BUF_LENGTH - 1, stdin);
int cl = strlen(command);
if (cl < 2) {
newline = 0;
continue;
} else {
newline = 1;
}
for (int i = 0; i < cl - 1; i++) {
command[i] = tolower(command[i]);
}
if (wasCombination && suggest_command(command, command_re, polls, name)) {
wasCombination = 0;
continue;
}
wasCombination = 0;
if (help_command(command))
continue;
if (polls_command(command, polls, elements))
continue;
if (slash_command(command, inv))
continue;
int combos = get_command(command, command_re, sort_tmp);
if (combos < 2)
continue;
int failed = 0;
for (int i = 0; i < combos; i++) {
uintptr_t result;
hashmap_get(inv, sort_tmp[i], strlen(sort_tmp[i]), &result);
if (result != 1) {
printf("You don't have %s.\n", sort_tmp[i]);
failed = 1;
continue;
}
}
if (failed)
continue;
uintptr_t result;
hashmap_get(elements, command_re, strlen(command_re), &result);
if (result == 0) {
init_tables(elements, inv, polls, 0);
hashmap_get(elements, command_re, strlen(command_re), &result);
}
if (result == 0) {
wasCombination = 1;
printf("You didn't make anything; use /suggest to suggest an element.\n");
continue;
}
char *res_str = (char *)result;
uintptr_t result2;
hashmap_get(inv, res_str, strlen(res_str), &result2);
if (result2 == 1) {
printf("You made %s, but you already have it.\n", res_str);
continue;
}
hashmap_set(inv, res_str, strlen(res_str), (uintptr_t)1, 0);
printf("You made %s!\n", res_str);
FILE *fptr;
fptr = fopen(inv_file, "a");
if (fptr == NULL)
continue;
fwrite(res_str, sizeof(char), strlen(res_str), fptr);
fwrite("\n", sizeof(char), 1, fptr);
fclose(fptr);
}
// free(command);
}