我有一个功能,允许用户单击图标并设置一个布尔值,以便主循环知道要执行哪个操作。该代码旨在用作单击喷枪图标->将airbrushMode
设置为true->返回airbrushMode
,以便paintScreen()
可以检测到->执行airbrushMode
中设置的操作while循环。我添加了打印语句以查找问题。变量确实会更改,但不会返回该变量,并且喷枪功能不起作用。当我在airbrushMode
内部将paintScreen()
设置为true但在函数中和函数外部将其设置为false时,它确实起作用。
主要功能
def paintScreen():
airbrushMode = False
paint = True
gameDisplay.fill(cyan)
message_to_screen('Welcome to PyPaint', black, -300, 'large')
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
pygame.draw.rect(gameDisplay, white, (50, 120, displayWidth - 100, displayHeight - 240))
while paint:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button('X', 20, 20, 50, 50, red, lightRed, action = 'quit')
icon(airbrushIcon, white, 50, displayHeight - 101, 51, 51, white, grey, 'airbrush')
icon(pencilIcon, white, 140, displayHeight - 101, 51, 51, white, grey, 'pencil')
icon(calligraphyIcon, white, 230, displayHeight - 101, 51, 51, white, grey, 'calligraphy')
pygame.display.update()
if cur[0] >= 50 <= displayWidth - 50 and cur[1] >= 120 <= displayHeight - 120:
if airbrushMode == True:
airbrush()
创建图标并检测动作,然后将其返回的功能
def icon(icon, colour, x, y, width, height, inactiveColour, activeColour, action = None):
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + width > cur[0] > x and y + height > cur[1] > y:#if the cursor is over the button
pygame.draw.rect(gameDisplay, activeColour, (x, y, width, height))
gameDisplay.blit(icon, (x, y))
if click[0] == 1 and action != None: #if clicked
print('click')
if action == 'quit':
pygame.quit()
quit()
elif action == 'airbrush':
airbrushMode = True
print('airbrush set')
return airbrushMode
print('airbrush active')
答案 0 :(得分:2)
您的问题是icon
不会尝试更改任何全局变量;它严格处理其输入参数和局部变量。如果您要更改超出其自身范围的变量,则需要添加
global airbrushMode
位于函数顶部。
此外,如果您希望paintScreen
能够识别全局变量,那么您必须具有该变量的全局存在性(顶级用法),或者paintScreen
也需要global
声明。
有关详细信息,请在Python中查找全局变量。
答案 1 :(得分:1)
与其检查icon()
中的事件,不如在按下按钮时发布事件,代码将更加流畅。
def icon(icon, colour, x, y, width, height, inactiveColour, activeColour, action = None):
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + width > cur[0] > x and y + height > cur[1] > y:#if the cursor is over the button
pygame.draw.rect(gameDisplay, activeColour, (x, y, width, height))
gameDisplay.blit(icon, (x, y))
if click[0] == 1 and action != None: #if clicked
print('click')
pygame.event.post( pygame.USEREVENT + 1, {} )
然后在主循环中处理这些问题:
while paint:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.USEREVENT + 1
airbrushMode = True
如果是我,我将设置一组自己的事件类型:
import enum
...
class MyEvents( enum.Enum ):
AIRBRUSH = pygame.USEREVENT + 1
PEN = pygame.USEREVENT + 2
PENCIL = pygame.USEREVENT + 3
允许:
pygame.event.post( MyEvents.AIRBRUSH, {} )
...
elif ( event.type == MyEvents.AIRBRUSH ):
airbrushMode = True