User: Напиши игру на пайтон. Она будет представлять из себя бежевый фон, и на бежевом фоне есть 4 квадратика устроены в порядке, что один квадрат на одной линии немного дальше от такого же второго, и под ними на дистанции такие же 2. Квадраты красного, черного, синего и зеленого цвета. На каждом квадрате написан его номер, у красного 1, у черного 2, у синего 3, у зеленого 4. И над ними, есть количество их здоровья, количество здоровья - это маленькие круги лаймового цвета над квадратом, главное чтобы эти шарики нее косались других квадратов. И у них всех их по 20 штук. И, раз в 5 секунд, какой то квадрат выпускает маленький желтый квадрат в сторону какого то квадрата, и при попадении желтого квадрата, у квадрата пропадает 1 зеленый круг. И так, пока 3 противника не умрут, тоесть оставшемуся квадрату не будет в кого стрелять.
Assistant: Для создания такой игры на Python мы можем использовать библиотеку pygame, которая хорошо подходит для разработки 2D-игр. Ниже представлен базовый пример реализации описанной игры:
import pygame
import random
import sys
# Инициализация pygame
pygame.init()
# Константы
WIDTH, HEIGHT = 800, 600
BG_COLOR = (222, 184, 135) # Бежевый фон
COLORS = [(255, 0, 0), (0, 0, 0), (0, 0, 255), (0, 255, 0)] # Красный, черный, синий, зеленый
HEALTH_COLOR = (50, 205, 50) # Лаймовый
BULLET_COLOR = (255, 255, 0) # Желтый
# Конфигурации квадратов
SQUARE_SIZE = 50
HEALTH_COUNT = 20
BULLET_SIZE = 5
# Создание окна
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Square Shooter")
# Определение классов
class Square:
def __init__(self, x, y, color, number):
self.rect = pygame.Rect(x, y, SQUARE_SIZE, SQUARE_SIZE)
self.color = color
self.number = number
self.health = HEALTH_COUNT
def draw(self, screen):
# Рисуем квадрат
pygame.draw.rect(screen, self.color, self.rect)
# Рисуем номер в центре квадрата
font = pygame.font.Font(None, 36)
text = font.render(str(self.number), True, (255, 255, 255))
text_rect = text.get_rect(center=self.rect.center)
screen.blit(text, text_rect)
# Рисуем здоровье в виде кругов
for i in range(self.health):
pygame.draw.circle(screen, HEALTH_COLOR, (self.rect.x + i * 2, self.rect.y - 10), 2)
class Bullet:
def __init__(self, x, y, target):
self.rect = pygame.Rect(x, y, BULLET_SIZE, BULLET_SIZE)
self.target = target
self.speed = 3
def update(self):
# Движение к цели
if self.target.rect.centerx > self.rect.x:
self.rect.x += self.speed
if self.target.rect.centerx < self.rect.x:
self.rect.x -= self.speed
if self.target.rect.centery > self.rect.y:
self.rect.y += self.speed
if self.target.rect.centery < self.rect.y:
self.rect.y -= self.speed
# Проверка на попадание
if self.rect.colliderect(self.target.rect):
self.target.health -= 1
return True
return False
def draw(self, screen):
pygame.draw.rect(screen, BULLET_COLOR, self.rect)
# Функция для обновления игрового состояния
def update_game(squares, bullets):
for bullet in bullets:
if bullet.update():
bullets.remove(bullet)
for square in squares:
if square.health <= 0:
squares.remove(square)
# Инициализация квадратов
squares = [
Square(100, 100, COLORS[0], 1),
Square(200, 100, COLORS[1], 2),
Square(100, 300, COLORS[2], 3),
Square(200, 300, COLORS[3], 4)
]
bullets = []
# Главный игровой цикл
clock = pygame.time.Clock()
bullet_event = pygame.USEREVENT + 1
pygame.time.set_timer(bullet_event, 5000) # Раз в 5 секунд
while len(squares) > 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == bullet_event:
shooter = random.choice(squares)
target = random.choice([s for s in squares if s != shooter])
bullets.append(Bullet(shooter.rect.centerx, shooter.rect.centery, target))
screen.fill(BG_COLOR)
update_game(squares, bullets)
for square in squares:
square.draw(screen)
for bullet in bullets:
bullet.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
Assistant
Этот код создает игру, в которой четыре квадрата (красный, черный, синий и зеленый) стреляют друг в друга желтыми квадратами через равные интервалы времени. Здоровье каждого квадрата отображается в виде маленьких лаймовых кругов над ними. Игра продолжается до тех пор, пока не останется один квадрат.
User: Игра должна быть зацикленна на квадратах, окно с ней не должно быть таким большим, а так-же если квадрат стреляет в квадрата по диагонале, то и путь должен быть по диагонале. Так-же чуть увеличь зеленые круги ХП, и сделай между ними расстояние.
Assistant: Для изменения окна, добавления диагонального движения для пуль и увеличения и разнесения зеленых кругов для отображения оставшегося здоровья, нам нужно сделать несколько изменений в коде. Вот обновленный пример:
import pygame
import random
import sys
# Инициализация pygame
pygame.init()
# Константы
WIDTH, HEIGHT = 400, 400
BG_COLOR = (222, 184, 135) # Бежевый фон
COLORS = [(255, 0, 0), (0, 0, 0), (0, 0, 255), (0, 255, 0)] # Красный, черный, синий, зеленый
HEALTH_COLOR = (50, 205, 50) # Лаймовый
BULLET_COLOR = (255, 255, 0) # Желтый
# Конфигурации квадратов
SQUARE_SIZE = 50
HEALTH_COUNT = 20
BULLET_SIZE = 5
HEALTH_RADIUS = 4 # Радиус круга здоровья
# Создание окна
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Square Shooter")
# Определение классов
class Square:
def __init__(self, x, y, color, number):
self.rect = pygame.Rect(x, y, SQUARE_SIZE, SQUARE_SIZE)
self.color = color
self.number = number
self.health = HEALTH_COUNT
def draw(self, screen):
# Рисуем квадрат
pygame.draw.rect(screen, self.color, self.rect)
# Рисуем номер в центре квадрата
font = pygame.font.Font(None, 36)
text = font.render(str(self.number), True, (255, 255, 255))
text_rect = text.get_rect(center=self.rect.center)
screen.blit(text, text_rect)
# Рисуем здоровье в виде кругов с расстоянием
for i in range(self.health):
offset_x = (i % 10) * (HEALTH_RADIUS * 2 + 2)
offset_y = (i // 10) * (HEALTH_RADIUS * 2 + 2)
pygame.draw.circle(screen, HEALTH_COLOR, (self.rect.x + offset_x, self.rect.y - 20 - offset_y), HEALTH_RADIUS)
class Bullet:
def __init__(self, x, y, target):
self.rect = pygame.Rect(x, y, BULLET_SIZE, BULLET_SIZE)
self.target = target
self.speed = 3
self.calc_direction()
def calc_direction(self):
# Рассчитываем движение пули по диагонали, если нужно
dx = self.target.rect.centerx - self.rect.centerx
dy = self.target.rect.centery - self.rect.centery
distance = (dx ** 2 + dy ** 2) ** 0.5
self.vel_x = (dx / distance) * self.speed
self.vel_y = (dy / distance) * self.speed
def update(self):
# Движение к цели
self.rect.x += self.vel_x
self.rect.y += self.vel_y
# Проверка на попадание
if self.rect.colliderect(self.target.rect):
self.target.health -= 1
return True
return False
def draw(self, screen):
pygame.draw.rect(screen, BULLET_COLOR, self.rect)
# Функция для обновления игрового состояния
def update_game(squares, bullets):
for bullet in bullets:
if bullet.update():
bullets.remove(bullet)
for square in squares:
if square.health <= 0:
squares.remove(square)
# Инициализация квадратов
squares = [
Square(50, 50, COLORS[0], 1),
Square(200, 50, COLORS[1], 2),
Square(50, 200, COLORS[2], 3),
Square(200, 200, COLORS[3], 4)
]
bullets = []
# Главный игровой цикл
clock = pygame.time.Clock()
bullet_event = pygame.USEREVENT + 1
pygame.time.set_timer(bullet_event, 5000) # Раз в 5 секунд
while len(squares) > 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == bullet_event:
shooter = random.choice(squares)
target = random.choice([s for s in squares if s != shooter])
bullets.append(Bullet(shooter.rect.centerx, shooter.rect.centery, target))
screen.fill(BG_COLOR)
update_game(squares, bullets)
for square in squares:
square.draw(screen)
for bullet in bullets:
bullet.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
В этом обновленном коде:
Уменьшен размер окна (400x400).
Пули летят по диагонали в зависимости от местоположения их цели.
Зеленые круги, отображающие здоровье, увеличены и разнесены по вертикали и горизонтали для лучшей четкости отображения.
User: Сделай все по четче, а то как мыло, еще чуть уменьш зеленые круги, а вот атаку желтую увеличь, и сделай каждые 3 секунды. Так-же добавь аттаку синим треугольником, данная атака будет редкой, так как сносит 3 зеленых круга. Так-же сделай окно примерно Чтобы его границы чуть чуть не доставали до квадратов.
Assistant: Чтобы сделать графику более четкой, мы можем использовать высокое разрешение для окна и убедиться, что все элементы игры отображаются правильно. Давайте немного изменим размеры и настройки элементов, добавим синий треугольник как специальную атаку, и изменим интервал атаки. Мы уменьшили размеры окна так, чтобы оно близко прилегало к квадратам, но не касалось их. Вот обновленный код:
import pygame
import random
import sys
# Инициализация pygame
pygame.init()
# Константы
WIDTH, HEIGHT = 320, 320
BG_COLOR = (222, 184, 135) # Бежевый фон
COLORS = [(255, 0, 0), (0, 0, 0), (0, 0, 255), (0, 255, 0)] # Красный, черный, синий, зеленый
HEALTH_COLOR = (50, 205, 50) # Лаймовый
BULLET_COLOR = (255, 255, 0) # Желтый
TRIANGLE_COLOR = (0, 0, 255) # Синий
# Конфигурации квадратов
SQUARE_SIZE = 50
HEALTH_COUNT = 20
BULLET_SIZE = 10
TRIANGLE_SIZE = 15
HEALTH_RADIUS = 3 # Радиус круга здоровья
# Создание окна
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Square Shooter")
# Определение классов
class Square:
def __init__(self, x, y, color, number):
self.rect = pygame.Rect(x, y, SQUARE_SIZE, SQUARE_SIZE)
self.color = color
self.number = number
self.health = HEALTH_COUNT
def draw(self, screen):
# Рисуем квадрат
pygame.draw.rect(screen, self.color, self.rect)
# Рисуем номер в центре квадрата
font = pygame.font.Font(None, 36)
text = font.render(str(self.number), True, (255, 255, 255))
text_rect = text.get_rect(center=self.rect.center)
screen.blit(text, text_rect)
# Рисуем здоровье в виде кругов с расстоянием
for i in range(self.health):
offset_x = (i % 10) * (HEALTH_RADIUS * 2 + 4)
offset_y = (i // 10) * (HEALTH_RADIUS * 2 + 4)
pygame.draw.circle(screen, HEALTH_COLOR, (self.rect.x + offset_x, self.rect.y - 20 - offset_y), HEALTH_RADIUS)
class Bullet:
def __init__(self, x, y, target):
self.rect = pygame.Rect(x, y, BULLET_SIZE, BULLET_SIZE)
self.target = target
self.speed = 5
self.calc_direction()
def calc_direction(self):
# Рассчитываем движение пули по диагонали, если нужно
dx = self.target.rect.centerx - self.rect.centerx
dy = self.target.rect.centery - self.rect.centery
distance = (dx ** 2 + dy ** 2) ** 0.5
self.vel_x = (dx / distance) * self.speed
self.vel_y = (dy / distance) * self.speed
def update(self):
# Движение к цели
self.rect.x += self.vel_x
self.rect.y += self.vel_y
# Проверка на попадание
if self.rect.colliderect(self.target.rect):
self.target.health -= 1
return True
return False
def draw(self, screen):
pygame.draw.rect(screen, BULLET_COLOR, self.rect)
class Triangle:
def __init__(self, x, y, target):
self.x, self.y = x, y
self.target = target
self.speed = 3
self.calc_direction()
def calc_direction(self):
# Рассчитываем движение треугольника по диагонали
dx = self.target.rect.centerx - self.x
dy = self.target.rect.centery - self.y
distance = (dx ** 2 + dy ** 2) ** 0.5
self.vel_x = (dx / distance) * self.speed
self.vel_y = (dy / distance) * self.speed
def update(self):
# Движение к цели
self.x += self.vel_x
self.y += self.vel_y
# Проверка на попадание
if self.target.rect.collidepoint(self.x, self.y):
self.target.health -= 3
return True
return False
def draw(self, screen):
# Рисуем треугольник
points = [
(self.x, self.y - TRIANGLE_SIZE),
(self.x - TRIANGLE_SIZE, self.y + TRIANGLE_SIZE),
(self.x + TRIANGLE_SIZE, self.y + TRIANGLE_SIZE),
]
pygame.draw.polygon(screen, TRIANGLE_COLOR, points)
# Функция для обновления игрового состояния
def update_game(squares, bullets, triangles):
for bullet in bullets:
if bullet.update():
bullets.remove(bullet)
for triangle in triangles:
if triangle.update():
triangles.remove(triangle)
for square in squares:
if square.health <= 0:
squares.remove(square)
# Инициализация квадратов
squares = [
Square(20, 20, COLORS[0], 1),
Square(250, 20, COLORS[1], 2),
Square(20, 250, COLORS[2], 3),
Square(250, 250, COLORS[3], 4)
]
bullets = []
triangles = []
# Главный игровой цикл
clock = pygame.time.Clock()
bullet_event = pygame.USEREVENT + 1
triangle_event = pygame.USEREVENT + 2
pygame.time.set_timer(bullet_event, 3000) # Раз в 3 секунды
pygame.time.set_timer(triangle_event, 15000) # Редкая атака каждые 15 секунд
while len(squares) > 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == bullet_event:
shooter = random.choice(squares)
target = random.choice([s for s in squares if s != shooter])
bullets.append(Bullet(shooter.rect.centerx, shooter.rect.centery, target))
elif event.type == triangle_event:
shooter = random.choice(squares)
target = random.choice([s for s in squares if s != shooter])
triangles.append(Triangle(shooter.rect.centerx, shooter.rect.centery, target))
screen.fill(BG_COLOR)
update_game(squares, bullets, triangles)
for square in squares:
square.draw(screen)
for bullet in bullets:
bullet.draw(screen)
for triangle in triangles:
triangle.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
Обновления и изменения:
Размеры окна уменьшены до 320x320, чтобы оно было более компактным.
Желтые квадраты (атака) увеличены в размере и выпускаются каждые 3 секунды.
Синий треугольник добавлен как редкая атака, наносящая 3 единицы урона. Он запускается раз в 15 секунд.
Зеленые круги здоровья уменьшены в размере и разнесены для более четкого отображения.
Диагональное движение предусмотрено для треугольных и квадратных атак.
User: Чуть забыл, чтобы границы чучуть не доставали до квадратов а так-же линии хп. Кароче, чтобы оно было не большое, но и чтобы оно ровно по середине показывало квадраты.
Assistant: Чтобы квадраты располагались в центре окна и границы окна слегка не доставали до игровых объектов, нам нужно скорректировать позиции квадратов и немного изменить размеры окна. Мы также переместим линии здоровья так, чтобы они корректно отображались. Вот обновленная версия игры:
import pygame
import random
import sys
# Инициализация pygame
pygame.init()
# Константы
WIDTH, HEIGHT = 360, 360
BG_COLOR = (222, 184, 135) # Бежевый фон
COLORS = [(255, 0, 0), (0, 0, 0), (0, 0, 255), (0, 255, 0)] # Красный, черный, синий, зеленый
HEALTH_COLOR = (50, 205, 50) # Лаймовый
BULLET_COLOR = (255, 255, 0) # Желтый
TRIANGLE_COLOR = (0, 0, 255) # Синий
# Конфигурации квадратов
SQUARE_SIZE = 50
HEALTH_COUNT = 20
BULLET_SIZE = 10
TRIANGLE_SIZE = 15
HEALTH_RADIUS = 3
# Создание окна
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Square Shooter")
# Определение классов
class Square:
def __init__(self, x, y, color, number):
self.rect = pygame.Rect(x, y, SQUARE_SIZE, SQUARE_SIZE)
self.color = color
self.number = number
self.health = HEALTH_COUNT
def draw(self, screen):
pygame.draw.rect(screen, self.color, self.rect)
# Рисуем номер в центре квадрата
font = pygame.font.Font(None, 36)
text = font.render(str(self.number), True, (255, 255, 255))
text_rect = text.get_rect(center=self.rect.center)
screen.blit(text, text_rect)
# Рисуем здоровье
for i in range(self.health):
offset_x = (i % 10) * (HEALTH_RADIUS * 2 + 4)
offset_y = (i // 10) * (HEALTH_RADIUS * 2 + 4)
pygame.draw.circle(screen, HEALTH_COLOR, (self.rect.x + offset_x, self.rect.y - 15 - offset_y), HEALTH_RADIUS)
class Bullet:
def __init__(self, x, y, target):
self.rect = pygame.Rect(x, y, BULLET_SIZE, BULLET_SIZE)
self.target = target
self.speed = 5
self.calc_direction()
def calc_direction(self):
dx = self.target.rect.centerx - self.rect.centerx
dy = self.target.rect.centery - self.rect.centery
distance = (dx ** 2 + dy ** 2) ** 0.5
self.vel_x = (dx / distance) * self.speed
self.vel_y = (dy / distance) * self.speed
def update(self):
self.rect.x += self.vel_x
self.rect.y += self.vel_y
if self.rect.colliderect(self.target.rect):
self.target.health -= 1
return True
return False
def draw(self, screen):
pygame.draw.rect(screen, BULLET_COLOR, self.rect)
class Triangle:
def __init__(self, x, y, target):
self.x, self.y = x, y
self.target = target
self.speed = 3
self.calc_direction()
def calc_direction(self):
dx = self.target.rect.centerx - self.x
dy = self.target.rect.centery - self.y
distance = (dx ** 2 + dy ** 2) ** 0.5
self.vel_x = (dx / distance) * self.speed
self.vel_y = (dy / distance) * self.speed
def update(self):
self.x += self.vel_x
self.y += self.vel_y
if self.target.rect.collidepoint(self.x, self.y):
self.target.health -= 3
return True
return False
def draw(self, screen):
points = [
(self.x, self.y - TRIANGLE_SIZE),
(self.x - TRIANGLE_SIZE, self.y + TRIANGLE_SIZE),
(self.x + TRIANGLE_SIZE, self.y + TRIANGLE_SIZE),
]
pygame.draw.polygon(screen, TRIANGLE_COLOR, points)
def update_game(squares, bullets, triangles):
for bullet in bullets:
if bullet.update():
bullets.remove(bullet)
for triangle in triangles:
if triangle.update():
triangles.remove(triangle)
for square in squares:
if square.health <= 0:
squares.remove(square)
# Инициализация квадратов
squares = [
Square(40, 40, COLORS[0], 1),
Square(270, 40, COLORS[1], 2),
Square(40, 270, COLORS[2], 3),
Square(270, 270, COLORS[3], 4)
]
bullets = []
triangles = []
clock = pygame.time.Clock()
bullet_event = pygame.USEREVENT + 1
triangle_event = pygame.USEREVENT + 2
pygame.time.set_timer(bullet_event, 3000) # Каждые 3 секунды
pygame.time.set_timer(triangle_event, 15000) # Каждые 15 секунд для редкой атаки
while len(squares) > 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == bullet_event:
shooter = random.choice(squares)
target = random.choice([s for s in squares if s != shooter])
bullets.append(Bullet(shooter.rect.centerx, shooter.rect.centery, target))
elif event.type == triangle_event:
shooter = random.choice(squares)
target = random.choice([s for s in squares if s != shooter])
triangles.append(Triangle(shooter.rect.centerx, shooter.rect.centery, target))
screen.fill(BG_COLOR)
update_game(squares, bullets, triangles)
for square in squares:
square.draw(screen)
for bullet in bullets:
bullet.draw(screen)
for triangle in triangles:
triangle.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
Изменения:
Размеры окна увеличены до 360x360 для лучшего размещения объектов.
Позиции квадратов скорректированы, чтобы они располагались ближе к центру, не касаясь границ экрана.
Зеленые круги здоровья находятся выше квадратов для большей ясности.
User: Синий треугольник не должен вылетать вместе с желтым квадратом.
Assistant:
Чтобы синий треугольник не вылетал одновременно с желтым квадратом, мы можем запустить каждую атаку случайным образом, гарантируя, что только одна атака произойдет в течение одного обновления. Это можно сделать с помощью простого рандомайзера, который определяет, какая из атак будет выпущена. Вот как это можно реализовать:
import pygame
import random
import sys
# Инициализация pygame
pygame.init()
# Константы
WIDTH, HEIGHT = 360, 360
BG_COLOR = (222, 184, 135) # Бежевый фон
COLORS = [(255, 0, 0), (0, 0, 0), (0, 0, 255), (0, 255, 0)] # Красный, черный, синий, зеленый
HEALTH_COLOR = (50, 205, 50) # Лаймовый
BULLET_COLOR = (255, 255, 0) # Желтый
TRIANGLE_COLOR = (0, 0, 255) # Синий
# Конфигурации квадратов
SQUARE_SIZE = 50
HEALTH_COUNT = 20
BULLET_SIZE = 10
TRIANGLE_SIZE = 15
HEALTH_RADIUS = 3
# Создание окна
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Square Shooter")
# Определение классов
class Square:
def __init__(self, x, y, color, number):
self.rect = pygame.Rect(x, y, SQUARE_SIZE, SQUARE_SIZE)
self.color = color
self.number = number
self.health = HEALTH_COUNT
def draw(self, screen):
pygame.draw.rect(screen, self.color, self.rect)
# Рисуем номер в центре квадрата
font = pygame.font.Font(None, 36)
text = font.render(str(self.number), True, (255, 255, 255))
text_rect = text.get_rect(center=self.rect.center)
screen.blit(text, text_rect)
# Рисуем здоровье
for i in range(self.health):
offset_x = (i % 10) * (HEALTH_RADIUS * 2 + 4)
offset_y = (i // 10) * (HEALTH_RADIUS * 2 + 4)
pygame.draw.circle(screen, HEALTH_COLOR, (self.rect.x + offset_x, self.rect.y - 15 - offset_y), HEALTH_RADIUS)
class Bullet:
def __init__(self, x, y, target):
self.rect = pygame.Rect(x, y, BULLET_SIZE, BULLET_SIZE)
self.target = target
self.speed = 5
self.calc_direction()
def calc_direction(self):
dx = self.target.rect.centerx - self.rect.centerx
dy = self.target.rect.centery - self.rect.centery
distance = (dx ** 2 + dy ** 2) ** 0.5
self.vel_x = (dx / distance) * self.speed
self.vel_y = (dy / distance) * self.speed
def update(self):
self.rect.x += self.vel_x
self.rect.y += self.vel_y
if self.rect.colliderect(self.target.rect):
self.target.health -= 1
return True
return False
def draw(self, screen):
pygame.draw.rect(screen, BULLET_COLOR, self.rect)
class Triangle:
def __init__(self, x, y, target):
self.x, self.y = x, y
self.target = target
self.speed = 3
self.calc_direction()
def calc_direction(self):
dx = self.target.rect.centerx - self.x
dy = self.target.rect.centery - self.y
distance = (dx ** 2 + dy ** 2) ** 0.5
self.vel_x = (dx / distance) * self.speed
self.vel_y = (dy / distance) * self.speed
def update(self):
self.x += self.vel_x
self.y += self.vel_y
if self.target.rect.collidepoint(self.x, self.y):
self.target.health -= 3
return True
return False
def draw(self, screen):
points = [
(self.x, self.y - TRIANGLE_SIZE),
(self.x - TRIANGLE_SIZE, self.y + TRIANGLE_SIZE),
(self.x + TRIANGLE_SIZE, self.y + TRIANGLE_SIZE),
]
pygame.draw.polygon(screen, TRIANGLE_COLOR, points)
def update_game(squares, bullets, triangles):
for bullet in bullets:
if bullet.update():
bullets.remove(bullet)
for triangle in triangles:
if triangle.update():
triangles.remove(triangle)
for square in squares:
if square.health <= 0:
squares.remove(square)
# Инициализация квадратов
squares = [
Square(40, 40, COLORS[0], 1),
Square(270, 40, COLORS[1], 2),
Square(40, 270, COLORS[2], 3),
Square(270, 270, COLORS[3], 4)
]
bullets = []
triangles = []
clock = pygame.time.Clock()
attack_event = pygame.USEREVENT + 1
pygame.time.set_timer(attack_event, 3000) # Каждые 3 секунды
while len(squares) > 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == attack_event:
if squares:
shooter = random.choice(squares)
target = random.choice([s for s in squares if s != shooter])
if random.random() < 0.8: # 80% вероятность запуска желтого квадрата
bullets.append(Bullet(shooter.rect.centerx, shooter.rect.centery, target))
else: # 20% вероятность запуска синего треугольника
triangles.append(Triangle(shooter.rect.centerx, shooter.rect.centery, target))
screen.fill(BG_COLOR)
update_game(squares, bullets, triangles)
for square in squares:
square.draw(screen)
for bullet in bullets:
bullet.draw(screen)
for triangle in triangles:
triangle.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
Изменения:
Я объединил таймеры в один USEREVENT, который запускается каждые 3 секунды.
В событии атаки используется случайное число для определения типа атаки:
80% вероятность для выстрела обычным желтым квадратом.
20% вероятность для выстрела редким синим треугольником.
Это позволяет различным атакам запускаться поочередно, предотвращая их одновременное появление.