Collab_RPG/src/events.c

101 lines
2.2 KiB
C
Raw Normal View History

2024-07-20 16:53:13 +02:00
#include <stdlib.h>
#include <string.h>
#include "events.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(int a, int b) {
return 0;
}
int _op_set(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
};
char _message_buffer[MESSAGE_BUFFER_SZ];
char *events_parse_string(EventHandler *handler, char *message) {
char *message_ptr = _message_buffer;
char in_op = message[0] == '`';
char *token;
int *var;
unsigned int n, i;
size_t len;
char *sign;
size_t left;
size_t size;
if(!strlen(message)) return message;
for(token=strtok(message,"`");token!=NULL;in_op=!in_op,
token=strtok(NULL,"`")){
len = strlen(token);
if(in_op && len){
sign = NULL;
for(n=0;sign==NULL&&n<OP_AMOUNT;n++,sign=strchr(token,op_chars[n]));
if(sign != NULL){
var = NULL;
for(i=0;i<handler->vars;i++){
if(!strncmp(token+1, handler->var_names[i], sign-token-1)){
var = handler->variables[i];
break;
}
}
if(var){
*var = _operations[n](*var, atoi(sign+1));
}
}
}else{
left = (_message_buffer+MESSAGE_BUFFER_SZ)-message_ptr;
size = len < left ? len : left;
memcpy(message_ptr, token, size);
message_ptr += size;
}
}
*message_ptr = '\0';
return _message_buffer;
}