我有一个函数,允许用户单击图标并设置布尔值,以便主循环知道要执行的操作。该代码将用作单击喷枪图标->;将airbrushMode
设置为true->;返回airbrushMode
,以便paintScreen()
可以检测到它->;执行while循环中由airbrushMode
设置的操作。我添加了打印语句来定位问题。该变量确实会更改,但不会返回该变量,而且喷枪功能不起作用。当我在paintScreen()
内将airbrushMode
设置为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')
与其在
icon()
中检查事件,不如在按下按钮时发布事件,代码可能会更流畅然后在主循环中处理这些问题:
如果是我,我会制作一套自己的事件类型:
允许:
您的问题是
icon
不试图更改任何全局变量;它严格地处理它的输入参数和局部变量。如果希望它更改自身范围之外的变量,则需要添加在你的功能的顶端
此外,如果希望
paintScreen
识别全局变量,则必须具有该变量的全局存在性(顶级用法),或者paintScreen
还需要global
声明有关详细信息,请在Python中查找全局变量
相关问题 更多 >
编程相关推荐