How to make some kind of "animation" of preparation

Viewed 25

I need my character to be displayed in a while loop when the "locate" variable is "4". First he shows the number three on his fingers, then after a second pause the number two, then 1 and after the variable "locate" has changed the value to "5". My character is a picture in jpg format. Initially, I tried to do it with this function:

def animation():
    screen.blit(step3, step3_rect)
    pygame.mixer.Sound.play(step_sound)
    pygame.time.wait(1000)
    screen.blit(step2, step2_rect)
    pygame.mixer.Sound.play(step_sound)
    pygame.time.wait(1000)
    screen.blit(step1, step1_rect)
    pygame.mixer.Sound.play(step_sound)
    pygame.time.wait(1000)
    

but it didn't work.

Full Code:

import pygame
import pygame_widgets as pw
import pygame_textinput

pygame.init()  # Инициализируем модуль pygame

width = 1920 # ширина игрового окна
height = 1080  # высота игрового окна
fps = 30  # частота кадров в секунду
game_name = "Тренажёр"  # название нашей игры

snd_dir = 'sound/'  # Путь до папки со звуками
img_dir = 'images/'  # Путь до папки со спрайтами

# Цвета
BLACK = "#000000"
WHITE = "#FFFFFF"
RED = "#FF0000"
GREEN = "#008000"
BLUE = "#0000FF"
CYAN = "#00FFFF"

code = "Number"

OneNumber = list(range(1, 10))
TwoNumber = list(range(10, 100))
ThreeNumber = list(range(100, 1000))

button_sound = pygame.mixer.Sound(snd_dir + 'button.mp3')
step_sound = pygame.mixer.Sound(snd_dir + 'tick.mp3')

base_font = pygame.font.Font(None, 100)
user_name = 'Ученик'

input_Name_rect = pygame.Rect(820, 500, 450, 70)
color = pygame.Color("Black")

user_code = ''






class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)  #call Sprite initializer
        self.image = pygame.image.load(image_file)
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = location







def print_text(message, x, y, font_color=(0, 0, 0), font_type='ttf/Slimamif.ttf', font_size=30):
    font_type = pygame.font.Font(font_type, font_size)
    text = font_type.render(message, True, font_color)
    screen.blit(text, (x, y))


class Button:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.inactive_color = (255, 165, 0)
        self.active_color = (13, 162, 58)
        self.button_Big = False
        self.button_active = False

    def draw(self, x, y, message, clicked, action=None):
        mouse = pygame.mouse.get_pos()

        button_rect = pygame.Rect(x, y, self.width, self.height)
        mouse_on_button = button_rect.collidepoint(mouse)
        if mouse_on_button and clicked:
            self.button_active = not self.button_active
            pygame.mixer.Sound.play(button_sound)

        color = self.inactive_color
        if mouse_on_button or self.button_active:
            color = self.active_color

        pygame.draw.rect(screen, color, button_rect)

        if self.button_Big == True:
            print_text(message, x, y, font_size=60)
        else: print_text(message, x + 10, y + 10)


BackGround = Background(img_dir + "fon3.jpg", [0,0])
BackGroundImages = []

# Создаем игровой экран
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption(game_name)  # Заголовок окна
icon = pygame.image.load(img_dir + 'icon.png')  # загружаем файл с иконкой
pygame.display.set_icon(icon)  # устанавливаем иконку в окно

timer = pygame.time.Clock()  # Создаем таймер pygame
run = True
locate = -1

Multy = None

MultiButton = Button(275, 100)
MultiButton.button_Big = True

SplitButton = Button(200, 100)
SplitButton.button_Big = True



# Кнопки умножения
funcbutton1 = Button(315, 55)
funcbutton2 = Button(300, 55)
funcbutton3 = Button(300, 55)
funcbutton4 = Button(300, 55)

fullCoureButton = Button(250, 55)
fullCoureButton.active_color = (255, 0, 0)


fullCourseSplitButton = Button(250, 55)
fullCourseSplitButton.active_color = (255, 0, 0)


# Кнопки деления
SplitFuncButton1 = Button(300, 55)
SplitFuncButton2 = Button(300, 55)
SplitFuncButton3 = Button(300, 55)
SplitFuncButton4= Button(300, 55)

NextButton = Button(294, 90)
NextButton.button_Big = True



exitButton = Button(250, 55)

startButton = Button(145, 95)
startButton.button_Big = True

backButton = Button(165,95)
backButton.button_Big = True


step3 = pygame.image.load(img_dir + "step3.jpg")
step3_rect = step3.get_rect()
step3_rect.x = width // 2
step3_rect.y = height // 2


step2 = pygame.image.load(img_dir + "step2.jpg")
step2_rect = step2.get_rect()
step2_rect.x = width // 2
step2_rect.y = height // 2


step1 = pygame.image.load(img_dir + "step1.jpg")
step1_rect = step1.get_rect()
step1_rect.x = width // 2
step1_rect.y = height // 2

Enemy = pygame.image.load(img_dir + "Enemy.png")

Enemy_rect = Enemy.get_rect()
Enemy_rect.x = 1620
Enemy_rect.y = 100

xCode = -830
yCode = -800

while run:  # Начинаем бесконечный цикл
    if locate == -1:



        timer.tick(fps)  # Контроль времени (обновление игры)
        left_click = False
        events = pygame.event.get()
        for event in events:  # Обработка ввода (события)
            if event.type == pygame.QUIT:  # Проверить закрытие окна
                run = False  # Завершаем игровой цикл
            if event.type == pygame.MOUSEBUTTONDOWN:
                left_click = event.button = 1
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_BACKSPACE:
                    user_code = user_code[:-1]
                else:
                    user_code += event.unicode

            if exitButton.button_active == True:
                run = False

        # Рендеринг (прорисовка)

        screen.fill(WHITE)  # Заливка заднего фона
        screen.blit(BackGround.image, BackGround.rect)

        text_surface = base_font.render(user_code, True, (0, 0, 0))
        screen.blit(text_surface, (input_Name_rect.x + 5, input_Name_rect.y + 5))

        if NextButton.button_active == True and user_code == code:
            NextButton.button_active = False
            locate = 0
            print(user_code)

        elif NextButton.button_active == True and user_code != code:
            NextButton.button_active = False
            xCode = 830
            yCode = 800


        input_Name_rect.w = (text_surface.get_width() + 10)

        print_text("Введите секретный код", 830, 400)

        pygame.draw.rect(screen, color, input_Name_rect, 3)

        NextButton.draw(800, 650, "Продолжить", left_click)

        print_text("Код неверный!", xCode, yCode)

        exitButton.draw(1820, 0, "Выход", left_click)

        pygame.display.update()  # Переворачиваем экран






    if locate == 0:
        timer.tick(fps)  # Контроль времени (обновление игры)
        left_click = False
        events = pygame.event.get()
        for event in events:  # Обработка ввода (события)
            if event.type == pygame.QUIT:  # Проверить закрытие окна
                run = False  # Завершаем игровой цикл
            if event.type == pygame.MOUSEBUTTONDOWN:
                left_click = event.button = 1
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_BACKSPACE:
                    user_name = user_name[:-1]
                else:
                    user_name += event.unicode

            if exitButton.button_active == True:
                run = False
            if NextButton.button_active == True:
                NextButton.button_active = False
                locate = 1
                print(user_name)

        # Рендеринг (прорисовка)

        screen.fill(WHITE)  # Заливка заднего фона
        screen.blit(BackGround.image, BackGround.rect)

        text_surface = base_font.render(user_name, True, (0, 0, 0))
        screen.blit(text_surface, (input_Name_rect.x + 5, input_Name_rect.y + 5))

        input_Name_rect.w = (text_surface.get_width() + 10)

        print_text("Введите Своё имя:", 830, 400)

        pygame.draw.rect(screen, color, input_Name_rect, 3)

        NextButton.draw(800, 650, "Продолжить", left_click)

        exitButton.draw(1820, 0, "Выход", left_click)

        pygame.display.update()  # Переворачиваем экран





    if locate == 1:
        timer.tick(fps)  # Контроль времени (обновление игры)
        left_click = False
        for event in pygame.event.get():  # Обработка ввода (события)
            if event.type == pygame.QUIT:  # Проверить закрытие окна
                run = False  # Завершаем игровой цикл
            if event.type == pygame.MOUSEBUTTONDOWN:
                left_click = event.button = 1

            if exitButton.button_active == True:
                run = False

            if MultiButton.button_active == True:
                Multy = True
                locate = 2
                MultiButton.button_active = False

            if SplitButton.button_active == True:
                Multy = False
                locate = 3
                SplitButton.button_active = False



        # Рендеринг (прорисовка)

        screen.fill(WHITE)  # Заливка заднего фона
        screen.blit(BackGround.image, BackGround.rect)

        MultiButton.draw(830, 300, "Умножение", left_click)
        SplitButton.draw(865, 450, "Деление", left_click)

        exitButton.draw(1820, 0, "Выход", left_click)

        pygame.display.update()  # Переворачиваем экран

    if locate == 2:
        timer.tick(fps)  # Контроль времени (обновление игры)
        left_click = False
        for event in pygame.event.get():  # Обработка ввода (события)
            if event.type == pygame.QUIT:  # Проверить закрытие окна
                run = False  # Завершаем игровой цикл
            if event.type == pygame.MOUSEBUTTONDOWN:
                left_click = event.button = 1

            if exitButton.button_active == True:
                run = False

            if backButton.button_active == True:
                locate = 1
                backButton.button_active = False

            if startButton.button_active == True:
                startButton.button_active = False
                locate = 4



        # Рендеринг (прорисовка)

        screen.fill(WHITE)  # Заливка заднего фона
        screen.blit(BackGround.image, BackGround.rect)

        print_text("Выберите режим:", 0, 0)

        funcbutton1.draw(10, 100, "Однознач. на Однознач.", left_click)
        funcbutton2.draw(330, 100, "Однознач. на Двузнач.", left_click)
        funcbutton3.draw(635, 100, "Однознач. на Трёхзнач.", left_click)
        funcbutton4.draw(940, 100, "Двузнач. на Двузнач.", left_click)
        fullCoureButton.draw(1445, 100, "Полный курс", left_click)
        exitButton.draw(1820, 0, "Выход", left_click)

        backButton.draw(390, 640, "НАЗАД", left_click)


        screen.blit(Enemy, Enemy_rect)

        if funcbutton1.button_active == True and funcbutton2.button_active == True and funcbutton3.button_active == True and funcbutton4.button_active == True:
            funcbutton1.button_active = False
            funcbutton2.button_active = False
            funcbutton3.button_active = False
            funcbutton4.button_active = False
            fullCoureButton.button_active = True

        if fullCoureButton.button_active == True:
            funcbutton1.button_active = False
            funcbutton2.button_active = False
            funcbutton3.button_active = False
            funcbutton4.button_active = False

        if funcbutton1.button_active == True or funcbutton2.button_active == True or funcbutton3.button_active == True or funcbutton4.button_active == True or fullCoureButton.button_active == True:
            startButton.draw(890, 540, "СТАРТ", left_click)

        pygame.display.update()  # Переворачиваем экран

    if locate == 3:
        timer.tick(fps)  # Контроль времени (обновление игры)
        left_click = False
        for event in pygame.event.get():  # Обработка ввода (события)
            if event.type == pygame.QUIT:  # Проверить закрытие окна
                run = False  # Завершаем игровой цикл
            if event.type == pygame.MOUSEBUTTONDOWN:
                left_click = event.button = 1

            if exitButton.button_active == True:
                run = False

            if backButton.button_active == True:
                locate = 1
                backButton.button_active = False


        # Рендеринг

        screen.fill(WHITE)  # Заливка заднего фона
        screen.blit(BackGround.image, BackGround.rect)

        print_text("Выберите режим:", 0, 0)

        SplitFuncButton1.draw(25, 100, "Двузнач. на Однознач.", left_click)
        SplitFuncButton2.draw(330, 100, "Двузнач. на Двузнач.", left_click)
        SplitFuncButton3.draw(635, 100, "Трёхзнач. на Однознач.", left_click)
        SplitFuncButton4.draw(940, 100, "Трёхзнач. на Двузнач.", left_click)
        fullCourseSplitButton.draw(1445, 100, "Полный курс", left_click)

        if SplitFuncButton1.button_active == True and SplitFuncButton2.button_active == True and SplitFuncButton3.button_active == True and SplitFuncButton4.button_active == True:
            fullCourseSplitButton.button_active = True
            SplitFuncButton1.button_active = False
            SplitFuncButton2.button_active = False
            SplitFuncButton3.button_active = False
            SplitFuncButton4.button_active = False

        if fullCourseSplitButton.button_active == True:
            SplitFuncButton1.button_active = False
            SplitFuncButton2.button_active = False
            SplitFuncButton3.button_active = False
            SplitFuncButton4.button_active = False


        if SplitFuncButton1.button_active == True or SplitFuncButton2.button_active == True or SplitFuncButton3.button_active == True or SplitFuncButton4.button_active == True or fullCourseSplitButton.button_active == True:
            startButton.draw(890, 540, "СТАРТ", left_click)


        screen.blit(Enemy, Enemy_rect)


        exitButton.draw(1820, 0, "Выход", left_click)

        backButton.draw(390, 640, "НАЗАД", left_click)


        pygame.display.update()  # Переворачиваем экран


    if locate == 4:
        timer.tick(fps)  # Контроль времени (обновление игры)
        left_click = False
        events = pygame.event.get()
        for event in events:  # Обработка ввода (события)
            if event.type == pygame.QUIT:  # Проверить закрытие окна
                run = False  # Завершаем игровой цикл

            if exitButton.button_active == True:
                run = False



        # Рендеринг (прорисовка)

        screen.fill(WHITE)  # Заливка заднего фона


        pygame.display.update()  # Переворачиваем экран


pygame.quit()  # Корректно завершаем игру
0 Answers
Related