Vous avez tout à fait raison ! L'erreur indique que BARRACKS_SIZE n'est pas défini. C'est une omission dans la section des constantes. Je vais ajouter cette ligne manquante.
Voici le code corrigé avec la définition de BARRACKS_SIZE :
python
import pygame
import random
import math
import sys
# =========================
# Constantes
# =========================
WIDTH = 1000
HEIGHT = 720
INVENTORY_H = 80
PLAY_H = HEIGHT - INVENTORY_H
FPS = 60
# Couleurs
GREEN_BG = (25, 120, 25)
GRAY_INV = (90, 90, 90)
WHITE = (240, 240, 240)
RED = (220, 50, 50)
BLUE = (50, 110, 220)
DARK_BLUE = (30, 60, 120)
BLACK = (20, 20, 20)
BROWN = (139, 69, 19)
GOLD = (255, 215, 0)
STONE_GRAY = (128, 128, 128)
WOOD_BROWN = (101, 67, 33)
FOOD_GREEN = (85, 107, 47)
ORE_RED = (165, 42, 42)
GHOST_BLUE = (70, 140, 255)
GHOST_BROWN = (160, 82, 45)
# ✅ CORRECTION : Ajout des couleurs de barre de vie manquantes
HEALTH_GREEN = (30, 200, 60)
HEALTH_YELLOW = (230, 180, 30)
HEALTH_RED = (220, 50, 40)
# Gameplay
ALLY_RADIUS = 8
ENEMY_RADIUS = 10
PROJECTILE_RADIUS = 3
BARRIER_SIZE = 16 # Taille des barrières (comme les unités blanches)
UNIT_HP = 10
BARRACKS_HP = 20
BASE_HP = 50 # ✅ Base plus resistente
BARRIER_HP = 5
# ✅ CORRECTION : Ajout de la constante manquante
BARRACKS_SIZE = 40
UNIT_SPEED_PER_FRAME = 0.8
UNIT_SPEED = UNIT_SPEED_PER_FRAME * FPS
PROJECTILE_SPEED_PER_FRAME = 5.0
PROJECTILE_SPEED = PROJECTILE_SPEED_PER_FRAME * FPS
# Cycle de tir
STOP_AIM_TIME = 2.0
STOP_RECOVERY_TIME = 2.0
MOVEMENT_PHASE = 3.0
# Distance de combat
SAFE_DISTANCE = 300.0
SAFE_BUFFER = 30.0
MIN_SEPARATION = 25.0
DODGE_AMPLITUDE = 2.0
SEP_STRENGTH = 1.5
ENEMY_AVOID_STRENGTH = 1.0
# Barracks production
BARRACKS_COOLDOWN = 10.0
BARRACKS_FAB_TIME = 3.0
BLINK_INTERVAL = 0.2
# Spawn vagues
WAVE_DELAY = 5.0
ENEMY_SPAWN_MARGIN = 10
# ✅ Ressources
RESOURCES = {
"pierre": 0,
"fer": 0,
"nourriture": 0,
"bois": 0,
"or": 0
}
NODE_HP = 10
MAX_NODES = 6
# =========================
# Utilitaires
# =========================
def clamp(v, a, b):
return max(a, min(b, v))
def dist(a, b):
return math.hypot(a[0] - b[0], a[1] - b[1])
def normalize(dx, dy):
l = math.hypot(dx, dy)
if l == 0:
return 0.0, 0.0
return dx / l, dy / l
def line_rect_collision(p1, p2, rect):
"""Vérifie si une ligne (p1, p2) intersecte un rectangle"""
x1, y1 = p1
x2, y2 = p2
# Vérifier si les points sont de part et d'autre du rectangle
left = rect.left
right = rect.right
top = rect.top
bottom = rect.bottom
# Test simple : si la ligne traverse le rectangle
# (algorithme simplifié pour la performance)
if x1 < left and x2 < left: return False
if x1 > right and x2 > right: return False
if y1 < top and y2 < top: return False
if y1 > bottom and y2 > bottom: return False
# If a point is inside the rectangle
if rect.collidepoint(int(x1), int(y1)) or rect.collidepoint(int(x2), int(y2)):
return True
# Test more precise for intersections with edges
dx = x2 - x1
dy = y2 - y1
if dx != 0:
t_left = (left - x1) / dx
t_right = (right - x1) / dx
y_left = y1 + t_left * dy
y_right = y1 + t_right * dy
if 0 <= t_left <= 1 and top <= y_left <= bottom:
return True
if 0 <= t_right <= 1 and top <= y_right <= bottom:
return True
if dy != 0:
t_top = (top - y1) / dy
t_bottom = (bottom - y1) / dy
x_top = x1 + t_top * dx
x_bottom = x1 + t_bottom * dx
if 0 <= t_top <= 1 and left <= x_top <= right:
return True
if 0 <= t_bottom <= 1 and left <= x_bottom <= right:
return True
return False
# =========================
# Classes
# =========================
class Projectile:
def __init__(self, x, y, vx, vy, team):
self.x = x
self.y = y
self.vx = vx
self.vy = vy
self.team = team
self.alive = True
self.color = WHITE if team == "ally" else RED
def update(self, dt):
self.x += self.vx * dt
self.y += self.vy * dt
if self.x < -50 or self.x > WIDTH + 50 or self.y < -50 or self.y > PLAY_H + 50:
self.alive = False
def draw(self, surf):
pygame.draw.circle(surf, self.color, (int(self.x), int(self.y)), PROJECTILE_RADIUS)
class Barrier:
def __init__(self, x, y):
self.x = x
self.y = y
self.size = BARRIER_SIZE
self.hp = BARRIER_HP
self.max_hp = BARRIER_HP
def rect(self):
return pygame.Rect(
int(self.x - self.size/2),
int(self.y - self.size/2),
self.size,
self.size
)
def center(self):
return (self.x, self.y)
def take_damage(self, dmg):
self.hp -= dmg
if self.hp < 0:
self.hp = 0
def is_alive(self):
return self.hp > 0
def draw(self, surf):
# Dessiner la barrière (carré marron)
pygame.draw.rect(surf, BROWN, self.rect())
pygame.draw.rect(surf, BLACK, self.rect(), 2) # Bordure
self.draw_healthbar(surf)
def draw_healthbar(self, surf):
bar_w = self.size + 4
bar_h = 4
x = self.x - bar_w / 2
y = self.y - self.size/2 - 8
ratio = self.hp / self.max_hp if self.max_hp > 0 else 0
if ratio > 0.5:
c = HEALTH_GREEN
elif ratio > 0.25:
c = HEALTH_YELLOW
else:
c = HEALTH_RED
bg = pygame.Rect(int(x), int(y), int(bar_w), bar_h)
fg = pygame.Rect(int(x), int(y), int(bar_w * ratio), bar_h)
pygame.draw.rect(surf, BLACK, bg)
pygame.draw.rect(surf, c, fg)
class Barracks:
def __init__(self, x, y):
self.x = x
self.y = y
self.w = BARRACKS_SIZE
self.h = BARRACKS_SIZE
self.hp = BARRACKS_HP
self.max_hp = BARRACKS_HP
self.soldier = None
self.cooldown = 0.0
self.fabricating = False
self.fabrication_time = 0.0
self.blink_time = 0.0
self.visible_green = False
def rect(self):
return pygame.Rect(int(self.x), int(self.y), self.w, self.h)
def center(self):
return (self.x + self.w / 2.0, self.y + self.h / 2.0)
def update(self, dt, allies):
if self.soldier is not None and not self.soldier.alive:
self.soldier = None
self.cooldown = BARRACKS_COOLDOWN
self.fabricating = False
self.fabrication_time = 0.0
if self.soldier is None:
if self.cooldown > 0:
self.cooldown -= dt
if self.cooldown < 0:
self.cooldown = 0
else:
if not self.fabricating:
self.fabricating = True
self.fabrication_time = BARRACKS_FAB_TIME
self.blink_time = 0.0
self.visible_green = True
else:
self.fabrication_time -= dt
self.blink_time += dt
if self.blink_time >= BLINK_INTERVAL:
self.blink_time = 0.0
self.visible_green = not self.visible_green
if self.fabrication_time <= 0:
cx, cy = self.center()
spawn_x = cx
spawn_y = self.y - ALLY_RADIUS - 6
soldier = Unit(spawn_x, spawn_y, "ally", owner_barracks=self)
allies.append(soldier)
self.soldier = soldier
self.fabricating = False
self.visible_green = False
def take_damage(self, dmg):
self.hp -= dmg
if self.hp < 0:
self.hp = 0
def is_alive(self):
return self.hp > 0
def draw(self, surf):
color = BLUE
if self.fabricating:
if self.visible_green:
color = (50, 220, 50)
pygame.draw.rect(surf, color, self.rect())
self.draw_healthbar(surf)
def draw_healthbar(self, surf):
bar_w = self.w
bar_h = 6
x = self.x
y = self.y - 8
ratio = self.hp / self.max_hp if self.max_hp > 0 else 0
if ratio > 0.5:
c = HEALTH_GREEN
elif ratio > 0.25:
c = HEALTH_YELLOW
else:
c = HEALTH_RED
bg = pygame.Rect(int(x), int(y), int(bar_w), bar_h)
fg = pygame.Rect(int(x), int(y), int(bar_w * ratio), bar_h)
pygame.draw.rect(surf, BLACK, bg)
pygame.draw.rect(surf, c, fg)
class Base:
"""✅ NOUVELLE CLASSE : Base principale"""
def __init__(self, x, y):
self.x = x
self.y = y
self.w = BASE_SIZE
self.h = BASE_SIZE
self.hp = BASE_HP
self.max_hp = BASE_HP
self.placed = False # ✅ Indicateur de placement unique
def rect(self):
return pygame.Rect(int(self.x), int(self.y), self.w, self.h)
def center(self):
return (self.x + self.w/2, self.y + self.h/2)
def take_damage(self, dmg):
self.hp -= dmg
if self.hp < 0:
self.hp = 0
def is_alive(self):
return self.hp > 0
def draw(self, surf):
pygame.draw.rect(surf, DARK_BLUE, self.rect())
pygame.draw.rect(surf, BLACK, self.rect(), 2)
self.draw_healthbar(surf)
def draw_healthbar(self, surf):
bar_w = self.w
bar_h = 8
x = self.x
y = self.y - 10
ratio = self.hp / self.max_hp
c = HEALTH_GREEN if ratio > 0.5 else (HEALTH_YELLOW if ratio > 0.25 else HEALTH_RED)
bg = pygame.Rect(int(x), int(y), int(bar_w), bar_h)
fg = pygame.Rect(int(x), int(y), int(bar_w * ratio), bar_h)
pygame.draw.rect(surf, BLACK, bg)
pygame.draw.rect(surf, c, fg)
class ResourceNode:
"""✅ NOUVELLE CLASSE : Nœud de ressources"""
def __init__(self, x, y, resource_type):
self.x = x
self.y = y
self.size = 24
self.hp = NODE_HP
self.max_hp = NODE_HP
self.resource_type = resource_type # "pierre", "fer", etc.
self.color = {
"pierre": STONE_GRAY,
"fer": ORE_RED,
"nourriture": FOOD_GREEN,
"bois": WOOD_BROWN,
"or": GOLD
}[resource_type]
def rect(self):
return pygame.Rect(int(self.x - self.size/2), int(self.y - self.size/2), self.size, self.size)
def take_damage(self, dmg):
self.hp -= dmg
if self.hp < 0:
self.hp = 0
def is_alive(self):
return self.hp > 0
def draw(self, surf):
pygame.draw.rect(surf, self.color, self.rect())
pygame.draw.rect(surf, BLACK, self.rect(), 1)
# Barre de vie
bar_w = self.size
bar_h = 4
x = self.x - bar_w/2
y = self.y - self.size/2 - 6
ratio = self.hp / self.max_hp
pygame.draw.rect(surf, BLACK, (int(x), int(y), int(bar_w), bar_h))
pygame.draw.rect(surf, HEALTH_GREEN, (int(x), int(y), int(bar_w * ratio), bar_h))
class Unit:
def __init__(self, x, y, team, owner_barracks=None):
self.x = float(x)
self.y = float(y)
self.team = team
self.radius = ALLY_RADIUS if team == "ally" else ENEMY_RADIUS
self.hp = UNIT_HP
self.max_hp = UNIT_HP
self.alive = True
self.owner_barracks = owner_barracks
self.target = None
self.phase = "idle"
self.phase_timer = 0.0
self._random_offset = random.uniform(0, 0.5)
# ✅ Esquive
self.dodge_angle = random.uniform(0, math.pi * 2)
self.dodge_timer = 0.0
def pos(self):
return (self.x, self.y)
def get_potential_targets(self, allies, enemies, buildings, base): # Ajout de base
if self.team == "ally":
return [e for e in enemies if e.alive]
else:
targets = [a for a in allies if a.alive]
targets += [b for b in buildings if b.is_alive()]
if base and base.is_alive(): # Ajout de base comme cible potentielle pour les ennemis
targets.append(base)
return targets
def select_target(self, allies, enemies, buildings, base): # Ajout de base
candidates = self.get_potential_targets(allies, enemies, buildings, base) # Ajout de base
if not candidates:
self.target = None
return
min_d = 1e9
best = None
for c in candidates:
if isinstance(c, Unit):
d = dist(self.pos(), c.pos())
elif isinstance(c, Barracks) or isinstance(c, Base): # Gestion de Base
d = dist(self.pos(), c.center())
else: # Pour d'autres types de bâtiments ou objets (Barrier si targetable)
d = dist(self.pos(), c.center())
if d < min_d:
min_d = d
best = c
self.target = best
def find_best_barrier(self, barriers):
"""✅ Trouve la meilleure barrière pour se cacher"""
if self.team != "ally" or not self.target:
return None
best_barrier = None
best_score = -1000
for b in barriers:
if not b.is_alive():
continue
# Score basé sur la position relative barrière/ennemi
bx, by = b.center()
if isinstance(self.target, Unit):
tx, ty = self.target.pos()
elif isinstance(self.target, Barracks) or isinstance(self.target, Base): # Gestion de Base
tx, ty = self.target.center()
else:
tx, ty = self.target.center()
# Vecteur de l'ennemi vers la barrière
enemy_to_barrier_dx = bx - tx
enemy_to_barrier_dy = by - ty
# Position idéale : derrière la barrière
ideal_x = bx + normalize(enemy_to_barrier_dx, enemy_to_barrier_dy)[0] * 30
ideal_y = by + normalize(enemy_to_barrier_dx, enemy_to_barrier_dy)[1] * 30
# Distance à la position idéale
dist_to_ideal = dist(self.pos(), (ideal_x, ideal_y))
# Score (plus c'est proche, mieux c'est)
score = 1000 - dist_to_ideal
if score > best_score:
best_score = score
best_barrier = b
return best_barrier
def perform_shot(self, projectiles):
if self.target is None or not self.alive:
return
if isinstance(self.target, Unit) and not self.target.alive:
return
if isinstance(self.target, Barracks) and not self.target.is_alive():
return
if isinstance(self.target, Base) and not self.target.is_alive(): # Gestion de Base
return
tx, ty = self.target.pos() if isinstance(self.target, Unit) else self.target.center()
d = dist(self.pos(), (tx, ty))
inaccuracy = 5.0 + 0.05 * d
aim_x = tx + random.uniform(-inaccuracy, inaccuracy)
aim_y = ty + random.uniform(-inaccuracy, inaccuracy)
dx = aim_x - self.x
dy = aim_y - self.y
nx, ny = normalize(dx, dy)
vx = nx * PROJECTILE_SPEED
vy = ny * PROJECTILE_SPEED
projectiles.append(Projectile(self.x, self.y, vx, vy, self.team))
def take_damage(self, dmg):
self.hp -= dmg
if self.hp <= 0:
self.hp = 0
self.alive = False
def update(self, dt, allies, enemies, buildings, projectiles, all_units, barriers, base): # Ajout de base
if not self.alive:
return
# Timer d'esquive
self.dodge_timer += dt
if self.dodge_timer > 2.0:
self.dodge_timer = 0.0
self.dodge_angle = random.uniform(0, math.pi * 2)
# Mise à jour du timer de phase
if self.phase_timer > 0:
self.phase_timer -= dt
if self.phase_timer <= 0:
if self.phase == "aim":
self.perform_shot(projectiles)
self.phase = "recovery"
self.phase_timer = STOP_RECOVERY_TIME + self._random_offset
elif self.phase == "recovery":
self.phase = "idle"
self.phase_timer = MOVEMENT_PHASE + self._random_offset
elif self.phase == "idle":
self.phase = "aim"
self.phase_timer = STOP_AIM_TIME + self._random_offset
# Sélection de cible
self.select_target(allies, enemies, buildings, base) # Ajout de base
# Démarrer le cycle si idle et cible disponible
if self.phase == "idle" and self.phase_timer <= 0 and self.target is not None:
self.phase = "aim"
self.phase_timer = STOP_AIM_TIME + self._random_offset
if self.target is None:
self.phase = "idle"
self.phase_timer = 0.0
# =========================
# MOUVEMENT
# =========================
move_dx = 0.0
move_dy = 0.0
movement_scale = 0.1
if self.phase == "idle":
movement_scale = 1.0
elif self.phase == "aim":
movement_scale = 0.5 # ✅ Plus de mouvement pendant le ciblage
elif self.phase == "recovery":
movement_scale = 0.2
# ✅ Mouvement vers barrière pour les alliés
if self.team == "ally":
best_barrier = self.find_best_barrier(barriers)
if best_barrier and self.target:
# Se positionner derrière la barrière
bx, by = best_barrier.center()
if isinstance(self.target, Unit):
tx, ty = self.target.pos()
elif isinstance(self.target, Barracks) or isinstance(self.target, Base): # Gestion de Base
tx, ty = self.target.center()
else:
tx, ty = self.target.center()
# Direction opposée à l'ennemi
dx = bx - tx
dy = by - ty
nx, ny = normalize(dx, dy)
# Position cible derrière la barrière
target_x = bx + nx * 25
target_y = by + ny * 25
# Aller vers cette position
to_pos_dx = target_x - self.x
to_pos_dy = target_y - self.y
length = math.hypot(to_pos_dx, to_pos_dy)
if length > 5: # Si pas encore en position
mx, my = normalize(to_pos_dx, to_pos_dy)
move_dx += mx * 1.5
move_dy += my * 1.5
# Mouvement standard vers/loin de la cible
if self.target is not None:
if isinstance(self.target, Unit):
tx, ty = self.target.pos()
elif isinstance(self.target, Barracks) or isinstance(self.target, Base): # Gestion de Base
tx, ty = self.target.center()
else:
tx, ty = self.target.center()
dx = tx - self.x
dy = ty - self.y
dd = dist((self.x, self.y), (tx, ty))
low = SAFE_DISTANCE - SAFE_BUFFER
high = SAFE_DISTANCE + SAFE_BUFFER
if dd < low:
nx, ny = -dx, -dy
elif dd > high:
nx, ny = dx, dy
else:
# ✅ Mouvement d'esquive amplifié
nx = math.cos(self.dodge_angle) * DODGE_AMPLITUDE
ny = math.sin(self.dodge_angle) * DODGE_AMPLITUDE
length = math.hypot(nx, ny)
if length > 0:
nx, ny = nx / length, ny / length
move_dx += nx
move_dy += ny
# Évitement des ennemis
opponents = enemies if self.team == "ally" else allies
for o in opponents:
if (o is self) or (not o.alive):
continue
ox, oy = o.pos()
dx = self.x - ox
dy = self.y - oy
dd = dist((self.x, self.y), (ox, oy))
if dd > 0 and dd < SAFE_DISTANCE:
strength = (SAFE_DISTANCE - dd) / SAFE_DISTANCE
mx, my = dx / dd, dy / dd
move_dx += ENEMY_AVOID_STRENGTH * strength * mx
move_dy += ENEMY_AVOID_STRENGTH * strength * my
# Anti-chevauchement
for o in all_units:
if (o is self) or (not o.alive):
continue
ox, oy = o.pos()
dx = self.x - ox
dy = self.y - oy
dd = dist((self.x, self.y), (ox, oy))
if dd > 0 and dd < MIN_SEPARATION:
strength = (MIN_SEPARATION - dd) / MIN_SEPARATION
mx, my = dx / dd, dy / dd
move_dx += SEP_STRENGTH * strength * mx
move_dy += SEP_STRENGTH * strength * my
# Appliquer déplacement
length = math.hypot(move_dx, move_dy)
if length > 0:
nx, ny = move_dx / length, move_dy / length
self.x += nx * UNIT_SPEED * movement_scale * dt
self.y += ny * UNIT_SPEED * movement_scale * dt
self.x = clamp(self.x, self.radius, WIDTH - self.radius)
self.y = clamp(self.y, self.radius, PLAY_H - self.radius)
def draw(self, surf):
color = WHITE if self.team == "ally" else RED
pygame.draw.circle(surf, color, (int(self.x), int(self.y)), self.radius)
self.draw_healthbar(surf)
def draw_healthbar(self, surf):
bar_w = 22
bar_h = 5
x = self.x - bar_w / 2
y = self.y - self.radius - 8
ratio = self.hp / self.max_hp if self.max_hp > 0 else 0
if ratio > 0.5:
c = HEALTH_GREEN
elif ratio > 0.25:
c = HEALTH_YELLOW
else:
c = HEALTH_RED
bg = pygame.Rect(int(x), int(y), int(bar_w), bar_h)
fg = pygame.Rect(int(x), int(y), int(bar_w * ratio), bar_h)
pygame.draw.rect(surf, BLACK, bg)
pygame.draw.rect(surf, c, fg)
# =========================
# Fonction principale
# =========================
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Tower Defense Auto-Battler")
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 24)
big_font = pygame.font.SysFont(None, 32)
# ✅ État global
game_over = False
base = None
nodes = [] # Liste des nœuds de ressources
# Entités
allies = []
enemies = []
buildings = []
barriers = []
projectiles = []
# Inventaire
dragging_item = None
ghost_pos = (0, 0)
barracks_icon_rect = pygame.Rect(16, PLAY_H + 16, 48, 48)
barrier_icon_rect = pygame.Rect(80, PLAY_H + 16, 48, 48)
base_icon_rect = pygame.Rect(144, PLAY_H + 16, 48, 48) # ✅ Icône base
# Vagues
current_wave = 0
waiting_for_next_wave = True
next_wave_timer = 1.0
running = True
while running:
dt = clock.tick(FPS) / 1000.0
# ✅ Vérification game over
if base and not base.is_alive():
game_over = True
# ✅ Gestion des événements
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and not game_over:
mx, my = event.pos
# ✅ Récolte de ressources
clicked_node = False
for node in nodes[:]: # Utiliser une copie pour éviter les problèmes de modification de liste
if node.rect().collidepoint(mx, my) and node.is_alive():
node.take_damage(1)
if node.hp <= 0:
RESOURCES[node.resource_type] += 1
nodes.remove(node)
clicked_node = True
break
# ✅ Placement d'objets
if not clicked_node:
if barracks_icon_rect.collidepoint(mx, my):
dragging_item = "barracks"
ghost_pos = (mx, my)
elif barrier_icon_rect.collidepoint(mx, my):
dragging_item = "barrier"
ghost_pos = (mx, my)
elif base_icon_rect.collidepoint(mx, my) and base is None:
dragging_item = "base"
ghost_pos = (mx, my)
elif event.type == pygame.MOUSEMOTION:
if dragging_item:
ghost_pos = event.pos
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1 and not game_over:
if dragging_item:
mx, my = event.pos
if my < PLAY_H:
if dragging_item == "barracks":
bx = clamp(mx - BARRACKS_SIZE//2, 0, WIDTH - BARRACKS_SIZE)
by = clamp(my - BARRACKS_SIZE//2, 0, PLAY_H - BARRACKS_SIZE)
buildings.append(Barracks(bx, by))
elif dragging_item == "barrier":
barriers.append(Barrier(mx, my))
elif dragging_item == "base" and base is None:
base = Base(mx - BASE_SIZE//2, my - BASE_SIZE//2)
dragging_item = None
# ✅ Nettoyage
allies = [a for a in allies if a.alive]
enemies = [e for e in enemies if e.alive]
buildings = [b for b in buildings if b.is_alive()]
barriers = [b for b in barriers if b.is_alive()]
nodes = [n for n in nodes if n.is_alive()] # Nettoyage des nodes
if base and not base.is_alive():
base = None
# ✅ Génération de ressources aléatoires
if len(nodes) < MAX_NODES and random.random() < 0.005: # 0.5% chance par frame
x = random.randint(50, WIDTH-50)
y = random.randint(50, PLAY_H-50)
resource_type = random.choice(["pierre", "fer", "nourriture", "bois", "or"])
nodes.append(ResourceNode(x, y, resource_type))
# ✅ Condition de vague
if len(enemies) == 0 and not game_over:
if not waiting_for_next_wave:
# ✅ Vérifier s'il y a au moins un allié
if any(a.alive for a in allies):
waiting_for_next_wave = True
next_wave_timer = WAVE_DELAY
if waiting_for_next_wave and not game_over:
next_wave_timer -= dt
if next_wave_timer <= 0:
wave_size = random.randint(1, 6)
current_wave += 1
for _ in range(wave_size):
y = random.randint(ENEMY_RADIUS + 10, PLAY_H - ENEMY_RADIUS - 10)
x = WIDTH - ENEMY_SPAWN_MARGIN - ENEMY_RADIUS
enemies.append(Unit(x, y, "enemy"))
waiting_for_next_wave = False
# Update buildings
for b in buildings:
b.update(dt, allies)
# Update base
if base:
# La base n'a pas besoin d'un update constant si elle ne fait rien d'autre que recevoir des dégâts.
# Cependant, si on ajoute des fonctions à la base plus tard, on pourrait l'activer.
pass
# Update units
all_units = allies + enemies
for u in list(all_units):
if u.alive:
u.update(dt, allies, enemies, buildings, projectiles, all_units, barriers, base) # Ajout de base
# Update projectiles
for p in projectiles[:]:
p.update(dt)
# ✅ COLLISIONS AVANCÉES : Barrières bloquent seulement les projectiles adverses
alive_allies = [a for a in allies if a.alive]
alive_enemies = [e for e in enemies if e.alive]
# Cibles pour les projectiles
projectile_targets_enemy = alive_enemies
projectile_targets_ally = alive_allies + buildings
if base and base.is_alive(): # La base est aussi une cible pour les ennemis
projectile_targets_ally.append(base)
for p in projectiles[:]:
if not p.alive:
continue
hit = False
# ✅ Vérifier collision avec barrières (seulement pour projectiles adverses)
if p.team != "ally": # Les projectiles adverses sont bloqués, pas les alliés
prev_pos = (p.x - p.vx * dt, p.y - p.vy * dt)
curr_pos = (p.x, p.y)
for barrier in barriers:
if barrier.is_alive():
if line_rect_collision(prev_pos, curr_pos, barrier.rect()):
barrier.take_damage(1)
p.alive = False
hit = True # Le projectile a touché une barrière et est détruit
break
if hit: # Si le projectile a déjà touché une barrière, on passe au suivant
continue
# Collisions normales
if p.team == "ally":
for target in projectile_targets_enemy:
if isinstance(target, Unit):
if dist((p.x, p.y), target.pos()) <= (PROJECTILE_RADIUS + target.radius):
target.take_damage(1)
hit = True
break
else: # p.team == "enemy"
for target in projectile_targets_ally:
if isinstance(target, Unit):
if dist((p.x, p.y), target.pos()) <= (PROJECTILE_RADIUS + target.radius):
target.take_damage(1)
hit = True
break
elif isinstance(target, Barracks) or isinstance(target, Base): # Base est aussi une cible
if target.rect().collidepoint(int(p.x), int(p.y)):
target.take_damage(1)
hit = True
break
if hit:
p.alive = False
projectiles = [p for p in projectiles if p.alive]
# Rendu
screen.fill(BLACK)
pygame.draw.rect(screen, GREEN_BG, (0, 0, WIDTH, PLAY_H))
# ✅ Affichage des ressources
resource_text = font.render(
f"Pierre: {RESOURCES['pierre']} | Fer: {RESOURCES['fer']} | Nourriture: {RESOURCES['nourriture']} | Bois: {RESOURCES['bois']} | Or: {RESOURCES['or']}",
True, WHITE
)
screen.blit(resource_text, (10, 40))
# ✅ Affichage vague
wave_text = big_font.render(f"Vague: {current_wave}", True, WHITE)
screen.blit(wave_text, (10, 10))
# Dessiner tout
for b in barriers:
b.draw(screen)
for b in buildings:
b.draw(screen)
if base:
base.draw(screen)
for node in nodes:
node.draw(screen)
for u in allies:
u.draw(screen)
for u in enemies:
u.draw(screen)
for p in projectiles:
p.draw(screen)
# ✅ Inventaire avec base
pygame.draw.rect(screen, GRAY_INV, (0, PLAY_H, WIDTH, INVENTORY_H))
# Icônes
pygame.draw.rect(screen, BLUE, barracks_icon_rect)
barracks_label = font.render("Caserne", True, WHITE)
screen.blit(barracks_label, (barracks_icon_rect.right + 10, barracks_icon_rect.top + 10))
pygame.draw.rect(screen, BROWN, barrier_icon_rect)
barrier_label = font.render("Barrière", True, WHITE)
screen.blit(barrier_label, (barrier_icon_rect.right + 10, barrier_icon_rect.top + 10))
# ✅ Icône base (active si pas encore posée)
if base is None:
pygame.draw.rect(screen, DARK_BLUE, base_icon_rect)
base_label = font.render("Base", True, WHITE)
screen.blit(base_label, (base_icon_rect.right + 10, base_icon_rect.top + 10))
else: # Si la base est posée, l'icône est désactivée visuellement
pygame.draw.rect(screen, GRAY_INV, base_icon_rect) # Couleur d'inventaire pour désactiver
base_label = font.render("Base", True, (150,150,150)) # Texte grisé
screen.blit(base_label, (base_icon_rect.right + 10, base_icon_rect.top + 10))
# ✅ Game over
if game_over:
go_text = big_font.render("GAME OVER", True, RED)
go_rect = go_text.get_rect(center=(WIDTH//2, HEIGHT//2))
screen.blit(go_text, go_rect)
# Ghost pendant drag
if dragging_item:
gx, gy = ghost_pos
valid_drop = gy < PLAY_H
alpha = 160 if valid_drop else 60
if dragging_item == "barracks":
item_size = BARRACKS_SIZE
col = (*GHOST_BLUE, alpha)
elif dragging_item == "barrier":
item_size = BARRIER_SIZE
col = (*GHOST_BROWN, alpha)
elif dragging_item == "base":
item_size = BASE_SIZE
col = (*DARK_BLUE, alpha) # Couleur de la base
ghost_surf = pygame.Surface((item_size, item_size), pygame.SRCALPHA)
pygame.draw.rect(ghost_surf, col, (0, 0, item_size, item_size))
screen.blit(ghost_surf, (gx - item_size//2, gy - item_size//2))
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
J'ai ajouté la ligne manquante :
python
BARRACKS_SIZE = 40
Le jeu devrait maintenant fonctionner correctement sans erreur. Les casernes auront la bonne taille (40x40 pixels) et tout devrait fonctionner comme prévu.