не могу сделать функцию вызова, чтобы заставить окно выхода появляться в pygame - PullRequest
1 голос
/ 21 февраля 2020

Я пытаюсь сделать это, если вы нажмете ES C, появится окно для выхода с текстом «Хотите выйти?» в теме. Если пользователь нажимает y , программа завершается. Я думаю, что первая проблема может быть в функции quitBox, но я вообще не знаю, что в ней не так. Для меня имя функции и переменные выглядят хорошо. когда я вызываю функцию, она говорит, что

имя 'quitBoxPosX' не определено

Я думаю, то же самое относится и к quitBoxPosY

Вот код :

import pygame
import random
pygame.init()

# variables
mainLoop = True
font1 = pygame.font.SysFont('comicsansms', 25)
font2 = pygame.font.SysFont('underline', 35)
white = [255, 255, 255]
green = [0, 150, 0]
gray = [200, 200, 200]
black = [0, 0, 0]
clickNum = 0
clickAmount = 1
FPS = pygame.time.Clock()
pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 2)
screen = pygame.display.set_mode((1300, 700))

# functions
def switchButton01(events, buttonPlusPos):
    global button02
    button02 = pygame.transform.scale(button02, (100, 100))
    screen.blit(button02, [580, 350])
    for event in events:
        if event.type == pygame.MOUSEBUTTONDOWN:
            global clickNum
            clickNum += 1
            global clickplusx, clickplusy
            clickplusx = mouse
            clickplusy = mouse
            return (clickplusx, clickplusy)
    return buttonPlusPos

def quitBox():
    global quitBoxImage
    global quitBoxPosX, quitBoxPosY
    quitBoxImage = pygame.transform.scale(quitBoxImage, (300, 200))
    quitBoxPosX = 430
    quitBoxPosY = 200
    return (quitBox, quitBoxPosX, quitBoxPosY)

# load images
button01 = pygame.image.load('button_100.png')
button02 = pygame.image.load('button_100hovered.png')
icon = pygame.image.load('icon_128.png')
buttonPlusImage = pygame.image.load('buttonPlus_32.png')
upgradeIcon = pygame.image.load('upgradesicon_64.png')
quitBoxImage = pygame.image.load('emptyGUI.png')

# title, icon
pygame.display.set_caption("incremental button")
pygame.display.set_icon(icon)

buttonPlusPos = None
while mainLoop:
    pygame.display.flip()
    FPS.tick(144)
    screen.fill(white)

    # actual content in the game
    events = pygame.event.get()
    mouse = pygame.mouse.get_pos()

    # define objects
    button01 = pygame.transform.scale(button01, (100, 100))
    click_counter_text = font1.render("Click counter: ", True, black, white)
    button01rect = button01.get_rect(center=(630, 400))
    button01collidepoint = button01rect.collidepoint(pygame.mouse.get_pos())
    click_counter = font1.render((str(clickNum)), True, black, white)
    upgradeIcon = pygame.transform.smoothscale(upgradeIcon, (30, 30))
    upgrades = font2.render('UPGRADES:', True, black)
    FPScounter = font1.render('Frames per second:' + str(int(FPS.get_fps())), True, black, white)


    # show objects
    screen.blit(FPScounter, [20, 10])
    screen.blit(button01, [580, 350])
    screen.blit(click_counter_text, [525, 50])
    upgradesBG = pygame.draw.rect(screen, gray, (1060, 44, 193, 600))
    screen.blit(upgradeIcon, [1064, 46])
    screen.blit(upgrades, [1100, 50])
    screen.blit(click_counter, [700, 50])

    if button01collidepoint:
        buttonPlusPos = switchButton01(events, buttonPlusPos)
    if buttonPlusPos:
        screen.blit(buttonPlusImage, buttonPlusPos)

    # quits
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            quitBoxPos = quitBox(quitBoxPosX, quitBoxPosY)
            if quitBoxPos:
                screen.blit(quitBoxImage(quitBoxPosX, quitBoxPosY))
                font1.render(quitBox, 'Do you want to quit?', True, black, white)
                if event.type == pygame.KEYDOWN and event.key == pygame.K_y:
                    pygame.quit()
                    quit()





1 Ответ

1 голос
/ 21 февраля 2020

quitBox должен вернуть кортеж с данными о выходе из поля, которое состоит из изображения и позиции поля:

def quitBox():
    img = pygame.transform.scale(quitBoxImage, (300, 200))
    text = font1.render('Do you want to quit?', True, black, white)
    img.blit(text, text.get_rect(center = img.get_rect().center))
    return img, (430, 200)

Вы должны инициализировать переменную quitBoxData перед основным приложением l oop и для рисования прямоугольника в l oop, если установлено quitBoxData:

quitBoxData = None
buttonPlusPos = None
while mainLoop:
    # [...]

    if quitBoxData:
        screen.blit(*quitBoxData)

    # [...]

Когда происходит событие KEYDOWN, вам придется делать разные вещи, в зависимости от того, если quitBoxData установлено или нет. Если он не установлен и нажата ES C, вам нужно вызвать quitBox и получить данные. Если quitBoxData не установлено и нажата y , оставьте приложение (mainLoop = False), иначе продолжите (quitBoxData = None):

while mainLoop:
    # [...]

    # quits
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN: 
            if quitBoxData:
                if event.key == pygame.K_y:
                    mainLoop = False
                else:
                    quitBoxData = None
            else:
                if event.key == pygame.K_ESCAPE:
                    quitBoxData = quitBox()

Полный код приложения:

import pygame
import random
pygame.init()

# variables
mainLoop = True
font1 = pygame.font.SysFont('comicsansms', 25)
font2 = pygame.font.SysFont('underline', 35)
white = [255, 255, 255]
green = [0, 150, 0]
gray = [200, 200, 200]
black = [0, 0, 0]
clickNum = 0
clickAmount = 1
FPS = pygame.time.Clock()
pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 2)
screen = pygame.display.set_mode((1300, 700))

# functions
def switchButton01(events, buttonPlusPos):
    global button02
    button02 = pygame.transform.scale(button02, (100, 100))
    screen.blit(button02, [580, 350])
    for event in events:
        if event.type == pygame.MOUSEBUTTONDOWN:
            global clickNum
            clickNum += 1
            global clickplusx, clickplusy
            clickplusx = mouse
            clickplusy = mouse
            return (clickplusx, clickplusy)
    return buttonPlusPos

def quitBox():
    img = pygame.transform.scale(quitBoxImage, (300, 200))
    text = font1.render('Do you want to quit?', True, black, white)
    img.blit(text, text.get_rect(center = img.get_rect().center))
    return img, (430, 200)

# load images
button01 = pygame.image.load('button_100.png')
button02 = pygame.image.load('button_100hovered.png')
icon = pygame.image.load('icon_128.png')
buttonPlusImage = pygame.image.load('buttonPlus_32.png')
upgradeIcon = pygame.image.load('upgradesicon_64.png')
quitBoxImage = pygame.image.load('emptyGUI.png')

# title, icon
pygame.display.set_caption("incremental button")
pygame.display.set_icon(icon)

quitBoxData = None
buttonPlusPos = None
while mainLoop:
    pygame.display.flip()
    FPS.tick(144)
    screen.fill(white)

    # actual content in the game
    events = pygame.event.get()
    mouse = pygame.mouse.get_pos()

    # define objects
    button01 = pygame.transform.scale(button01, (100, 100))
    click_counter_text = font1.render("Click counter: ", True, black, white)
    button01rect = button01.get_rect(center=(630, 400))
    button01collidepoint = button01rect.collidepoint(pygame.mouse.get_pos())
    click_counter = font1.render((str(clickNum)), True, black, white)
    upgradeIcon = pygame.transform.smoothscale(upgradeIcon, (30, 30))
    upgrades = font2.render('UPGRADES:', True, black)
    FPScounter = font1.render('Frames per second:' + str(int(FPS.get_fps())), True, black, white)


    # show objects
    screen.blit(FPScounter, [20, 10])
    screen.blit(button01, [580, 350])
    screen.blit(click_counter_text, [525, 50])
    upgradesBG = pygame.draw.rect(screen, gray, (1060, 44, 193, 600))
    screen.blit(upgradeIcon, [1064, 46])
    screen.blit(upgrades, [1100, 50])
    screen.blit(click_counter, [700, 50])

    if button01collidepoint:
        buttonPlusPos = switchButton01(events, buttonPlusPos)
    if buttonPlusPos:
        screen.blit(buttonPlusImage, buttonPlusPos)
    if quitBoxData:
        screen.blit(*quitBoxData)

    # quits
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN: 
            if quitBoxData:
                if event.key == pygame.K_y:
                    mainLoop = False
                else:
                    quitBoxData = None
            else:
                if event.key == pygame.K_ESCAPE:
                    quitBoxData = quitBox()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...