>我有一个程序,可以从文本文件中读取地图(障碍物,怪物,宝藏,玩家的出生点),然后玩家可以通过WASD键移动到宝藏,怪物M和障碍#挡在路上。
有些地图有 3 个或更多怪物。
为什么怪物"obj"在同一个坐标上时不吃掉玩家?
if (obj->x == player->x && obj->y == player->y) {
似乎不适用于坐标比较
void move_monsters() {
list_node *monster = monster_position;
list_node *treasure = treasure_position;
game_object *obj;
game_object *obj2;
while (monster) {
unsigned possibilities[4][2];
int position_count = 0;
obj = monster->object;
obj2 = treasure->object;
if (isMovable(obj, obj->x + 1, obj->y)) {
possibilities[position_count][0] = obj->x + 1;
possibilities[position_count][1] = obj->y;
position_count++;
}
if (isMovable(obj, obj->x - 1, obj->y)) {
possibilities[position_count][0] = obj->x - 1;
possibilities[position_count][1] = obj->y;
position_count++;
}
if (isMovable(obj, obj->x, obj->y + 1)) {
possibilities[position_count][0] = obj->x;
possibilities[position_count][1] = obj->y + 1;
position_count++;
}
if (isMovable(obj, obj->x, obj->y - 1)) {
possibilities[position_count][0] = obj->x;
possibilities[position_count][1] = obj->y - 1;
position_count++;
}
// If the monster (obj) eats the treasure (obj2), the game is over.
if (obj->x == obj2->x && obj->y == obj2->y) {
printf("GAME OVERn");
free_memory();
printf(KNRM);
exit(0);
}
// If the monster (obj) eats the player, the game is over.
if (obj->x == player->x && obj->y == player->y) {
printf("GAME OVERn");
free_memory();
printf(KNRM);
exit(0);
}
// Do nothing if no moves are available.
if (position_count) {
int target = rand() % position_count;
move_object(monster->object, possibilities[target][0], possibilities[target][1]);
}
monster = monster->next;
}
}
这些怪物相当愚蠢:当任何一个都触手可及时,它们不会移动去吃掉宝藏或玩家,只有一步之遥。玩家和任何怪物之间的碰撞只是巧合,玩家可以在怪物在下一次迭代中吃掉它之前摆脱危险。
如果这种情况从未发生,我怀疑玩家永远不会心甘情愿地遇到怪物,并且isMovable()
函数认为玩家的位置不可用,从而阻止怪物进入以吃掉玩家。