#python #windows #pygame
#python #Windows #pygame
Вопрос:
У меня есть некоторый код, который создает кнопку, и код, создающий некоторый текст, который отображается на экране. Цель состоит в том, чтобы при нажатии кнопки добавить 1 к переменной и отразить измененное на экране (т. Е. При нажатии кнопки значение на экране меняется с 0 на 1, а затем с 1 на 2 и так далее).
Функция кнопки:
def button(message, x, y, w, h, activeRGB, inactiveRGB, action=None): #example of color param for line 61/63
mouse = pygame.mouse.get_pos() #get location of mouse recorded by pygame
click = pygame.mouse.get_pressed()
if x w > mouse[0] > x and y h > mouse[1] > y:
pygame.draw.rect(gameDisplay, activeRGB, (x, y, w, h))
if click[0] ==1 and action != None:
if action == "countUP":
clickCounter = 1
print(str(clickCounter)) # print to check that the button actually changes the value
pygame.display.update()
else:
pygame.draw.rect(gameDisplay, inactiveRGB, (x, y, w, h))
smallText = pygame.font.Font("freesansbold.ttf", 20)
textSurf, textRect = textBox(message, mediumText)
textRect.center = ( (x (w/2)), y (h/2))
gameDisplay.blit(textSurf, textRect)
Логика, которую я пока
gameDisplay.fill(white)
pygame.display.update()
clickCounter = str(clickCounter)
textObject(clickCounter, black, mediumText, 200, 200)
closeGame = False
while not closeGame: # this keeps the window from shutting down
for thing in pygame.event.get():
if thing.type == pygame.QUIT:
closeGame = True
print(thing)
button("Click me!", 300, 300, 100, 100, blue, brightBlue, "countUP")
pygame.display.update()
clock.tick(20)
gameDisplay.fill(white)
pygame.display.update()
#logicloop()
Функция button, похоже, изменяет значение clickCounter
, но это не отражается на экране. Я предполагал, что отсутствует команда blit или обновление экрана, хотя ничего из того, что я пробовал, не сработало.
По какой-то причине, когда у меня был этот блок кода, настроенный как функция, которая затем вызывается, он выполнялся без gameDisplay.fill(white)
или любого другого отображаемого на экране элемента, как бы мне настроить его как функцию, чтобы упростить добавление большего к логике?
Весь код:
import pygame
pygame.init()
displayWidth = 700
displayHeight = displayWidth
gameDisplay = pygame.display.set_mode((700,700))
clock = pygame.time.Clock()
black = (0, 0, 0)
brightBlue = (0, 0, 225)
blue = (0, 0, 255)
white = (255, 255, 255) #predef colors to make temp rgb value coding easier
closeGame = False
mediumText = pygame.font.Font("freesansbold.ttf", 70) #initalize font
clickCounter = 0
#def fontSize (pxsize):
#pygame.font.Font("freesandsbold.ttf", pxsize)
def textObject (text, color, font, x, y):
storedGenerate = font.render(text, 1, ((color)))
gameDisplay.blit(storedGenerate, (x,y))
def textBox(text, font): #purely for returning rectangle around font// used for btn function only, tObject for displaying text
textSurface = font.render(text, True, black) #swap black for rgb later
return textSurface, textSurface.get_rect()
def button(message, x, y, w, h, activeRGB, inactiveRGB, action=None): #example of color param for line 61/63
mouse = pygame.mouse.get_pos() #get location of mouse recorded by pygame
click = pygame.mouse.get_pressed()
global clickCounter
clickCounter = 0
if x w > mouse[0] > x and y h > mouse[1] > y:
pygame.draw.rect(gameDisplay, activeRGB, (x, y, w, h))
if click[0] ==1 and action != None:
if action == "countUP":
clickCounter = 1
print(str(clickCounter))
pygame.display.update()
else:
pygame.draw.rect(gameDisplay, inactiveRGB, (x, y, w, h))
#smallText = pygame.font.Font("freesansbold.ttf", 20) # constant has been declared, try deleting line when done w/ proj
smallText = pygame.font.SysFont('Times New Roman', 20)
textSurf, textRect = textBox(message, smallText)
textRect.center = ( (x (w/2)), y (h/2))
gameDisplay.blit(textSurf, textRect)
gameDisplay.fill(white)
pygame.display.update()
clickCounter = str(clickCounter)
textObject(clickCounter, black, mediumText, 200, 200)
closeGame = False
while not closeGame: # this keeps the window from shutting down
for thing in pygame.event.get():
if thing.type == pygame.QUIT:
closeGame = True
print(thing)
button("Click me!", 300, 300, 100, 100, blue, brightBlue, "countUP")
pygame.display.update()
clock.tick(20)
gameDisplay.fill(white)
pygame.display.update()
#logicloop()
pygame.quit()
quit()
Ответ №1:
Первая проблема заключается в том, что числовое значение, хранящееся в clickCounter
, преобразуется в строку. Удалить:
lickCounter = str(clickCounter)
В функции button
значение clickCounter
постоянно устанавливается равным 0. Удалите и это:
def button(message, x, y, w, h, activeRGB, inactiveRGB, action=None):
mouse = pygame.mouse.get_pos() #get location of mouse recorded by pygame
click = pygame.mouse.get_pressed()
global clickCounter
# clickCounter = 0 <------ delete
# [...]
Вы пропустили рисование измененного текста в основном цикле. Перед отображением текста «старый» текст должен быть очищен. Непрерывно перерисовывайте всю сцену в главном цикле приложения.
Это означает, что дисплей должен быть заполнен цветом фона, а текст и кнопка должны быть перерисованы:
while not closeGame: # this keeps the window from shutting down
for thing in pygame.event.get():
if thing.type == pygame.QUIT:
closeGame = True
print(thing)
gameDisplay.fill(white)
button("Click me!", 300, 300, 100, 100, blue, brightBlue, "countUP")
textObject(str(clickCounter), black, mediumText, 200, 200)
pygame.display.update()
clock.tick(20)
Комментарии:
1. Это работает, и теперь я понимаю, что было не так. Как я могу остановить удержание кнопки и ее увеличение? Похоже, что нет простого способа добиться этого, видя, как
pygame.mouse.get_pressed()
работает.