import pygame pygame.init() window = pygame.display.setmode((500,500))…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import pygame pygame.init() window = pygame.display.set_mode((500,500)) window.fill((254,186,1)) class Area(): def init (self,x,y,w,h,color=None): self.rect=pygame.Rect(x,y,w,h) self.fill_color=(254,186,1) def color(self,new_color): self.fill_color=new_color def fill(self): pygame.draw.rect(window,self.fill_color,self.rect) def collidepoint(self,x,y): return self.rect.collidepoint(x,y) def colliderect(self,rect): return self.rect.colliderect(rect) class Label(Area): def set_text(self, text, text_size, text_color=(0,0,0)): self.image=pygame.font.SysFont('verdana',text_size).render(text,True,text_color) def draw (self,shift_x,shift_y): self.fill() window.blit(self.image,(self.rect.x+shift_x,self.rect.y+shift_y)) class Picture1 (Area): def init(self,filename,x,y,w,h): Area.init(self,x=x,y=y,w=w,h=h,color=None) self.image=pygame.transform.scale(pygame.image.load(filename),(w,h)) def draw(self): window.blit(self.image,(self.rect.x,self.rect.y)) ball=Picture1('Робот 1.png',200,230,50,50) platform=Picture1('Cube23.png',250,350,150,30) start_x=5 start_y=5 numb=9 monsters=[] for j in range(3): y=start_y+(55j) x=start_x+(27.5j) for i in range(numb): monster=Picture1('Улитка (вид сбоку) 1.png',x,y,50,50) monsters.append(monster) x+=55 numb-=1 clock=pygame.time.Clock() game_over=False move_right=False move_left=False dx=3 dy=3 while not game_over: ball.fill() platform.fill() for event in pygame.event.get(): if event.type==pygame.QUIT: game_over=True if event.type==pygame.KEYDOWN: if event.key==pygame.K_RIGHT: move_right=True if event.key==pygame.K_LEFT: move_left=True elif event.type==pygame.KEYUP: if event.key==pygame.K_RIGHT: move_right=False if event.key==pygame.K_LEFT: move_left=False if move_right: platform.rect.x+=5 if move_left: platform.rect.x-=5 ball.rect.x+=dx ball.rect.y+=dy if ball.rect.y<0: dy*=-1 if ball.rect.x<0 or ball.rect.x>450: dx*=-1 if ball.rect.y>400: lose_text=Label(100,200,100,100,(254,186,1)) lose_text.set_text('Ты проиграл',60,(255,0,0)) lose_text.draw(10,10) game_over=True if ball.rect.colliderect(platform.rect): dy*=-1 if len(monsters)==0: lose_text=Label(100,200,100,100,(254,186,1)) lose_text.set_text('Ты выйграл',60,(255,0,0)) lose_text.draw(10,10) game_over=True for m in monsters: m.draw() if m.rect.colliderect(ball.rect): monsters.remove(m) m.fill() dy*=-1 platform.draw() ball.draw() pygame.display.update() clock.tick(65)
This code creates a simple Arkanoid/Breakout-style game using Pygame. The game features a ball, a platform controlled by the player, and rows of "monster" enemies that the player needs to hit with the ball to clear the screen.
Would you like me to explain or break down how this code works?
напишите идеи
Вот несколько идей для улучшения вашей игры:
1, 2 4 5 8
Хорошо, вот более подробное описание выбранных вами идей для реализации:
Система очков:
score = 0score += 10Несколько уровней:
create_level(level_number), которая будет генерировать разные расположения монстровcurrent_level = 1current_level и загружайте новый уровеньРазные типы монстров:
StrongMonster, FastMonster)health для монстров (обычные - 1, сильные - 2 или 3 удара)Бонусы:
Bonus с разными типами (увеличение платформы, замедление мяча, дополнительные очки)Меню:
MENU, GAME, PAUSE, GAME_OVERЭти улучшения значительно повысят интерес к игре и сделают её более разнообразной!
напиши код
Вот обновленный код с реализацией выбранных вами идей:
import pygame
import random
import time
pygame.init()
window = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Арканоид")
# Состояния игры
MENU = 0
GAME = 1
PAUSE = 2
GAME_OVER = 3
game_state = MENU
# Игровые переменные
score = 0
current_level = 1
max_levels = 3
lives = 3
class Area():
def __init__(self, x, y, w, h, color=None):
self.rect = pygame.Rect(x, y, w, h)
self.fill_color = (254, 186, 1)
def color(self, new_color):
self.fill_color = new_color
def fill(self):
pygame.draw.rect(window, self.fill_color, self.rect)
def collidepoint(self, x, y):
return self.rect.collidepoint(x, y)
def colliderect(self, rect):
return self.rect.colliderect(rect)
class Label(Area):
def set_text(self, text, text_size, text_color=(0, 0, 0)):
self.image = pygame.font.SysFont('verdana', text_size).render(text, True, text_color)
def draw(self, shift_x=0, shift_y=0):
self.fill()
window.blit(self.image, (self.rect.x + shift_x, self.rect.y + shift_y))
class Button(Area):
def __init__(self, x, y, w, h, text, text_size=20, color=(180, 180, 180), text_color=(0, 0, 0)):
super().__init__(x, y, w, h, color)
self.fill_color = color
self.text = text
self.text_size = text_size
self.text_color = text_color
self.font = pygame.font.SysFont('verdana', text_size)
self.rendered_text = self.font.render(text, True, text_color)
def draw(self):
self.fill()
text_rect = self.rendered_text.get_rect(center=self.rect.center)
window.blit(self.rendered_text, text_rect)
pygame.draw.rect(window, (0, 0, 0), self.rect, 2) # Рамка кнопки
class Picture(Area):
def __init__(self, filename, x, y, w, h):
Area.__init__(self, x=x, y=y, w=w, h=h, color=None)
self.image = pygame.transform.scale(pygame.image.load(filename), (w, h))
def draw(self):
window.blit(self.image, (self.rect.x, self.rect.y))
class Monster(Picture):
def __init__(self, filename, x, y, w, h, health=1, points=10):
super().__init__(filename, x, y, w, h)
self.health = health
self.points = points
def hit(self):
self.health -= 1
return self.health <= 0
class StrongMonster(Monster):
def __init__(self, filename, x, y, w, h):
super().__init__(filename, x, y, w, h, health=2, points=20)
class Bonus(Picture):
def __init__(self, bonus_type, x, y):
self.type = bonus_type
if bonus_type == "enlarge":
filename = "bonus_enlarge.png" # Замените на реальное имя файла
elif bonus_type == "slow":
filename = "bonus_slow.png" # Замените на реальное имя файла
elif bonus_type == "extra_points":
filename = "bonus_points.png" # Замените на реальное имя файла
super().__init__(filename, x, y, 30, 30)
self.speed = 2
def update(self):
self.rect.y += self.speed
return self.rect.y > 500 # Возвращает True, если бонус вышел за пределы экрана
def create_level(level_number):
monsters = []
if level_number == 1:
# Уровень 1: простые монстры в 3 ряда
start_x = 5
start_y = 5
numb = 9
for j in range(3):
y = start_y + (55 * j)
x = start_x + (27.5 * j)
for i in range(numb):
monster = Monster('Улитка (вид сбоку) 1.png', x, y, 50, 50)
monsters.append(monster)
x += 55
numb -= 1
elif level_number == 2:
# Уровень 2: смесь обычных и сильных монстров
for j in range(4):
for i in range(8):
x = 10 + i * 60
y = 10 + j * 40
if j == 0 or j == 3: # Первый и последний ряд - сильные монстры
monster = StrongMonster('Улитка (вид сбоку) 1.png', x, y, 50, 30)
else:
monster = Monster('Улитка (вид сбоку) 1.png', x, y, 50, 30)
monsters.append(monster)
elif level_number == 3:
# Уровень 3: сложная формация
positions = [
(50, 50), (100, 50), (150, 50), (200, 50), (250, 50), (300, 50), (350, 50), (400, 50),
(50, 100), (400, 100),
(50, 150), (150, 150), (250, 150), (350, 150), (400, 150),
(50, 200), (400, 200),
(50, 250), (100, 250), (150, 250), (200, 250), (250, 250), (300, 250), (350, 250), (400, 250)
]
for pos in positions:
if random.random() < 0.3: # 30% шанс сильного монстра
monster = StrongMonster('Улитка (вид сбоку) 1.png', pos[0], pos[1], 50, 40)
else:
monster = Monster('Улитка (вид сбоку) 1.png', pos[0], pos[1], 50, 40)
monsters.append(monster)
return monsters
# Создание игровых объектов
ball = Picture('Робот 1.png', 200, 230, 50, 50)
platform = Picture('Cube23.png', 250, 350, 150, 30)
original_platform_width = 150
# Создание кнопок меню
start_button = Button(150, 200, 200, 50, "Новая игра", 30)
continue_button = Button(150, 270, 200, 50, "Продолжить", 30)
exit_button = Button(150, 340, 200, 50, "Выход", 30)
# Создание текстовых меток
score_label = Label(10, 10, 150, 30, (254, 186, 1))
score_label.set_text("Счет: 0", 20)
lives_label = Label(350, 10, 150, 30, (254, 186, 1))
lives_label.set_text("Жизни: 3", 20)
level_label = Label(180, 10, 150, 30, (254, 186, 1))
level_label.set_text("Уровень: 1", 20)
# Инициализация игровых переменных
clock = pygame.time.Clock()
move_right = False
move_left = False
dx = 3
dy = 3
original_dx = dx
original_dy = dy
monsters = []
bonuses = []
# Таймеры для бонусов
bonus_timers = {
"enlarge": 0,
"slow": 0
}
def reset_game():
global score, current_level, lives, dx, dy, monsters, bonuses, bonus_timers
score = 0
current_level = 1
lives = 3
dx = original_dx
dy = original_dy
monsters = create_level(current_level)
bonuses = []
bonus_timers = {"enlarge": 0, "slow": 0}
platform.rect.x = 250
platform.rect.width = original_platform_width
ball.rect.x = 200
ball.rect.y = 230
def draw_menu():
window.fill((254, 186, 1))
title = Label(100, 100, 300, 50, (254, 186, 1))
title.set_text("АРКАНОИД", 40, (0, 0, 0))
title.draw()
start_button.draw()
exit_button.draw()
if game_state == PAUSE:
continue_button.draw()
def draw_game():
window.fill((254, 186, 1))
# Отрисовка интерфейса
score_label.set_text(f"Счет: {score}", 20)
score_label.draw()
lives_label.set_text(f"Жизни: {lives}", 20)
lives_label.draw()
level_label.set_text(f"Уровень: {current_level}", 20)
level_label.draw()
# Отрисовка игровых объектов
for monster in monsters:
monster.draw()
for bonus in bonuses:
bonus.draw()
platform.draw()
ball.draw()
def draw_pause():
pause_overlay = pygame.Surface((500, 500), pygame.SRCALPHA)
pause_overlay.fill((0, 0, 0, 128))
window.blit(pause_overlay, (0, 0))
pause_text = Label(150, 200, 200, 50, (0, 0, 0, 0))
pause_text.set_text("ПАУЗА", 40, (255, 255, 255))
pause_text.draw()
def draw_game_over(win):
window.fill((254, 186, 1))
if win:
result_text = Label(100, 150, 300, 100, (254, 186, 1))
result_text.set_text("ТЫ ВЫИГРАЛ!", 40, (0, 200, 0))
else:
result_text = Label(100, 150, 300, 100, (254, 186, 1))
result_text.set_text("ТЫ ПРОИГРАЛ", 40, (255, 0, 0))
result_text.draw()
score_text = Label(150, 250, 200, 50, (254, 186, 1))
score_text.set_text(f"Счет: {score}", 30, (0, 0, 0))
score_text.draw()
start_button.draw()
exit_button.draw()
def apply_bonus(bonus_type):
global bonus_timers, dx, dy
if bonus_type == "enlarge":
platform.rect.width = original_platform_width * 1.5
bonus_timers["enlarge"] = time.time() + 10 # 10 секунд
elif bonus_type == "slow":
dx = original_dx * 0.7
dy = original_dy * 0.7
bonus_timers["slow"] = time.time() + 10 # 10 секунд
elif bonus_type == "extra_points":
global score
score += 50
def check_bonus_timers():
current_time = time.time()
if bonus_timers["enlarge"] > 0 and current_time > bonus_timers["enlarge"]:
platform.rect.width = original_platform_width
bonus_timers["enlarge"] = 0
if bonus_timers["slow"] > 0 and current_time > bonus_timers["slow"]:
global dx, dy
dx = original_dx
dy = original_dy
bonus_timers["slow"] = 0
# Основной игровой цикл
reset_game()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
move_right = True
if event.key == pygame.K_LEFT:
move_left = True
if event.key == pygame.K_ESCAPE:
if game_state == GAME:
game_state = PAUSE
elif game_state == PAUSE:
game_state = GAME
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
move_right = False
if event.key == pygame.K_LEFT:
move_left = False
elif event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
if game_state == MENU or game_state == GAME_OVER:
if start_button.collidepoint(pos[0], pos[1]):
reset_game()
game_state = GAME
if exit_button.collidepoint(pos[0], pos[1]):
running = False
if game_state == PAUSE:
if continue_button.collidepoint(pos[0], pos[1]):
game_state = GAME
if start_button.collidepoint(pos[0], pos[1]):
reset_game()
game_state = GAME
if exit_button.collidepoint(pos[0], pos[1]):
running = False
if game_state == GAME:
# Движение платформы
if move_right and platform.rect.x < 500 - platform.rect.width:
platform.rect.x += 5
if move_left and platform.rect.x > 0:
platform.rect.x -= 5
# Движение мяча
ball.rect.x += dx
ball.rect.y += dy
# Проверка столкновений со стенами
if ball.rect.y < 0:
dy *= -1
if ball.rect.x < 0 or ball.rect.x > 450:
dx *= -1
# Проверка падения мяча
if ball.rect.y > 500:
lives -= 1
if lives <= 0:
game_state = GAME_OVER
else:
ball.rect.x = 200
ball.rect.y = 230
dx = original_dx
dy = original_dy
#