Не получается перезапустить игру при проигрыше в pygame

N3NI

Новичок
Пользователь
Янв 31, 2023
1
0
1
OC: Windows 10
Python 3.10.7, Pygame 2.1.2

Python:
import sys
import pygame as pg
from menu import menu
pg.mixer.pre_init(44100, -16, 1, 512)
pg.init()
pg.font.init()

def Collision(bx, by, ball, rect):
    if bx > 0:
        dx = ball.right - rect.left
    else:
        dx = rect.right - ball.left
    if by > 0:
        dy = ball.bottom - rect.top
    else:
        dy = rect.bottom - ball.top

    if (dx - dy) < 5:
        bx, by == -bx, by
    if dx > dy:
        by *= -1
    if dy > dx:
        bx *= -1
    return bx, by

width = 800
height = 670
scr = pg.display.set_mode((width, height))
screen = pg.Surface((800, 640))
info = pg.Surface((800, 30))
clock = pg.time.Clock()

move_menu = pg.mixer.Sound("G:\Для проекта по информатике\приложения\snd_movemeni.wav")
save = pg.mixer.Sound("G:\Для проекта по информатике\приложения\snd_save.wav")
pg.mixer.music.load('G:\Для проекта по информатике\приложения\Terra_nada_by_console_cabaret.mp3')

now_scene = None
def switch_scene(scne):
    global now_scene
    now_scene = scne

def instruction():
    run = True
    while run:
        for e in pg.event.get():

            if e.type == pg.QUIT:
                run = False
                sys.exit()
            if e.type == pg.KEYDOWN:
                if e.key == pg.K_q:
                    run = False
                    switch_scene(None)
                    save.play()

            scr.fill(pg.Color('black'))
            inst = txt.render("Здравствуй! Это инструкция.", 1, pg.Color('yellow'))
            inst_2 = txt.render("Чтобы мяч прыгал нажмите ЛЕВУЮ КНОПКУ МЫШИ.", 1, pg.Color('yellow'))
            inst_3 = txt.render("Управление платформой ЛЕВАЯ и ПРАВАЯ КНОПКИ КЛАФИАТУРЫ.", 1, pg.Color('yellow'))
            inst_4 = txt.render("Чтобы выйти из инструкции нажмите на Q", 1, pg.Color('yellow'))
            inst_5 = txt.render("К сожалению, звук для мышки не работает. Ну, пока не работает", 1, pg.Color('yellow'))
            scr.blit(inst, (12, 90))
            scr.blit(inst_2, (12, 140))
            scr.blit(inst_3, (12, 190))
            scr.blit(inst_4, (12, 210))
            scr.blit(inst_5, (12, 240))
            pg.display.flip()

class Menu:

    def __init__(self, punkts=[400, 350, u'Punkt', (255, 255, 0), (70, 130, 180)]):
        self.punkts = punkts

    def render(self, surface, font, num_punkt):
        for i in self.punkts:
            if num_punkt == i[5]:
                surface.blit(font.render(i[2], 1, i[4]), (i[0], i[1]))
            else:
                surface.blit(font.render(i[2], 1, i[3]), (i[0], i[1]))

    def menu(self):
        done = True
        pg.mixer.music.play()
        font_menu = pg.font.SysFont('Arial', 50)
        punkt = 0
        while done:
            scr.fill((0, 0, 0))

            mp = pg.mouse.get_pos()
            for i in self.punkts:
                if i[0] < mp[0] < i[0] + 155 and i[1] < mp[1] < i[1] + 50:
                    punkt = i[5]
            self.render(screen, font_menu, punkt)

            for e in pg.event.get():
                if e.type == pg.QUIT:
                    save.play()
                    exit()
                if e.type == pg.KEYDOWN:
                    if e.key == pg.K_SPACE:
                        if punkt == 0:
                            scr.blit(screen, (800, 670))
                            pg.display.update()
                            done = False
                            save.play()
                            pg.mixer.music.pause()
                        if punkt == 1:
                            exit()
                            pg.display.update()
                            save.play()
                        if punkt == 2:
                            save.play()
                            switch_scene(instruction)
                            while now_scene is not None:
                                now_scene()

                    if e.key == pg.K_UP:
                        if punkt > 0:
                            punkt -= 1
                            move_menu.play()
                    if e.key == pg.K_DOWN:
                        if punkt < len(self.punkts) - 1:
                            punkt += 1
                            move_menu.play()

                press = pg.mouse.get_pressed()
                if e.type == pg.MOUSEBUTTONDOWN and e.button == 1:
                    if punkt == 0 and press[0]:
                        scr.blit(screen, (800, 670))
                        pg.display.update()
                        done = False
                        save.play()
                    elif punkt == 1:
                        exit()
                        pg.display.update()
                        save.play()
                    elif punkt == 2:
                        save.play()
                        switch_scene(instruction)
                        while now_scene is not None:
                            now_scene()

            scr.blit(screen, (0, 0))
            pg.display.flip()
            pg.display.update()
            clock.tick(60)

text = pg.font.SysFont('Century Gothic', 40, bold=False)
txt = pg.font.SysFont('Small Font', 26, bold=True)
blk = [pg.Rect(50 * i, 50 + 50 * j, 50, 50) for i in range(16) for j in
       range(3)] 
cl_blk = [pg.Color("orange") for i in range(16) for j in range(3)]
score, kolblock = 0, len(blk)

player = pg.Rect(310, 560, 190, 16)

R = 12
ball = pg.Rect(400, 540, R, R + 12)
bx, by, life = 1, -1, 3

pusk, play, win = True, False, False

# menu
punkts = [(120, 140, u'Game', (70, 130, 180), (255, 255, 0), 0),
          (130, 210, u'Quit', (70, 130, 180), (255, 255, 0), 1),
          (140, 280, u'instruction', (70, 130, 180), (255, 255, 0), 2)]
game = Menu(punkts)
game.menu()

coll = pg.mixer.Sound("G:\Для проекта по информатике\приложения\sfx-6 (1).ogg")
hit = pg.mixer.Sound("G:\Для проекта по информатике\приложения\snd_hurt1_c.wav")
fin = pg.mixer.Sound("G:\Для проекта по информатике\приложения\win.ogg.")
mist = pg.mixer.Sound("G:\Для проекта по информатике\приложения\sfx-7.ogg")

pg.key.set_repeat(1, 1)
arrow_color = 255
gameover = False
gg = True
while gg:

    for event in pg.event.get():
        if event.type == pg.QUIT:
            exit()
        if event.type == pg.MOUSEBUTTONDOWN and gameover == False and win == False:
            pusk, play = False, True

       [COLOR=rgb(209, 72, 65)] if event.type == pg.KEYDOWN: #Вот в этом месте должна перезапускаться игра
            if event.key == pg.K_e:
                gameover == False
                player.x, player.y = 310, 560
                ball.x, ball.y = 400, 540
                score = 0
                life = 3
                pg.display.update()
                blk = [pg.Rect(50 * i, 50 + 50 * j, 50, 50) for i in range(16) for j in
                       range(3)]
                cl_blk = [pg.Color("orange") for i in range(16) for j in range(3)]
                pg.draw.rect(scr, pg.Color('blue'), player)
                pg.draw.circle(scr, pg.Color('white'), ball.center, R)

                play, pusk = False, True
                pg.display.update()[/COLOR]

    if gameover == False and win == False:
        key = pg.key.get_pressed()
        if key[pg.K_RIGHT] and player.right < width:
            player.x += 10
            if pusk == True:
                ball.x += 10
        if key[pg.K_LEFT] and player.left > 0:
            player.x -= 10
            if pusk == True:
                ball.x -= 10

    if play == True:
        ball.x += 4 * bx
        ball.y += 4 * by

        if ball.x < R or ball.x > width - R:
            bx *= -1
        if ball.y - 50 < R:
            by *= -1

        if ball.colliderect(player) and by > 0:
            bx, by = Collision(bx, by, ball, player)

        destroy = ball.collidelist(blk)
        if destroy != -1:
            destrect = blk.pop(destroy)

            bx, by = Collision(bx, by, ball, destrect)

            score += 1
            coll.play()

        if ball.y > height + R:
            play, pusk = False, True

            player.x, player.y = 310, 560
            ball.x, ball.y = 400, 540

            life -= 1
            hit.play()

            if life == 0:
                gameover = True
                mist.play()

        if score == kolblock:
            play, win = False, True
            fin.play()
    scr.fill(pg.Color('black'))

    scr.blit(info, (0, 0))
    scr.blit(screen, (0, 30))

    pg.draw.aaline(scr, pg.Color('orange'), [0, 60], [width, 60])
    [pg.draw.rect(scr, cl_blk[color], i) for color, i in enumerate(blk)]
    if gameover == False:
        pg.draw.rect(scr, pg.Color('blue'), player)
        pg.draw.circle(scr, pg.Color('white'), ball.center, R)

    screen.fill((50, 50, 50))
    info.fill((45, 80, 45))
    arrow_color += 0.1
    if arrow_color > 254:
        arrow_color = 50

    Tlife = text.render(f'Life: {life}', 1, pg.Color('yellow'))
    scr.blit(Tlife, (15, 5))
    Tscore = text.render(f'Score: {score}/{kolblock}', 1, pg.Color('yellow'))
    scr.blit(Tscore, (160, 5))
    if gameover == True:
        Tgameover = text.render('Game over!', 1, pg.Color('RED'))
        scr.blit(Tgameover, (10, 200))
        Tgameover_1 = text.render("press E, if you want pestart game", 1, pg.Color('red'))
        scr.blit(Tgameover_1, (10, 230))
    elif win:
        Twin = text.render('You win!', 1, pg.Color('Blue'))
        scr.blit(Twin, (10, 200))

    pg.display.flip()
    pg.time.delay(10)
pg.quit()
 

Форум IT Специалистов