Полицейский симулятор с реалистичным ИИ
Вот реализация тайловой игры с реалистичным ИИ для полиции и преступников на Pygame:
import pygame
import random
import math
import heapq
from collections import deque
# Инициализация Pygame
pygame.init()
# Константы
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
TILE_SIZE = 20
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
GRAY = (100, 100, 100)
YELLOW = (255, 255, 0)
# Настройки игры
NUM_COPS = 5
NUM_CRIMINALS = 5
NUM_WALLS = 30
# Создание экрана
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Полицейский симулятор")
clock = pygame.time.Clock()
class TileMap:
def __init__(self, width, height):
self.width = width // TILE_SIZE
self.height = height // TILE_SIZE
self.grid = [[0 for _ in range(self.width)] for _ in range(self.height)]
self.obstacles = set()
def add_obstacle(self, x, y):
if 0 <= x < self.width and 0 <= y < self.height:
self.grid[y][x] = 1
self.obstacles.add((x, y))
def is_obstacle(self, x, y):
if 0 <= x < self.width and 0 <= y < self.height:
return self.grid[y][x] == 1
return True
def draw(self, surface):
for y in range(self.height):
for x in range(self.width):
if self.grid[y][x] == 1:
pygame.draw.rect(surface, GRAY, (x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE))
class Entity:
def __init__(self, x, y, color, map):
self.x = x
self.y = y
self.color = color
self.map = map
self.path = []
self.target = None
self.vision_range = 5
self.speed = 1.0
self.move_cooldown = 0
self.health = 100
self.ammo = 10
self.reload_time = 0
self.team = None
self.state = "patrol"
self.last_seen_enemy = None
self.cover_position = None
self.combat_cooldown = 0
def get_tile_pos(self):
return int(self.x), int(self.y)
def move_towards(self, target_x, target_y):
dx = target_x - self.x
dy = target_y - self.y
dist = math.sqrt(dx*dx + dy*dy)
if dist > 0:
dx = dx / dist
dy = dy / dist
new_x = self.x + dx * self.speed * 0.1
new_y = self.y + dy * self.speed * 0.1
tile_x, tile_y = int(new_x), int(new_y)
if not self.map.is_obstacle(tile_x, tile_y):
self.x = new_x
self.y = new_y
else:
# Попробовать обойти препятствие
if not self.map.is_obstacle(tile_x, int(self.y)):
self.x = new_x
elif not self.map.is_obstacle(int(self.x), tile_y):
self.y = new_y
def find_path(self, target_x, target_y):
start = self.get_tile_pos()
end = (int(target_x), int(target_y))
if start == end:
return []
def heuristic(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
frontier = []
heapq.heappush(frontier, (0, start))
came_from = {}
cost_so_far = {}
came_from[start] = None
cost_so_far[start] = 0
while frontier:
current = heapq.heappop(frontier)[1]
if current == end:
break
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
next_node = (current[0] + dx, current[1] + dy)
if (0 <= next_node[0] < self.map.width and
0 <= next_node[1] < self.map.height and
not self.map.is_obstacle(next_node[0], next_node[1])):
new_cost = cost_so_far[current] + 1
if next_node not in cost_so_far or new_cost < cost_so_far[next_node]:
cost_so_far[next_node] = new_cost
priority = new_cost + heuristic(end, next_node)
heapq.heappush(frontier, (priority, next_node))
came_from[next_node] = current
# Восстановление пути
path = []
if end in came_from:
current = end
while current != start:
path.append(current)
current = came_from[current]
path.reverse()
return path
def can_see(self, other):
# Проверка прямой видимости с помощью алгоритма Брезенхема
x0, y0 = self.get_tile_pos()
x1, y1 = other.get_tile_pos()
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:
return True
if self.map.is_obstacle(x0, y0):
return False
e2 = 2 * err
if e2 >= dy:
if x0 == x1:
break
err += dy
x0 += sx
if e2 <= dx:
if y0 == y1:
break
err += dx
y0 += sy
return False
def find_cover(self, from_pos):
# Поиск ближайшего укрытия от врага
best_cover = None
best_dist = float('inf')
for dx in range(-5, 6):
for dy in range(-5, 6):
x, y = self.get_tile_pos()[0] + dx, self.get_tile_pos()[1] + dy
if (0 <= x < self.map.width and 0 <= y < self.map.height and
not self.map.is_obstacle(x, y) and
self.map.is_obstacle(x-1, y) or self.map.is_obstacle(x+1, y) or
self.map.is_obstacle(x, y-1) or self.map.is_obstacle(x, y+1)):
# Проверяем, что укрытие действительно защищает от врага
cover_pos = (x, y)
if not self.has_line_of_sight(from_pos, cover_pos):
dist = (x - self.x)**2 + (y - self.y)**2
if dist < best_dist:
best_dist = dist
best_cover = cover_pos
return best_cover
def has_line_of_sight(self, from_pos, to_pos):
# Проверка прямой видимости между двумя точками
x0, y0 = from_pos
x1, y1 = to_pos
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:
return True
if self.map.is_obstacle(x0, y0):
return False
e2 = 2 * err
if e2 >= dy:
if x0 == x1:
break
err += dy
x0 += sx
if e2 <= dx:
if y0 == y1:
break
err += dx
y0 += sy
return True
def shoot(self, target):
if self.ammo > 0 and self.reload_time <= 0:
self.ammo -= 1
if random.random() < 0.7: # 70%