diff --git a/src/item.py b/src/item.py index 1b24f20..4be10a6 100644 --- a/src/item.py +++ b/src/item.py @@ -5,6 +5,35 @@ from src.settings import ( COLOR_HP_BAR_YELLOW, COLOR_HP_BAR_BG ) + +# try 50 times to find a free position to spawn item +def _random_position(room_rect, blocked_rects): + attempts = 0 + max_attempts = 50 + + while attempts < max_attempts: + # generate random x/y coordinates with room boundaries + # * 2 to have a margin to walls + x = random.randint(room_rect.left + ITEM_SIZE, room_rect.right - ITEM_SIZE * 2) + y = random.randint(room_rect.top + ITEM_SIZE, room_rect.bottom - ITEM_SIZE * 2) + + # create a rect at this position for testing collision + test_rect = pygame.Rect(x, y, ITEM_SIZE, ITEM_SIZE) + blocked = False + for b in blocked_rects: + if test_rect.colliderect(b): + blocked = True + break + + # if position is not blocked, return the position + if not blocked: + return x, y + + attempts += 1 + + # no spot after 50 attempts -> return + return None + # remove expired items def update(self, room_rect, blocked_rects): now = pygame.time.get_ticks()