Files
silent-fh/src/item.py
T
Berger Lena 32525ccdbb feat: item
- Add function for finding a random item spawn position
2026-05-08 15:13:31 +02:00

49 lines
1.4 KiB
Python

import pygame
import random
from src.settings import (
ITEM_SPAWN_INTERVAL, ITEM_SHOPPING_TIMER, ITEM_SIZE,
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()
remaining_items = []
for item in self.items:
if item.is_expired() == False:
remaining_items.append(item)
# replace the old list with the new temp_list
self.items = remaining_items