feat: item
- Add logic to spawn items at random intervals - Add mechanic to collect items with 'E' key - Refactor _random_position to a function
This commit is contained in:
+32
-9
@@ -18,7 +18,7 @@ class Item:
|
||||
# timer to store time when item appeared
|
||||
self.spawn_time = pygame.time.get_ticks()
|
||||
|
||||
# try to load sprite
|
||||
# try to load sprite with item type
|
||||
try:
|
||||
path = f"assets/items/{item_type}.png"
|
||||
self.image = pygame.image.load(path).convert_alpha()
|
||||
@@ -50,13 +50,9 @@ class Item:
|
||||
pygame.draw.rect(screen, color, draw_rect)
|
||||
pygame.draw.rect(screen, COLOR_HP_BAR_BG, draw_rect, 2)
|
||||
|
||||
class ItemManager:
|
||||
def __init__(self):
|
||||
self.items = []
|
||||
self.last_spawn_time = pygame.time.get_ticks()
|
||||
|
||||
# try 50 times to find a free position to spawn item
|
||||
def _random_position(self, room_rect, blocked_rects):
|
||||
# try 50 times to find a free position to spawn item
|
||||
def _random_position(room_rect, blocked_rects):
|
||||
attempts = 0
|
||||
max_attempts = 50
|
||||
|
||||
@@ -84,6 +80,11 @@ class ItemManager:
|
||||
return None
|
||||
|
||||
|
||||
class ItemManager:
|
||||
def __init__(self):
|
||||
self.items = []
|
||||
self.last_spawn_time = pygame.time.get_ticks()
|
||||
|
||||
# remove expired items and spawn new ones
|
||||
def update(self, room_rect, blocked_rects):
|
||||
now = pygame.time.get_ticks()
|
||||
@@ -97,9 +98,31 @@ class ItemManager:
|
||||
# replace the old list with the new temp_list
|
||||
self.items = remaining_items
|
||||
|
||||
# todo spawn logic for ned ones with random time? (in settings we can set the time range?)
|
||||
# spawn logic for new items
|
||||
if room_rect is not None:
|
||||
if now - self.last_spawn_time >= ITEM_SPAWN_INTERVAL:
|
||||
pos = _random_position(room_rect, blocked_rects)
|
||||
if pos is not None:
|
||||
x, y = pos
|
||||
item_type = random.choice(["coffee", "beer"])
|
||||
self.items.append(Item(x, y, item_type))
|
||||
|
||||
# draw active items
|
||||
self.last_spawn_time = now
|
||||
|
||||
# check if player press "e" to buy
|
||||
def check_collect(self, player_rect, keys):
|
||||
if keys[pygame.K_e]:
|
||||
for item in self.items:
|
||||
if player_rect.colliderect(item.rect):
|
||||
return item
|
||||
return None
|
||||
|
||||
# delete item from list after buying it
|
||||
def remove_item(self, item):
|
||||
if item in self.items:
|
||||
self.items.remove(item)
|
||||
|
||||
# draw all active items
|
||||
def draw(self, screen, cam_x, cam_y):
|
||||
for item in self.items:
|
||||
item.draw(screen, cam_x, cam_y)
|
||||
|
||||
Reference in New Issue
Block a user