diff --git a/game.py b/game.py index c890bee..f0dc673 100644 --- a/game.py +++ b/game.py @@ -31,6 +31,7 @@ def __init__(self, **kwargs): self.npc_last_shot_times = {} self.npc_shoot_cooldown = 500 + def try_npc_shoot(self, npc): now = pygame.time.get_ticks() npc_id = id(npc) diff --git a/npc.py b/npc.py index ce4f7b3..948b93f 100644 --- a/npc.py +++ b/npc.py @@ -9,6 +9,7 @@ class NPC: def __init__(self, x, y): self.rect = pygame.Rect(x, y, 20, 20) + def update(self, **kwargs): """Updates self position according to players""" nearest_player = self.find_closest_player(self, kwargs["players"].values()) @@ -26,11 +27,6 @@ def update(self, **kwargs): def get_shot_target(self, players): return self.find_closest_player(self, players) - # def shoot(self, target): - # bullet = Bullet(self.rect.centerx, self.rect.centery, - # target.rect.centerx, target.rect.centery, - # color=(255, 0, 0)) - # self.bullets.append(bullet) def draw(self, screen): """Draws itself""" diff --git a/player.py b/player.py index 7b7f191..314c7b9 100644 --- a/player.py +++ b/player.py @@ -1,5 +1,5 @@ """Player module""" - +import math import pygame from config import PLAYER_WIDTH, PLAYER_HEIGHT, PLAYER_SPEED, SCREEN_WIDTH, SCREEN_HEIGHT @@ -20,6 +20,7 @@ def __init__(self, uid): self.is_moving = False self.facing = Facing.RIGHT + self.shoot_cooldown = 250 self.last_shot_time = pygame.time.get_ticks() @@ -59,21 +60,38 @@ def update(self, **kwargs): self.rect.x = min(self.rect.x, SCREEN_WIDTH - PLAYER_WIDTH) self.rect.y = min(self.rect.y, SCREEN_HEIGHT - PLAYER_HEIGHT) + def distance(self, rect1, rect2): + """Helper function for distance computing""" + return math.hypot(rect1.x - rect2.x, rect1.y - rect2.y) + + def find_closest_npc(self, npcs): + closest = None + min_dist = float('inf') + + for npc in npcs: + dist = self.distance(self.rect, npc.rect) + if dist < min_dist: + min_dist = dist + closest = npc + + return closest + def shoot(self, npcs): """Try to shoot, does not fire in cooldown""" now = pygame.time.get_ticks() - if now - self.last_shot_time >= self.shoot_cooldown: + target = self.find_closest_npc(npcs) + if target is None: + return None - #if target_pos is None:# todo targetting here. - target_pos = (400, 300) - + target_pos = (target.rect.centerx, target.rect.centery) bullet = Bullet(self.rect.centerx, self.rect.centery, *target_pos, color=self.color) self.last_shot_time = now return bullet + def draw(self, screen): """Draws itself""" pygame.draw.rect(screen, self.color, self.rect)