pygame常識&技巧(2)

來源:互聯網
上載者:User
取保模組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

<本節完>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.