From d4a35b62df56246ef67cbe4f1eb0a24457e70dde Mon Sep 17 00:00:00 2001 From: Lukas Krickl Date: Tue, 5 Aug 2025 20:21:45 +0200 Subject: [PATCH] unit: Added basic chaser cpu script --- src/defs.s | 3 ++ src/math.s | 4 +-- src/unit_cpu.s | 82 +++++++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 86 insertions(+), 3 deletions(-) diff --git a/src/defs.s b/src/defs.s index b5f8ae0..7d5fadd 100644 --- a/src/defs.s +++ b/src/defs.s @@ -330,3 +330,6 @@ #define DD_TIME 90 #define DD_D0_TILE 0x90 #define DD_CROSS_TILE 0xA0 + +#define DISTANCE_BGTA 1 +#define DISTANCE_AGTB 0 diff --git a/src/math.s b/src/math.s index 2d1d4b0..4d90eec 100644 --- a/src/math.s +++ b/src/math.s @@ -15,7 +15,7 @@ distance: ; otherwise a simple sub will do sub a, b - ld c, 0 + ld c, DISTANCE_AGTB ret @b_gt_a: ; exchange a and b and sub @@ -23,5 +23,5 @@ distance: ld a, b ld b, c sub a, b - ld c, 1 + ld c, DISTANCE_BGTA ret diff --git a/src/unit_cpu.s b/src/unit_cpu.s index 10a5df8..f743617 100644 --- a/src/unit_cpu.s +++ b/src/unit_cpu.s @@ -1,15 +1,95 @@ +#define UNIT_SCAN_RANGE_Y MAP_H/4 +#define UNIT_SCAN_RANGE_X MAP_W/4 ; handles cpu inputs + ; chaser CPU script ; inputs: ; de: actor ; returns: ; bc: next state unit_handle_cpu_inputs: +#define MOVE_MADE scratch + ; clear move made buffer + xor a, a + ld [MOVE_MADE], a + + ; there's a change the + ; unit will just move randomly anyway + call rand + and a, 0x7F + cp a, 0 + jp z, @random_move + + ; otherwise follow player + + ; check y position + ; and follow player in y direction if player is in range + ld hl, player_unit+act_pos_y + ld a, [hl] + ld b, a ; b = player y pos + push de + ld hl, act_pos_y + add hl, de + ld a, [hl] ; a = act y pos + call distance + pop de + + ; are we in scan range? + cp a, UNIT_SCAN_RANGE_Y + jr nc, @not_in_y_range REL + cp a, 1 + jr z, @not_in_y_range REL + + ; which direction? + ld a, c + cp a, DISTANCE_BGTA + push af + call nz, unit_try_move_up + pop af + call z, unit_try_move_down + ld a, 1 + ld [MOVE_MADE], a +@not_in_y_range: + + ; check x position + ; and follow player in x direction if player is in range + ld hl, player_unit+act_pos_x + ld a, [hl] + ld b, a ; b = player x pos + push de + ld hl, act_pos_x + add hl, de + ld a, [hl] ; a = act x pos call distance + pop de + + ; are we in scan range? + cp a, UNIT_SCAN_RANGE_X + jr nc, @not_in_x_range REL + cp a, 1 + jr z, @not_in_x_range REL + + ; which direction? + ld a, c + cp a, DISTANCE_BGTA + push af + call nz, unit_try_move_left + pop af + call z, unit_try_move_right + ld a, 1 + ld [MOVE_MADE], a +@not_in_x_range: +@random_move: + + ; call random move if move was not made + ld a, [MOVE_MADE] + cp a, 0 + call z, unit_cpu_random_move - call unit_cpu_random_move +@move_made: ld bc, st_unit_delay_to_active ret +#undefine MOVE_MADE ; moves actor into a random direction -- 2.30.2