我正在使用libtcod和c,我的移动功能不响应输入,这是调用时函数的外观
TCOD_key_t key;
move_entity(player.x, player.y, key);
这是实际的源代码
void move_entity(int x, int y, TCOD_key_t key){
TCOD_sys_check_for_event(TCOD_EVENT_KEY_PRESS, &key, NULL);
switch(key.vk){
case TCODK_UP : y--; break;
case TCODK_DOWN : y++; break;
case TCODK_RIGHT : x++; break;
case TCODK_LEFT : x--; break;
default:break;
}
}
奇怪的是,当move_entity内部的代码被复制到主函数中时,程序会响应,这里是主循环
#include "libtcod.h"
#include "move.h"
#include "entity.h"
int main(){
struct Entity player = {40, 25, '@', 100, TCOD_COLOR_LIME};
struct Entity enemy = {20, 35, '&', 50, TCOD_COLOR_RED};
TCOD_console_set_custom_font("terminal12x12_gs_ro.png", TCOD_FONT_LAYOUT_ASCII_INROW, 16, 16);
TCOD_console_init_root(80, 50, "Placeholder title", false, TCOD_RENDERER_SDL);
while(!TCOD_console_is_window_closed()){
TCOD_key_t key;
move_entity(player.x, player.y, key);
TCOD_console_clear(NULL);
TCOD_console_print(NULL, 1, 1, "Player Health:%d", player.health);
TCOD_console_print(NULL, 1, 2, "Enemy Health:%d", enemy.health);
entity_render(player.x, player.y, player.ch, player.forcol);
entity_render(enemy.x, enemy.y, enemy.ch, enemy.forcol);
TCOD_console_flush(NULL);
}
return 0;
}
我确定这只是一些愚蠢的东西,我忽略了但是它真的让我感到震惊,我很感激帮助:)
*编辑selalerer的建议在这里是我编辑的代码
在主循环中调用的代码
move_entity(&player.x, &player.y);
函数中的代码
void move_entity(int *x, int *y){
TCOD_key_t key;
TCOD_sys_wait_for_event(TCOD_EVENT_KEY_PRESS, &key, NULL, false);
switch(key.vk){
case TCODK_UP : *y--; break;
case TCODK_DOWN : *y++; break;
case TCODK_RIGHT : *x++; break;
case TCODK_LEFT : *x--; break;
default:break;
}
}
答案 0 :(得分:1)
似乎你将player.x和player.y按值传递给move_entity()函数。在此函数中对x和y所做的任何更改都是函数的本地更改,不会影响player.x和player.y。
您应该更改move_entity()函数以接收指向int的指针并将player.x和player.y的地址发送给它,以便它能够更改它们。
答案 1 :(得分:0)
void test(int *x1, int *x2) {
printf("before modif x1 = %d\n", *x1);
printf("before modif x2 = %d\n", *x2);
*x1++; // equivalent to *(x1 + 1)
(*x2)++; // equivalent to *x2 += 1;
}
int main() {
int x1 = 1;
int x2 = 1;
test(&x1, &x2);
printf("after modif x1 = %d\n", x1);
printf("after modif x2 = %d\n", x2);
return 0;
}
参见上面的C示例,为了理解发生了什么,你没有按正确的顺序表达优先级,你必须在添加1之前先取消引用,否则你要取消引用位于你的变量之后的内存空间没有效果。
Output:
before modif x1 = 1
before modif x2 = 1
after modif x1 = 1
after modif x2 = 2