Я блещу изображение, но оно исчезает через миллисекунду или около того - PullRequest
4 голосов
/ 21 февраля 2020

Я пытаюсь перетаскивать изображение на экране при нажатии кнопки в строке

screen.blit(buttonPlusImage,
           [random.randrange(560, 680),
            random.randrange(330, 450)])

, но изображение исчезает вскоре после обновления экрана, которое я получил (я использую эти 3 строки для Обновление дисплея: pygame.display.flip(), FPS.tick(144) и screen.fill(white)). Как я могу сделать так, чтобы изображение оставалось на экране, а не go с screen.fill (белым)? (Я думаю, что это и является причиной этого).

Я вставил код в https://dpaste.org/qGdi

import pygame
import random
pygame.init()
​
# variables
mainLoop = True
font = pygame.font.SysFont('comicsansms', 25)
white = [255, 255, 255]
green = [0, 150, 0]
gray = [140, 140, 140]
black = [0, 0, 0]
clickNum = 0
clickAmount = 1
FPS = pygame.time.Clock()
screen = pygame.display.set_mode((1300, 700))
​
# functions
def switchButton01():
    global button02
    button02 = pygame.transform.scale(button02, (100, 100))
    screen.blit(button02, [580, 350])
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            global clickNum
            clickNum += 1
            screen.blit(buttonPlusImage, [random.randrange(560, 680), random.randrange(330, 450)])
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            pygame.quit()
            quit()
​
# 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')
​
# window itself and icon
pygame.display.set_caption("incremental adventures")
pygame.display.set_icon(icon)
​
while mainLoop:
    pygame.display.flip()
    FPS.tick(144)
    screen.fill(white)
​
    # actual content in the game
​
    button01 = pygame.transform.scale(button01, (100, 100))
    screen.blit(button01, [580, 350])
    click_counter_text = font.render("Click counter: ", True, black, white)
    screen.blit(click_counter_text, [525, 50])
    button01rect = button01.get_rect(center=(630, 400))
    button01collidepoint = button01rect.collidepoint(pygame.mouse.get_pos())
    click_counter = font.render((str(clickNum)), True, black, white)
    screen.blit(click_counter, [700, 50])
    if button01collidepoint:
        switchButton01()
​
​
    # quits
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            pygame.quit()
            quit()

Ответы [ 2 ]

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

Я не все изменил.

Избегайте множественных циклов событий в приложении l oop. Обратите внимание, что pygame.event.get() удаляет все сообщения из очереди. Таким образом, либо первое, либо второе событие l oop получит события. Но не обе петли. Вы можете избавиться от этого, получая события один раз в циклах и используя список событий несколько раз:

while mainLoop:

    events = pygame.event.get()

    # [...]

    if button01collidepoint:
        switchButton01(events)

    # [...]

    for event in events:
        # [...]

Если вы хотите, чтобы изображение оставалось на экране, вы должны нарисовать его в каждый кадр. Добавьте a, в котором хранится положение кнопки buttonPlusPos, и нарисуйте положение в главном приложении l oop. Функция switchButton01 должна возвращать позицию:

buttonPlusPos = None
while mainLoop:

    # [...]

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

Функция switchButton01 не blit кнопка, она просто возвращает позицию. Кроме того, список событий передается в функцию, и функция обрабатывает события в списке, а не извлекает свой «собственный» список. В любом случае позиция изображения возвращается. Либо новая позиция, либо текущая позиция (которая может быть None):

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
            return (random.randrange(560, 680), random.randrange(330, 450))
    return buttonPlusPos

Полный код:

import pygame
import random
pygame.init()

# variables
mainLoop = True
font = pygame.font.SysFont('comicsansms', 25)
white = [255, 255, 255]
green = [0, 150, 0]
gray = [140, 140, 140]
black = [0, 0, 0]
clickNum = 0
clickAmount = 1
FPS = pygame.time.Clock()
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
            return (random.randrange(560, 680), random.randrange(330, 450))
    return buttonPlusPos

# 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')

# window itself and icon
pygame.display.set_caption("incremental adventures")
pygame.display.set_icon(icon)

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

    events = pygame.event.get()

    # actual content in the game

    button01 = pygame.transform.scale(button01, (100, 100))
    screen.blit(button01, [580, 350])
    click_counter_text = font.render("Click counter: ", True, black, white)
    screen.blit(click_counter_text, [525, 50])
    button01rect = button01.get_rect(center=(630, 400))
    button01collidepoint = button01rect.collidepoint(pygame.mouse.get_pos())
    click_counter = font.render((str(clickNum)), True, black, white)

    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:
            pygame.quit()
            quit()
1 голос
/ 21 февраля 2020

Я все изменил.

Я храню всю информацию о кнопках в словаре. Существует также state, который хранит информацию, если кнопка в норме, зависла или нажата. Я изменяю его, используя pygame.mouse.get_pressed() вместо MOUSEBUTTONDOWN. Я мог бы использовать state, чтобы выбрать изображение для отображения, но я установил изображение, когда проверяю pygame.mouse.get_pressed()

import pygame
import random

# --- constants --- (UPPER_CASE_NAMES)

WHITE = (255, 255, 255)
GREEN = (0, 150, 0)
RED   = (255, 0, 0)
GRAY  = (140, 140, 140)
BLACK = (0, 0, 0)

FPS = 25 # 144

# --- functions ---

# empty

# --- main ---

pygame.init()
screen = pygame.display.set_mode((1300, 700))

# - objects -

button01 = dict()
button01['image_normal'] = pygame.surface.Surface((100,100))#
button01['image_normal'].fill(GRAY)
#button01['image_normal'] = pygame.image.load('button_100.png')
#button01['image_normal'] = pygame.transform.scale(button01['image_normal'], (100, 100))
button01['image_hovered'] = pygame.surface.Surface((100,100))
button01['image_hovered'].fill(GREEN)
#button01['image_hovered'] = pygame.image.load('button_100hovered.png')
#button01['image_hovered'] = pygame.transform.scale(button02['image_hovered'], (100, 100))
button01['image_clicked'] = pygame.surface.Surface((100,100))
button01['image_clicked'].fill(RED)
#button01['image_clicked'] = pygame.image.load('button_100clicked.png')
#button01['image_clicked'] = pygame.transform.scale(button02['image_clicked'], (100, 100))
button01['state'] = 'normal'
button01['image'] = button01['image_normal']
button01['rect'] = button01['image'].get_rect(center=(630, 400))

plus_image = dict()
plus_image['image'] = pygame.surface.Surface((30, 30))
plus_image['image'].fill(BLACK)
plus_image['rect'] = plus_image['image'].get_rect()
plus_image['state'] = 'hidden'
#screen.blit(buttonPlusImage, [random.randrange(560, 680), random.randrange(330, 450)])

# - other -

click_number = 0

# - mainloop -

mainloop = True
clock = pygame.time.Clock()

while mainloop:

    pygame.display.flip()
    clock.tick(FPS)
    screen.fill(WHITE)

    # draw elements

    screen.blit(button01['image'], button01['rect'])
    if plus_image['state'] == 'displayed':
        screen.blit(plus_image['image'], plus_image['rect'])

    # check collisions and clicks

    if not button01['rect'].collidepoint(pygame.mouse.get_pos()):
        button01['state'] = 'normal'
        button01['image'] = button01['image_normal']
    elif pygame.mouse.get_pressed()[0]:
        button01['state'] = 'clicked'
        button01['image'] = button01['image_clicked']
    else:
        button01['state'] = 'hovered'
        button01['image'] = button01['image_hovered']

    #if button01['state'] == 'clicked':
    #    plus_image['rect'].center = [random.randrange(560, 680), random.randrange(330, 450)]
    #    plus_image['state'] = 'displayed'
    #else:
    #    plus_image['state'] = 'hidden'

    # other events

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            mainloop = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                mainloop = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            #if button01['state'] == 'hovered':
            if button01['rect'].collidepoint(event.pos):
                click_number += 1
                print('click_number:', click_number)
                plus_image['rect'].center = [random.randrange(560, 680), random.randrange(330, 450)]
                plus_image['state'] = 'displayed'
                button01['rect'].center = [random.randrange(560, 680), random.randrange(330, 450)]
        if event.type == pygame.MOUSEBUTTONUP:
            plus_image['state'] = 'hidden'

# - end -            

pygame.quit()
quit()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...