国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

2015/11/3用Python寫游戲,pygame入門(3):字體模塊、事件顯示和錯誤處理

2019-11-14 16:56:12
字體:
來源:轉載
供稿:網友

游戲里面一般是肯定會出現文字顯示的,即使是俄羅斯方塊也應該顯示分數。那么我們應該怎樣來顯示文字呢,今天一起學習一下pygame的font模塊。


 

使用字體模塊

pygame可以直接調用系統字體,也可以調用TTF字體。為了使用字體,首先應該創建一個Font對象,對于系統自帶的字體,應該這樣調用:

>>> font1 = pygame.font.SysFont('arial', 16)

第一個參數是字體名,第二個參數是字號。正常情況下系統里都會有arial字體,如果沒有會使用默認字體,默認字體和各個系統有關。

可以使用pygame.font.get_fonts()來獲得當前系統所有可用字體:

>>> 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字體:

my_font = pygame.font.Font("my_font.ttf", 16)

這個方法的優勢是你可以把字體文件和游戲一起打包分發,避免玩家電腦上沒有這個字體無法顯示的問題。

一旦你有了Font對象,你就可以用render方法來寫字了,然后通過blit方法blit到屏幕上;

>>> text = font1.render("Input your text here",True,(0,0,0),(255,255,255))

render方法的第一個參數是寫入的文字內容;第二個是布爾值,說明是否開啟抗鋸齒;第三個是字體本身的顏色;第四個是背景的顏色。如果不想有背景色,也就是讓背景透明的話,可以不加第四個參數。

另外,如果是Python2,想顯示中文的話,要使用能用中文的字體,然后用u前綴字符串,也就是用Unicode編碼。最后還得在文件頭加上,# -*- coding: utf-8 -*-這樣的注釋文字。

字體模塊的具體使用,我舉下面這個例子,連上講,說明顯示所有事件的辦法:

#-*- coding: utf-8 -*-import pygamefrom sys import exitpygame.init() #初始化pygameSCREEN_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小游戲。只是獻丑。

 

今天女朋友給我買的鍵盤剛到貨,青軸的脆響的確很舒服。讓我自己偷著樂一會兒。

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 汤阴县| 吉隆县| 安福县| 嘉鱼县| 沧州市| 南江县| 武强县| 增城市| 黄石市| 彰化县| 卫辉市| 肇源县| 富顺县| 盐源县| 色达县| 忻城县| 壤塘县| 厦门市| 靖州| 来安县| 林州市| 灌阳县| 司法| 开化县| 卢氏县| 诸暨市| 樟树市| 乌拉特后旗| 竹山县| 常山县| 阿瓦提县| 凌云县| 三明市| 紫云| 二手房| 霍城县| 七台河市| 宜兰县| 尼勒克县| 成武县| 石城县|