取保模組import不會產生錯誤
pygame中有一些模組是測試的,比如camera等,說不定哪天就沒了。
在寫代碼的時候需要進行容錯處理
try:import sysimport randomimport mathimport osimport getoptimport pygamefrom socket import *from pygame.locals import *except ImportError, err:print "couldn't load module. %s" % (err)sys.exit(2)
編寫自己的資源載入函數否則每次載入的時候就會寫一堆代碼,不夠簡潔。像載入音樂,網路連接的資源相關的代碼都應該封裝起來。
def load_png(name):""" Load image and return image object"""fullname = os.path.join('data', name)try:image = pygame.image.load(fullname)if image.get_alpha() is None:image = image.convert()else:image = image.convert_alpha()except pygame.error, message: print 'Cannot load image:', fullname raise SystemExit, messagereturn image, image.get_rect()
def load_sound(name): class NoneSound: def play(self): pass if not pygame.mixer: return NoneSound() fullname = os.path.join('data', name) try: sound = pygame.mixer.Sound(fullname) except pygame.error, message: print 'Cannot load sound:', wav raise SystemExit, message return sound
<本節完>