Вот код реалистичного тактического симулятора сражений полиции и преступников на pygame:
python Copy code
import pygame
import random
import math
from enum import Enum
from collections import deque
# Инициализация Pygame
pygame.init()
# Константы
SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 800
TILE_SIZE = 20
GRID_WIDTH = SCREEN_WIDTH // TILE_SIZE
GRID_HEIGHT = SCREEN_HEIGHT // TILE_SIZE
# Цвета
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 100, 255)
RED = (255, 0, 0)
GRAY = (128, 128, 128)
GREEN = (0, 255, 0)
YELLOW = (255, 255, 0)
DARK_GRAY = (64, 64, 64)
# Состояния юнитов
class UnitState(Enum):
PATROLLING = 1
PURSUING = 2
FIGHTING = 3
TAKING_COVER = 4
FLANKING = 5
RETREATING = 6
class Tile:
def __init__(self, x, y):
self.x = x
self.y = y
self.wall = False
self.cover = False
class Unit:
def __init__(self, x, y, team):
self.x = x
self.y = y
self.team = team # 'police' или 'criminal'
self.health = 100
self.max_health = 100
self.state = UnitState.PATROLLING
self.target = None
self.path = []
self.shoot_cooldown = 0
self.vision_range = 15
self.shoot_range = 10
self.accuracy = 0.7 if team == 'police' else 0.5
self.damage = 20
self.speed = 0.5 if team == 'police' else 0.6
self.move_timer = 0
self.in_cover = False
self.last_seen_enemy = None
self.patrol_target = None
self.retreat_threshold = 30
self.squad_leader = None
self.squad_members = []
def update(self, units, grid):
self.shoot_cooldown = max(0, self.shoot_cooldown - 1)
self.move_timer += self.speed
# Обновление состояния
self.update_state(units, grid)
# Действия в зависимости от состояния
if self.state == UnitState.PATROLLING:
self.patrol(grid)
elif self.state == UnitState.PURSUING:
self.pursue_enemy(grid)
elif self.state == UnitState.FIGHTING:
self.fight(units, grid)
elif self.state == UnitState.TAKING_COVER:
self.take_cover(grid, units)
elif self.state == UnitState.FLANKING:
self.flank_enemy(grid, units)
elif self.state == UnitState.RETREATING:
self.retreat(grid, units)
def update_state(self, units, grid):
enemies = self.get_visible_enemies(units, grid)
allies = self.get_nearby_allies(units)
# Логика смены состояний
if self.health < self.retreat_threshold:
self.state = UnitState.RETREATING
elif enemies:
self.last_seen_enemy = enemies[0]
if self.distance_to(enemies[0]) <= self.shoot_range:
# Решение: сражаться, прятаться или фланговать
if self.should_take_cover(enemies, allies, grid):
self.state = UnitState.TAKING_COVER
elif self.should_flank(enemies, allies):
self.state = UnitState.FLANKING
else:
self.state = UnitState.FIGHTING
self.target = enemies[0]
else:
self.state = UnitState.PURSUING
self.target = enemies[0]
elif self.last_seen_enemy and self.state != UnitState.PATROLLING:
# Преследовать последнее известное местоположение
self.state = UnitState.PURSUING
else:
self.state = UnitState.PATROLLING
def should_take_cover(self, enemies, allies, grid):
# Прятаться если враги превосходят числом или мало здоровья
enemy_count = len(enemies)
ally_count = len(allies) + 1
return (enemy_count > ally_count * 1.5 or self.health < 50) and self.find_nearest_cover(grid)
def should_flank(self, enemies, allies):
# Фланговать если есть союзники для отвлечения
return len(allies) >= 2 and random.random() < 0.3
def patrol(self, grid):
if not self.patrol_target or (self.x == self.patrol_target[0] and self.y == self.patrol_target[1]):
# Выбрать новую точку патрулирования
self.patrol_target = self.get_random_patrol_point(grid)
self.path = self.find_path((self.x, self.y), self.patrol_target, grid)
self.move_along_path()
def pursue_enemy(self, grid):
if self.target:
target_pos = (self.target.x, self.target.y)
elif self.last_seen_enemy:
target_pos = (self.last_seen_enemy.x, self.last_seen_enemy.y)
else:
self.state = UnitState.PATROLLING
return
if not self.path or len(self.path) == 0:
self.path = self.find_path((self.x, self.y), target_pos, grid)
self.move_along_path()
def fight(self, units, grid):
if self.target and self.target.health > 0:
# Стрельба
if self.shoot_cooldown <= 0 and self.has_line_of_sight(self.target, grid):
self.shoot(self.target)
# Тактическое движение
if random.random() < 0.2:
self.tactical_move(grid, units)
else:
self.target = None
def take_cover(self, grid, units):
cover_pos = self.find_nearest_cover(grid)
if cover_pos and (self.x != cover_pos[0] or self.y != cover_pos[1]):
self.path = self.find_path((self.x, self.y), cover_pos, grid)
self.move_along_path()
self.in_cover = True
else:
# Стрелять из укрытия
enemies = self.get_visible_enemies(units, grid)
if enemies and self.shoot_cooldown <= 0:
self.target = enemies[0]
self.shoot(self.target)
def flank_enemy(self, grid, units):
if self.target:
# Найти позицию для флангового маневра
flank_pos = self.find_flank_position(self.target, grid)
if flank_pos and not self.path:
self.path = self.find_path((self.x, self.y), flank_pos, grid)
self.move_along_path()
# Стрелять если в радиусе
if self.distance_to(self.target) <= self.shoot_range and self.shoot_cooldown <= 0:
self.shoot(self.target)
def retreat(self, grid, units):
# Найти безопасную позицию
safe_pos = self.find_safe_position(grid, units)
if safe_pos and not self.path:
self.path = self.find_path((self.x, self.y), safe_pos, grid)
self.move_along_path()
# Прикрывающий огонь при отступлении
enemies = self.get_visible_enemies(units, grid)
if enemies and self.shoot_cooldown <= 0 and random.random() < 0.5:
self.shoot(enemies[0])
def move_along_path(self):
if self.move_timer >= 1 and self.path:
next_pos = self.path[0]
self.x, self.y = next_pos
self.path.pop(0)
self.move_timer = 0
self.in_cover = False
def shoot(self, target):
if random.random() < self.accuracy:
damage = self.damage
if self.in_cover:
damage *= 1.2 # Бонус из укрытия
target.health -= damage
self.shoot_cooldown = 30 # Задержка между выстрелами
def tactical_move(self, grid, units):
# Случайное тактическое перемещение
directions = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)]
random.shuffle(directions)
for dx, dy in directions:
new_x = self.x + dx
new_y = self.y + dy
if self.is_valid_position(new_x, new_y, grid):
self.path = [(new_x, new_y)]
break
def find_nearest_cover(self, grid):
# Поиск ближайшего укрытия
min_dist = float('inf')
best_cover = None
for y in range(GRID_HEIGHT):
for x in range(GRID_WIDTH):
if grid[y][x].cover and not grid[y][x].wall:
dist = abs(x - self.x) + abs(y - self.y)
if dist < min_dist:
min_dist = dist
best_cover = (x, y)
return best_cover
def find_flank_position(self, target, grid):
# Найти позицию для флангового маневра
angle = math.atan2(target.y - self.y, target.x - self.x)
flank_angle = angle + math.pi/2 if random.random() < 0.5 else angle - math.pi/2
dist = 5
flank_x = int(target.x + dist * math.cos(flank_angle))
flank_y = int(target.y + dist * math.sin(flank_angle))
if self.is_valid_position(flank_x, flank_y, grid):
return (flank_x, flank_y)
return None
def find_safe_position(self, grid, units):
# Найти безопасную позицию для отступления
enemies = self.get_visible_enemies(units, grid)
if not enemies:
return None
# Направление от врагов
avg_enemy_x = sum(e.x for e in enemies) / len(enemies)
avg_enemy_y = sum(e.y for e in enemies) / len(enemies)
retreat_x = self.x + (self.x - avg_enemy_x)
retreat_y = self.y + (self.y - avg_enemy_y)
retreat_x = max(0, min(GRID_WIDTH-1, int(retreat_x)))
retreat_y = max(0, min(GRID_HEIGHT-1, int(retreat_y)))
if self.is_valid_position(retreat_x, retreat_y, grid):
return (retreat_x, retreat_y)
return self.get_random_patrol_point(grid)
def get_random_patrol_point(self, grid):
attempts = 0
while attempts < 50:
x = random.randint(0, GRID_WIDTH-1)
y = random.randint(0, GRID_HEIGHT-1)
if not grid[y][x].wall:
return (x, y)
attempts += 1
return (self.x, self.y)
def get_visible_enemies(self, units, grid):
enemies = []
for unit in units:
if unit.team != self.team and unit.health > 0:
if self.distance_to(unit) <= self.vision_range:
if self.has_line_of_sight(unit, grid):
enemies.append(unit)
return sorted(enemies, key=lambda u: self.distance_to(u))
def get_nearby_allies(self, units):
allies = []
for unit in units:
if unit != self and unit.team == self.team and unit.health > 0:
if self.distance_to(unit) <= 10:
allies.append(unit)
return allies
def distance_to(self, other):
return math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2)
def has_line_of_sight(self, target, grid):
# Проверка прямой видимости
x0, y0 = self.x, self.y
x1, y1 = target.x, target.y
dx = abs(x1 - x0)
dy = abs(y1 - y0)
sx = 1 if x0 < x1 else -1
sy = 1 if y0 < y1 else -1
err = dx - dy
while True:
if x0 == x1 and y0 == y1:
break
if 0 <= x0 < GRID_WIDTH and 0 <= y0 < GRID_HEIGHT:
if grid[y0][x0].wall:
return False
e2 = 2 * err
if e2 > -dy:
err -= dy
x0 += sx
if e2 < dx:
err += dx
y0 += sy
return True
def is_valid_position(self, x, y, grid):
return (0 <= x < GRID_WIDTH and 0 <= y < GRID_HEIGHT and
not grid[y][x].wall)
def find_path(self, start, goal, grid):
# A* pathfinding
if not self.is_valid_position(goal[0], goal[1], grid):
return []
open_set = [(start, 0)]
came_from = {}
g_score = {start: 0}
while open_set:
current, _ = min(open_set, key=lambda x: x[1])
open_set.remove((current, _))
if current == goal:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
return list(reversed(path))
for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
neighbor = (current[0] + dx, current[1] + dy)
if not self.is_valid_position(neighbor[0], neighbor[1], grid):
continue
tentative_g = g_score[current] + 1
if neighbor not in g_score or tentative_g < g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = tentative_g
f_score = tentative_g + abs(neighbor[0] - goal[0]) + abs(neighbor[1] - goal[1])
if (neighbor, f_score) not in open_set:
open_set.append((neighbor, f_score))
return []
class BattleSimulator:
def __init__(self):
self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Симулятор сражений: Полиция vs Преступники")
self.clock = pygame.time.Clock()
self.grid = [[Tile(x, y) for x in range(GRID_WIDTH)] for y in range(GRID_HEIGHT)]
self.units = []
self.running = True
self.font = pygame.font.Font(None, 24)
self.generate_map()
self.spawn_units()
def generate_map(self):
# Генерация стен
for _ in range(30):
x = random.randint(2, GRID_WIDTH-3)
y = random.randint(2, GRID_HEIGHT-3)
w = random.randint(3, 8)
h = random.randint(3, 8)
for dx in range(w):
for dy in range(h):
if x+dx < GRID_WIDTH and y+dy < GRID_HEIGHT:
self.grid[y+dy][x+dx].wall = True
# Генерация укрытий
for _ in range(40):
x = random.randint(1, GRID_WIDTH-2)
y = random.randint(1, GRID_HEIGHT-2)
if not self.grid[y][x].wall:
self.grid[y][x].cover = True
def spawn_units(self):
# Спавн полиции (левая сторона)
for _ in range(12):
attempts = 0
while attempts < 50:
x = random.randint(0, GRID_WIDTH//3)
y = random.randint(0, GRID_HEIGHT-1)
if not self.grid[y][x].wall:
self.units.append(Unit(x, y, 'police'))
break
attempts += 1
# Спавн преступников (правая сторона)
for _ in range(15):
attempts = 0
while attempts < 50:
x = random.randint(2*GRID_WIDTH//3, GRID_WIDTH-1)
y = random.randint(0, GRID_HEIGHT-1)
if not self.grid[y][x].wall:
self.units.append(Unit(x, y, 'criminal'))
break
attempts += 1
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
# Рестарт
self.units.clear()
self.spawn_units()
def update(self):
# Обновление юнитов
alive_units = [u for u in self.units if u.health > 0]
for unit in alive_units:
unit.update(alive_units, self.grid)
# Удаление мертвых юнитов
self.units = [u for u in self.units if u.health > 0]
def draw(self):
self.screen.fill(BLACK)
# Отрисовка сетки
for y in range(GRID_HEIGHT):
for x in range(GRID_WIDTH):
rect = pygame.Rect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE)
if self.grid[y][x].wall:
pygame.draw.rect(self.screen, GRAY, rect)
elif self.grid[y][x].cover:
pygame.draw.rect(self.screen, DARK_GRAY, rect)
else:
pygame.draw.rect(self.screen, BLACK, rect)
pygame.draw.rect(self.screen, (30, 30, 30), rect, 1)
# Отрисовка юнитов
for unit in self.units:
x = unit.x * TILE_SIZE
y = unit.y * TILE_SIZE
# Цвет в зависимости от команды
if unit.team == 'police':
color = BLUE
else:
color = RED
# Отрисовка юнита
rect = pygame.Rect(x + 2, y + 2, TILE_SIZE - 4, TILE_SIZE - 4)
pygame.draw.rect(self.screen, color, rect)
# Индикатор здоровья
health_width = int((TILE_SIZE - 4) * (unit.health / unit.max_health))
health_rect = pygame.Rect(x + 2, y - 5, health_width, 3)
pygame.draw.rect(self.screen, GREEN if unit.health > 50 else YELLOW if unit.health > 25 else RED, health_rect)
# Индикатор состояния
if unit.state == UnitState.FIGHTING:
pygame.draw.circle(self.screen, YELLOW, (x + TILE_SIZE//2, y + TILE_SIZE//2), 3)
elif unit.state == UnitState.TAKING_COVER and unit.in_cover:
pygame.draw.rect(self.screen, GREEN, (x, y, 3, 3))
# Статистика
police_count = len([u for u in self.units if u.team == 'police'])
criminal_count = len([u for u in self.units if u.team == 'criminal'])
police_text = self.font.render(f"Полиция: {police_count}", True, BLUE)
criminal_text = self.font.render(f"Преступники: {criminal_count}", True, RED)
controls_text = self.font.render("R - Рестарт", True, WHITE)
self.screen.blit(police_text, (10, 10))
self.screen.blit(criminal_text, (10, 40))
self.screen.blit(controls_text, (10, 70))
# Победитель
if police_count == 0 and criminal_count > 0:
win_text = self.font.render("ПРЕСТУПНИКИ ПОБЕДИЛИ!", True, RED)
self.screen.blit(win_text, (SCREEN_WIDTH//2 - 100, SCREEN_HEIGHT//2))
elif criminal_count == 0 and police_count > 0:
win_text = self.font.render("ПОЛИЦИЯ ПОБЕДИЛА!", True, BLUE)
self.screen.blit(win_text, (SCREEN_WIDTH//2 - 80, SCREEN_HEIGHT//2))
pygame.display.flip()
def run(self):
while self.running:
self.handle_events()
self.update()
self.draw()
self.clock.tick(30)
pygame.quit()
if __name__ == "__main__":
simulator = BattleSimulator()
simulator.run()
Юниты автоматически оценивают ситуацию, принимают тактические решения, используют укрытия, координируются с союзниками и адаптируют свое поведение в зависимости от обстановки на поле боя.