import pygame
import random
import math

# Определение констант
SCREEN_WIDTH = 1920
SCREEN_HEIGHT = 1080
PLAYER_SIZE = 150
BULLET_SIZE = 30
FPS = 60
BULLET_SPEED = 6
TANK_SPEED = 2
FIRE_DELAY = 500  # Задержка между выстрелами в миллисекундах
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

# Инициализация Pygame
pygame.init()

# Создание игрового окна
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), flags=pygame.FULLSCREEN)
pygame.display.set_caption("Танчики")

# Загрузка изображений
background_image = pygame.transform.scale(pygame.image.load("travka_pol.jpeg"), (960, 540))
stena = pygame.transform.scale(pygame.image.load("stena.jpeg").convert(), (100, 100))
stenki = pygame.transform.scale(pygame.image.load("stena.jpeg").convert(), (200, 200))
tank_image = pygame.transform.scale(pygame.image.load("ntank-removebg-preview.png"), (PLAYER_SIZE, PLAYER_SIZE))
bullet_image = pygame.transform.scale(pygame.image.load("bullet.png"), (BULLET_SIZE, BULLET_SIZE))
menu_background = pygame.transform.scale(pygame.image.load("menu_background.jpg"), (SCREEN_WIDTH, SCREEN_HEIGHT))

# Определение класса танка
class Tank(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.original_image = tank_image
        self.image = self.original_image
        self.rect = self.image.get_rect(center=(x, y))
        self.angle = -90  # Поворот на 90 градусов против часовой стрелки
        self.last_fire_time = pygame.time.get_ticks()  # Время последнего выстрела

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_w]:
            self.move_forward()
        mouse_pos = pygame.mouse.get_pos()
        self.angle = math.degrees(math.atan2(mouse_pos[1] - self.rect.centery, mouse_pos[0] - self.rect.centerx)) + 90
        self.image = pygame.transform.rotate(self.original_image, -self.angle)
        self.rect = self.image.get_rect(center=self.rect.center)

    def move_forward(self):
        angle_rad = math.radians(self.angle + 270)
        self.rect.x += TANK_SPEED * math.cos(angle_rad)
        self.rect.y += TANK_SPEED * math.sin(angle_rad)

    def shoot(self):
        current_time = pygame.time.get_ticks()
        if current_time - self.last_fire_time > FIRE_DELAY:  # Проверка задержки между выстрелами
            bullet = Bullet(self.rect.centerx, self.rect.centery, self.angle + 270)  # Изменено на 90 градусов влево
            all_sprites.add(bullet)
            bullets.add(bullet)
            self.last_fire_time = current_time  # Обновление времени последнего выстрела


# Определение класса снаряда
class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y, angle):
        super().__init__()
        self.original_image = bullet_image
        self.image = self.original_image
        self.rect = self.image.get_rect(center=(x, y))
        self.angle = angle

    def update(self):
        self.rect.x += BULLET_SPEED * math.cos(math.radians(self.angle))
        self.rect.y += BULLET_SPEED * math.sin(math.radians(self.angle))
        if not screen.get_rect().colliderect(self.rect):
            self.kill()


# Создание групп спрайтов
all_sprites = pygame.sprite.Group()
tanks = pygame.sprite.Group()
bullets = pygame.sprite.Group()

# Создание игрока
player = Tank(SCREEN_WIDTH // 4, SCREEN_HEIGHT // 2)
all_sprites.add(player)
tanks.add(player)


# Функция для отображения меню
def draw_menu():
    screen.blit(menu_background, (0, 0))
    # Рисуем текст меню
    font = pygame.font.Font(None, 50)
    text = font.render("Start", True, WHITE)
    text_rect = text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 - 50))
    screen.blit(text, text_rect)

    # Рисуем кнопку "Выйти"
    quit_text = font.render("Quit", True, WHITE)
    quit_rect = quit_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 50))
    screen.blit(quit_text, quit_rect)

    pygame.display.flip()

    return quit_rect  # Возвращаем прямоугольник для кнопки "Выйти"


# Главный цикл программы
menu_active = True
while menu_active:
    quit_rect = draw_menu()
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:  # Левая кнопка мыши
                if quit_rect.collidepoint(event.pos):
                    pygame.quit()
                    quit()
                else:
                    menu_active = False  # Нажата кнопка "Старт"

# Игровой цикл
running = True
clock = pygame.time.Clock()
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:  # Обработка левой кнопки мыши
            player.shoot()

    # Обновление всех спрайтов
    all_sprites.update()

    # Отрисовка фона и спрайтов
    for i in range(2):
        for j in range(2):
            screen.blit(background_image, (i * 960, j * 540))
    all_sprites.draw(screen)
    screen.blit(stena, (360, 40))

    screen.blit(stena, (460, 730))
    screen.blit(stena, (460, 830))
    screen.blit(stena, (460, 930))

    screen.blit(stena, (960, 40))
    screen.blit(stena, (960, 140))
    screen.blit(stena, (960, 240))

    screen.blit(stena, (660, 240))

    screen.blit(stena, (960, 440))
    screen.blit(stena, (960, 540))
    screen.blit(stena, (960, 640))
    screen.blit(stena, (960, 740))

    screen.blit(stena, (1260, 740))
    screen.blit(stena, (1360, 740))
    screen.blit(stena, (1460, 740))
    screen.blit(stena, (1560, 740))
    screen.blit(stena, (1660, 740))

    screen.blit(stena, (360, 240))
    screen.blit(stena, (360, 340))
    screen.blit(stena, (360, 440))

    screen.blit(stena, (0, 540))
    screen.blit(stena, (60, 540))
    screen.blit(stena, (260, 540))
    screen.blit(stena, (360, 540))
    screen.blit(stena, (460, 540))
    screen.blit(stena, (560, 540))
    screen.blit(stena, (660, 540))
    screen.blit(stena, (760, 540))
    screen.blit(stena, (860, 540))

    screen.blit(stena, (1160, 240))
    screen.blit(stena, (1260, 240))
    screen.blit(stena, (1360, 240))
    screen.blit(stena, (1460, 240))
    screen.blit(stena, (1460, 340))
    screen.blit(stena, (1760, 340))
    screen.blit(stena, (1860, 340))

    screen.blit(stenki, (-150, 0))
    screen.blit(stenki, (-150, 200))
    screen.blit(stenki, (-150, 400))
    screen.blit(stenki, (-150, 600))
    screen.blit(stenki, (-150, 800))
    screen.blit(stenki, (-150, 1000))
    screen.blit(stenki, (0, -150))
    screen.blit(stenki, (200, -150))
    screen.blit(stenki, (400, -150))
    screen.blit(stenki, (600, -150))
    screen.blit(stenki, (800, -150))
    screen.blit(stenki, (1000, -150))
    screen.blit(stenki, (1200, -150))
    screen.blit(stenki, (1400, -150))
    screen.blit(stenki, (1600, -150))
    screen.blit(stenki, (1800, -150))
    screen.blit(stenki, (1870, 0))
    screen.blit(stenki, (1870, 200))
    screen.blit(stenki, (1870, 400))
    screen.blit(stenki, (1870, 600))
    screen.blit(stenki, (1870, 800))
    screen.blit(stenki, (1870, 1000))
    screen.blit(stenki, (0, 1030))
    screen.blit(stenki, (200, 1030))
    screen.blit(stenki, (400, 1030))
    screen.blit(stenki, (600, 1030))
    screen.blit(stenki, (800, 1030))
    screen.blit(stenki, (1000, 1030))
    screen.blit(stenki, (1200, 1030))
    screen.blit(stenki, (1400, 1030))
    screen.blit(stenki, (1600, 1030))
    screen.blit(stenki, (1800, 1030))

    pygame.display.flip()
    clock.tick(FPS)

# Завершение работы Pygame
pygame.quit()
