From 58e9c7ed13c7d5317f29b41765b45423be51679e Mon Sep 17 00:00:00 2001 From: Linus Probert Date: Tue, 31 Jul 2018 21:08:36 +0200 Subject: [PATCH] Fixes: #21 Complex method issue in monster.c At least this is an attempt at a fix --- src/monster.c | 69 ++++++++++++++++++++++++++++----------------------- 1 file changed, 38 insertions(+), 31 deletions(-) diff --git a/src/monster.c b/src/monster.c index 1684691..3c5c7c6 100644 --- a/src/monster.c +++ b/src/monster.c @@ -245,8 +245,8 @@ monster_drunk_walk(Monster *m, RoomMatrix *rm) } } -static void -monster_agressive_walk(Monster *m, RoomMatrix *rm) +static Direction +get_optimal_move_towards(Monster *m, RoomMatrix *rm, const Position *dest) { int x_dist, y_dist; Position mPos; @@ -261,21 +261,21 @@ monster_agressive_walk(Monster *m, RoomMatrix *rm) unsigned int nextScore = 0; switch (i) { - case UP: - next.y -= 1; - break; - case DOWN: - next.y += 1; - break; - case LEFT: - next.x -= 1; - break; - case RIGHT: - next.x += 1; - break; + case UP: + next.y -= 1; + break; + case DOWN: + next.y += 1; + break; + case LEFT: + next.x -= 1; + break; + case RIGHT: + next.x += 1; + break; } - if (position_equals(&next, &rm->playerRoomPos)) { + if (position_equals(&next, dest)) { chosenDirection = (Direction) i; break; } @@ -283,8 +283,8 @@ monster_agressive_walk(Monster *m, RoomMatrix *rm) if (!position_in_roommatrix(&next)) continue; - x_dist = abs(next.x - rm->playerRoomPos.x); - y_dist = abs(next.y - rm->playerRoomPos.y); + x_dist = abs(next.x - dest->x); + y_dist = abs(next.y - dest->y); if (rm->spaces[next.x][next.y].occupied || rm->spaces[next.x][next.y].lethal) { nextScore += 50; @@ -293,23 +293,31 @@ monster_agressive_walk(Monster *m, RoomMatrix *rm) nextScore += x_dist > y_dist ? x_dist : y_dist; if (nextScore < currentScore) { currentScore = nextScore; - chosenDirection = (Direction)i; + chosenDirection = (Direction) i; } } + return chosenDirection; +} + +static void +monster_agressive_walk(Monster *m, RoomMatrix *rm) +{ + unsigned int chosenDirection = get_optimal_move_towards(m, rm, &rm->playerRoomPos); + switch (chosenDirection) { - case UP: - move(m, rm, VECTOR2D_UP); - break; - case DOWN: - move(m, rm, VECTOR2D_DOWN); - break; - case LEFT: - move(m, rm, VECTOR2D_LEFT); - break; - case RIGHT: - move(m, rm, VECTOR2D_RIGHT); - break; + case UP: + move(m, rm, VECTOR2D_UP); + break; + case DOWN: + move(m, rm, VECTOR2D_DOWN); + break; + case LEFT: + move(m, rm, VECTOR2D_LEFT); + break; + case RIGHT: + move(m, rm, VECTOR2D_RIGHT); + break; } } @@ -324,7 +332,6 @@ monster_coward_walk(Monster *m, RoomMatrix *rm) x_dist = mPos.x - rm->playerRoomPos.x; y_dist = mPos.y - rm->playerRoomPos.y; - if (abs(x_dist) > abs(y_dist)) { if (x_dist > 0) move(m, rm, VECTOR2D_RIGHT);