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% вероятность для выстрела редким синим треугольником.
Это позволяет различным атакам запускаться поочередно, предотвращая их одновременное появление.
User: Когда у квадрата не остаеться хп, он исчезает. И да, давай перепишем эту игру не на пайтоне, а на джаве
Assistant:
Переписать игру на Java можно, используя библиотеку Java Swing для создания графического интерфейса и анимаций. Мы создам основной каркас игры, включая управление, отрисовку и основные события. Вот пример того, как можно реализовать описанную игру на Java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
// Класс для квадратов
class Square {
int x, y, health, number;
Color color;
public Square(int x, int y, Color color, int number) {
this.x = x;
this.y = y;
this.color = color;
this.number = number;
this.health = 20;
}
public void draw(Graphics g) {
// Рисуем квадрат
g.setColor(color);
g.fillRect(x, y, 50, 50);
// Рисуем номер
g.setColor(Color.WHITE);
g.drawString(String.valueOf(number), x + 20, y + 30);
// Рисуем здоровье
g.setColor(new Color(50, 205, 50)); // Лаймовый
for (int i = 0; i < health; i++) {
int offsetX = (i % 10) * 7;
int offsetY = (i / 10) * 7;
g.fillOval(x + offsetX, y - 15 - offsetY, 6, 6);
}
}
}
// Класс для пуль
class Bullet {
double x, y, velocityX, velocityY;
Square target;
boolean active;
public Bullet(double x, double y, Square target) {
this.x = x;
this.y = y;
this.target = target;
this.active = true;
calculateDirection();
}
private void calculateDirection() {
double dx = target.x + 25 - x;
double dy = target.y + 25 - y;
double distance = Math.hypot(dx, dy);
velocityX = (dx / distance) * 5;
velocityY = (dy / distance) * 5;
}
public void update() {
x += velocityX;
y += velocityY;
if (target.health > 0 && target.x < x && x < target.x + 50 && target.y < y && y < target.y + 50) {
target.health--;
active = false;
}
}
public void draw(Graphics g) {
if (active) {
g.setColor(Color.YELLOW);
g.fillRect((int)x, (int)y, 10, 10);
}
}
}
// Класс для треугольников
class Triangle {
double x, y, velocityX, velocityY;
Square target;
boolean active;
public Triangle(double x, double y, Square target) {
this.x = x;
this.y = y;
this.target = target;
this.active = true;
calculateDirection();
}
private void calculateDirection() {
double dx = target.x + 25 - x;
double dy = target.y + 25 - y;
double distance = Math.hypot(dx, dy);
velocityX = (dx / distance) * 3;
velocityY = (dy / distance) * 3;
}
public void update() {
if (active) {
x += velocityX;
y += velocityY;
if (target.health > 0 && target.x < x && x < target.x + 50 && target.y < y && y < target.y + 50) {
target.health -= 3;
active = false;
}
}
}
public void draw(Graphics g) {
if (active) {
g.setColor(Color.BLUE);
int[] xPoints = {(int)x, (int)x - 15, (int)x + 15};
int[] yPoints = {(int)y - 15, (int)y + 15, (int)y + 15};
g.fillPolygon(xPoints, yPoints, 3);
}
}
}
// Основной класс игры
public class SquareShooter extends JPanel implements ActionListener {
ArrayList<Square> squares = new ArrayList<>();
ArrayList<Bullet> bullets = new ArrayList<>();
ArrayList<Triangle> triangles = new ArrayList<>();
Timer timer;
Random rand = new Random();
public SquareShooter() {
setPreferredSize(new Dimension(360, 360));
squares.add(new Square(40, 40, Color.RED, 1));
squares.add(new Square(270, 40, Color.BLACK, 2));
squares.add(new Square(40, 270, Color.BLUE, 3));
squares.add(new Square(270, 270, Color.GREEN, 4));
timer = new Timer(30, this);
timer.start();
Timer attackTimer = new Timer(3000, e -> {
if (squares.size() > 1) {
Square shooter = squares.get(rand.nextInt(squares.size()));
Square target;
do {
target = squares.get(rand.nextInt(squares.size()));
} while (target == shooter || target.health <= 0);
if (rand.nextDouble() < 0.8) {
bullets.add(new Bullet(shooter.x + 25, shooter.y + 25, target));
} else {
triangles.add(new Triangle(shooter.x + 25, shooter.y + 25, target));
}
}
});
attackTimer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(222, 184, 135)); // Бежевый
g.fillRect(0, 0, getWidth(), getHeight());
for (Square square : squares) {
square.draw(g);
}
bullets.removeIf(b -> !b.active);
for (Bullet bullet : bullets) {
bullet.update();
bullet.draw(g);
}
triangles.removeIf(t -> !t.active);
for (Triangle triangle : triangles) {
triangle.update();
triangle.draw(g);
}
squares.removeIf(square -> square.health <= 0);
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Square Shooter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(new SquareShooter());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Пояснения:
Классы Square, Bullet и Triangle:
Square представляет квадрат с его координатами, цветом, номером и уровнем здоровья.
Bullet и Triangle отвечают за управление пулями и треугольниками соответственно, включая их движение и нанесение урона целевым квадратам.
Класс SquareShooter:
Управляет основным процессом игры.
paintComponent отвечает за отрисовку кадра игры: отрисовываются квадраты, пули и треугольники.
Таймеры используются для обновления состояния и запуска атак с определенной периодичностью.
Инициализация игры:
Создание окна игры и добавление компонентов.
Настройка расположения квадратов и таймеров для управления игровым процессом.
Игра будет следовать описанным правилам, при этом легко можно добавлять новые функции или изменять существующие настройки для улучшения игрового процесса.