Pygame访问函数中的变量

时间:2016-05-04 02:23:31

标签: python function pygame

嘿我一直试图在函数中调用pygame事件来减少代码的混乱。但由于全局变量的错误,我无法执行该过程。任何帮助,将不胜感激。

from pygame.locals import *
import pygame, sys
def color():
    screen.fill((85,163,48)) 

def events():
for event in pygame.event.get():
    if event.type == QUIT:
        pygame.quit()
    if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
        print "left"
#sets the game map variables
tilesize = 100
map_width = 600
map_height = 300
#initialises the game screen setting it up with the game map variables
pygame.init()
screen = pygame.display.set_mode((map_width,map_height))

while True:
    color()
    events()
    pygame.display.update()

1 个答案:

答案 0 :(得分:1)

如果您无法在函数内本地访问值,那么答案就是将值传递给函数。这样的简单就足够了:

def events(ev_list):
    for event in ev_list:
        if event.type == QUIT:
            pygame.quit()

在您的游戏循环中,您将其称为:

event_list = pygame.event.get()
events(event_list)

或者(不太理想)您可以从函数中导入库或声明变量global