Collab_RPG/src/events.c

114 lines
3.3 KiB
C

#include "events.h"
#include <gint/display.h>
#include <gint/keyboard.h> /*debug*/
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
void events_init_handler(EventHandler *handler) { handler->vars = 0; }
int events_bind_variable(EventHandler *handler, int *var, char *name) {
if(handler->vars < MAX_VARIABLES) {
handler->variables[handler->vars] = var;
handler->var_names[handler->vars++] = name;
} else {
return 1;
}
return 0;
}
char op_chars[OP_AMOUNT + 1] = " =+-/*%";
int _op_null(GUNUSED int a, GUNUSED int b) { return 0; }
int _op_set(GUNUSED int a, int b) { return b; }
int _op_add(int a, int b) { return a + b; }
int _op_sub(int a, int b) { return a - b; }
int _op_div(int a, int b) {
if(b == 0)
return 0;
return a / b;
}
int _op_mul(int a, int b) { return a * b; }
int _op_mod(int a, int b) {
if(b == 0)
return 0;
return a % b;
}
int (*_operations[OP_AMOUNT])(int, int) = {_op_null, _op_set, _op_add, _op_sub,
_op_div, _op_mul, _op_mod};
#define MIN(a, b) a < b ? a : b
char _message_buffer[MESSAGE_BUFFER_SZ];
char *events_parse_string(EventHandler *handler, char *message) {
size_t message_pos = 0;
char in_token = 0;
char var_name[TOKEN_MAX_SZ];
size_t name_pos = 0;
Operation var_op = OP_NULL;
char num[TOKEN_MAX_SZ];
size_t num_pos = 0;
Token tok_type = T_NULL;
char c;
size_t i, n;
int *var;
for(i = 0; i < strlen(message); i++) {
c = message[i];
if(c == '`') {
in_token = !in_token;
if(!in_token) {
if(tok_type == T_VAR_EDIT) {
/* Do the calculation */
var_name[MIN(name_pos, TOKEN_MAX_SZ)] = '\0';
num[MIN(num_pos, TOKEN_MAX_SZ)] = '\0';
for(n = 0; n < handler->vars; n++) {
if(!strcmp(var_name, handler->var_names[n])) {
var = handler->variables[n];
if(var_op) {
*var = _operations[var_op](*var, atoi(num));
}
break;
}
}
}
/* Reset everything */
tok_type = T_NULL;
name_pos = 0;
var_op = OP_NULL;
num_pos = 0;
}
} else if(!in_token) {
if(message_pos < TOKEN_MAX_SZ)
_message_buffer[message_pos++] = c;
}
if(in_token && c != ' ') {
if(tok_type == T_VAR_EDIT) {
if(var_op != OP_NULL) {
if(num_pos < TOKEN_MAX_SZ)
num[num_pos++] = c;
}
if(strchr(op_chars, c)) {
var_op = (Operation)(strchr(op_chars, c) - op_chars);
}
if(var_op == OP_NULL) {
if(name_pos < TOKEN_MAX_SZ)
var_name[name_pos++] = c;
}
}
if(c == '$') {
tok_type = T_VAR_EDIT;
}
}
}
_message_buffer[MIN(message_pos, MESSAGE_BUFFER_SZ)] = '\0';
return _message_buffer;
}