遊戲裏面通常是確定會出現文字顯示的,即便是俄羅斯方塊也應該顯示分數。那麼咱們應該怎樣來顯示文字呢,今天一塊兒學習一下pygame的font模塊。程序員
使用字體模塊web
pygame能夠直接調用系統字體,也能夠調用TTF字體。爲了使用字體,首先應該建立一個Font對象,對於系統自帶的字體,應該這樣調用:api
>>> font1 = pygame.font.SysFont('arial', 16)
第一個參數是字體名,第二個參數是字號。正常狀況下系統裏都會有arial字體,若是沒有會使用默認字體,默認字體和各個系統有關。微信
可使用pygame.font.get_fonts()來得到當前系統全部可用字體:app
>>> pygame.font.get_fonts() ['stsong', 'rod', 'microsoftyahei', 'mingliupmingliumingliuhkscs', 'stxingkai', 'euclidmathtwo', 'impact', 'simplifiedarabicfixed', 'wingdings2', 'wingdings3', 'lucidabright', 'verdana', 'mistral', 'gigi', 'traditionalarabic', 'lucidacalligraphy', 'lucidasanstypewriteroblique', 'stzhongsong', 'tempussansitc', 'microsoftuighur', 'georgia', 'wingdings', 'goudystout', 'candara', 'pristina', 'microsoftjhengheimicrosoftjhengheiui', 'gulimgulimchedotumdotumche', 'lisu', 'levenim', 'lucidafaxregular', 'lucidasansregular', 'lucidafax', 'tahoma', 'blackadderitc', 'niagarasolid', 'euclid', 'bernardcondensed', 'lucidasanstypewriterregular', 'bauhaus93', 'corbel', 'segoeuisymbol', 'franklingothicdemi', 'poorrichard', 'centaur', 'stxinwei', 'arialblack', 'nirmalaui', 'msoutlook', 'microsoftjhenghei', 'tigerexpert', 'malgungothic', 'felixtitling', 'freesiaupc', 'colonna', 'franklingothicheavy', 'harrington', 'jokerman', 'extra', 'lucidasanstypewriter', 'rockwellcondensed', 'stfangsong', 'microsoftnewtailue', 'aharoni', 'twcen', 'britannic', 'mvboli', 'goudyoldstyle', 'microsoftsansserif', 'gisha', 'fzshuti', 'simsunnsimsun', 'estrangeloedessa', 'symboltigerexpert', 'juiceitc', 'onyx', 'tiger', 'webdings', 'franklingothicmediumcond', 'edwardianscriptitc', 'vani', 'couriernew', 'freestylescript', 'palacescript', 'bodonicondensed', 'msminchomspmincho', 'andalus', 'footlight', 'vivaldi', 'century', 'arialrounded', 'papyrus', 'ocraextended', 'simsunextb', 'arialms', 'microsoftphagspa', 'hightowertext', 'stxihei', 'bodoni', 'haettenschweiler', 'berlinsansfbdemi', 'twcencondensedextra', 'elephant', 'angsananew', 'widelatin', 'meiryomeiryoboldmeiryouiboldmeiryouibolditalic', 'segoeuisemilight', 'shruti', 'arabictypesetting', 'timesnewroman', 'lucidahandwriting', 'maturascriptcapitals', 'engravers', 'segoeuisemibold', 'vladimirscript', 'kaiti', 'mingliuextbpmingliuextbmingliuhkscsextb', 'miriamfixed', 'kokila', 'chiller', 'fangsong', 'niagaraengraved', 'gillsansextcondensed', 'raavi', 'rockwellextra', 'gillsansultra', 'browalliaupc', 'euclidmathone', 'broadway', 'dilleniaupc', 'stkaiti', 'parchment', 'franklingothicdemicond', 'gadugi', 'calibri', 'arial', 'curlz', 'batangbatangchegungsuhgungsuhche', 'shonarbangla', 'extratiger', 'maiandragd', 'simhei', 'narkisim', 'segoeui', 'aparajitaitali', 'calisto', 'leelawadee', 'lucidasansroman', 'cooperblack', 'sakkalmajalla', 'berlinsansfb', 'consolas', 'frenchscript', 'microsoftjhengheimicrosoftjhengheiuibold', 'sylfaen', 'algerian', 'microsoftyaheimicrosoftyaheiui', 'microsoftyaheimicrosoftyaheiuibold', 'oldenglishtext', 'bradleyhanditc', 'aparajita', 'kodchiangupc', 'gillsans', 'palatinolinotype', 'gloucesterextracondensed', 'gabriola', 'lucidaconsole', 'plantagenetcherokee', 'meiryomeiryomeiryouimeiryouiitalic', 'cordiaupc', 'erasdemiitc', 'segoeprint', 'nyala', 'harlowsolid', 'forte', 'franklingothicmedium', 'laoui', 'microsofttaile', 'bookantiqua', 'symbol', 'lucidasans', 'garamond', 'vrinda', 'agencyfb', 'constantia', 'jasmineupc', 'khmerui', 'kalinga', 'kartika', 'euphemia', 'frankruehl', 'vinerhanditc', 'snapitc', 'euclidsymbol', 'david', 'baskervilleoldface', 'segoescript', 'cambria', 'daunpenh', 'bodonipostercompressed', 'monotypecorsiva', 'perpetuatitling', 'trebuchetms', 'msreferencesansserif', 'imprintshadow', 'centuryschoolbook', 'browallianew', 'sthupo', 'stencil', 'script', 'bookmanoldstyle', 'ebrima', 'msgothicmspgothicmsuigothic', 'copperplategothic', 'modernno20', 'utsaahitali', 'microsoftyibaiti', 'dfkaisb', 'comicsansms', 'magneto', 'rockwell', 'ravie', 'youyuan', 'bodoniblack', 'latha', 'irisupc', 'dokchampa', 'rage', 'msreferencespecialty', 'euclidfraktur', 'playbill', 'cambriacambriamath', 'kunstlerscript', 'twcencondensed', 'showcardgothic', 'bell', 'mangal', 'cordianew', 'californianfb', 'stliti', 'kristenitc', 'erasmediumitc', 'fencesplain', 'euclidextra', 'moolboran', 'informalroman', 'mongolianbaiti', 'symboltiger', 'centurygothic', 'franklingothicbook', 'castellar', 'iskoolapota', 'microsofthimalaya', 'erasitc', 'kokilaitali', 'stcaiyun', 'fzyaoti', 'gillsanscondensed', 'simplifiedarabic', 'vijaya', 'gillsansultracondensed', 'miriam', 'perpetua', 'bookshelfsymbol7', 'gautami', 'utsaah', 'lilyupc', 'tunga', 'angsanaupc', 'brushscript', 'eucrosiaupc']
還有一種調用方法是使用本身的ttf字體:cors
my_font = pygame.font.Font("my_font.ttf", 16)
這個方法的優點是你能夠把字體文件和遊戲一塊兒打包分發,避免玩家電腦上沒有這個字體沒法顯示的問題。curl
一旦你有了Font對象,你就能夠用render方法來寫字了,而後經過blit方法blit到屏幕上;ide
>>> text = font1.render("Input your text here",True,(0,0,0),(255,255,255))
render方法的第一個參數是寫入的文字內容;第二個是布爾值,說明是否開啓抗鋸齒;第三個是字體自己的顏色;第四個是背景的顏色。若是不想有背景色,也就是讓背景透明的話,能夠不加第四個參數。oop
另外,若是是Python2,想顯示中文的話,要使用能用中文的字體,而後用u前綴字符串,也就是用Unicode編碼。最後還得在文件頭加上,# -*- coding: utf-8 -*-這樣的註釋文字。post
字體模塊的具體使用,我舉下面這個例子,連上講,說明顯示全部事件的辦法:
#-*- coding: utf-8 -*- import pygame from sys import exit pygame.init() #初始化pygame SCREEN_SIZE = (640, 480) #存儲屏幕尺寸 screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32) #建立窗口 my_font = pygame.font.SysFont('arial',16) #建立字體對象 font_height = my_font.get_linesize() #獲得字體的高度值 text = [] while True:#主循環 event = pygame.event.wait()#這裏用了wait()方法 text.append(str(event)) #得到事件的名稱 text = text[-SCREEN_SIZE[1]/font_height:] #這個切片操做保證了event_text裏面只保留一個屏幕的文字 if event.type == pygame.QUIT: pygame.quit() exit() screen.fill((255,255,255)) y = SCREEN_SIZE[1]-font_height #找一個合適的起筆位置,最下面開始可是要留一行的空 for line in reversed(text):#倒序寫滿整個屏幕的文字 screen.blit(my_font.render(line, True, (0,0,0)), (0, y)) #顯示字體 y -= font_height #把筆提一行 pygame.display.update()
這個程序的具體解釋應該看註釋就能夠理解。因此就不詳細說明了。其中pygame.event.wait()是一直等待到有事件的發生纔會執行,通常不經常使用這個方法。
寫程序的時候建議你們讀懂後給每一行加上本身的註釋,而後刪去個人源碼,從新打一遍,那樣會比較容易掌握pygame的使用。固然,這麼簡單的東西對於大多熟練的程序員都不須要那麼細緻的學習,大體看過去就能夠了。
Python的錯誤處理
程序老是會出錯的,pygame的運行也經常是這樣,那個時候沒辦法只能強制停止程序,而強制停止程序可以成功仍是系統的功勞。那麼咱們應該怎樣避免程序錯誤時徹底沒法反應呢?
Python提供了良好的錯誤處理機制,應該使用起來:
try: screen = pygame.display.set_mode(SCREEN_SIZE) except pygame.error, e: print "Can't create the display :-(" print e pygame.quit() exit()
這種方法很是有用,特別是開發實際的程序中。固然這僅僅是Python自帶的處理方式,可是這頗有用。
今天就講這麼多,以後我經過一步步製做一個簡單的小遊戲來講明pygame的具體使用。講的比較基礎,價值有限,對於初學者稍有一些意思。
我準備模仿微信的飛機大戰製做過程說明,很簡單的2D小遊戲。只是獻醜。
今天女友給我買的鍵盤剛到貨,青軸的脆響的確很舒服。讓我本身偷着樂一下子。