2015/11/3用Python写游戏,pygame入门(3):字体模块、事件显示和错误处理

时间:2023-12-27 15:09:49

游戏里面一般是肯定会出现文字显示的,即使是俄罗斯方块也应该显示分数。那么我们应该怎样来显示文字呢,今天一起学习一下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', '*nbaiti', '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 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小游戏。只是献丑。

今天女朋友给我买的键盘刚到货,青轴的脆响的确很舒服。让我自己偷着乐一会儿。