How do I make an animated background in the game menu in pygame?
How to properly embed the executing code that creates an animated background in the game in the game menu loop, which is presented below, there is also a picture of this game menu.
import pygame
from pygame.sprite import Sprite
import sys
pygame.init()
class Flame(Sprite):
def __init__(self, images, time_interval):
super().__init__()
self.images = [pygame.image.load(f'images/{i}.jpg') for i in range(1, 61)]
self.image = self.images[0]
self.time_interval = time_interval
self.index = 0
self.timer = 0
def update(self, seconds):
self.timer += seconds
if self.timer >= self.time_interval:
self.image = self.images[self.index]
self.index = (self.index + 1) % len(self.images)
self.timer = 0
def create_images():
images = []
for i in range(4):
image = pygame.Surface((256, 256))
images.append(image)
return images
def main():
images = create_images()
a = Flame(images, 0.25)
# Main loop.
while True:
seconds = clock.tick(FPS) / 300.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
a.update(seconds)
screen.fill((230, 230, 230))
screen.blit(a.image, (0, 0))
pygame.display.update()
if __name__ == '__main__':
screen = pygame.display.set_mode((1920, 1080))
clock = pygame.time.Clock()
FPS = 60
main()
The fragment of the game menu below is from the main code
class Menu:
## Покрытие False по-умолчанию
hovered = False
## Инициализация строк меню
def __init__(self, text, pos):
self.text = text
self.pos = pos
self.set_rect()
self.draw()
## Рисование и рендер
def draw(self):
self.set_rend()
screen.blit(self.rend, self.rect)
## Сам рендер
def set_rend(self):
self.rend = menu_font.render(self.text, True, self.get_color())
## Указание цветов (Покрытый\Не покрытый)
def get_color(self):
if self.hovered:
return (255, 255, 255)
else:
return (0, 255, 0)
## Рендер углов
def set_rect(self):
self.set_rend()
self.rect = self.rend.get_rect()
self.rect.topleft = self.pos
## Главное Меню
def mmenu():
## Пункты меню
menus = [Menu("NEW GAME", (870, 605)),
Menu("Help", (920, 655)),
Menu("AUTORS", (890, 705)),
Menu("EXIT", (920, 755))]
begin = True
screen.blit(mm, (0, 0))
## Рабочий цикл
while begin:
pygame.event.pump()
## Проверка пунктов меню
for menu in menus:
if menu.rect.collidepoint(pygame.mouse.get_pos()):
menu.hovered = True
else:
menu.hovered = False
menu.draw()
pygame.display.flip()
## Создал практически с нуля
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:# and event.button == 1: ## Небольшая правка
for menu in menus:
if menu.hovered and menu.text == "NEW GAME":
print("NEW GAME?")
click.play()
novel()
elif menu.hovered and menu.text == "Help":
print("Help?")
click.play()
helps()
elif menu.hovered and menu.text == "AUTORS":
print("AUTORS?")
click.play()
authors()
elif menu.hovered and menu.text == "EXIT":
begin = False
click.play()
pygame.quit()
##Анимация меню:
2
Author: VosMottor's Bot, 2020-11-09