2015/11/3 use Python to write a game. Getting started with pygame (3): font module, event display, and error handling, pythonpygame
In the game, text is usually displayed, and even the Russian square should show scores. So how should we display the text? Today, let's take a look at the font module of pygame.
Use font Module
Pygame can directly call the system font or TTF font. To use the Font, you should first create a Font object. For the built-in Font, you should call:
>>> font1 = pygame.font.SysFont('arial', 16)
The first parameter is the font size, and the second parameter is the font size. Under normal circumstances, there will be arial fonts in the system. If the default fonts are not used, the default fonts are related to various systems.
You can use pygame. font. get_fonts () to obtain all available fonts of the current system:
>>> 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']
Another method is to use your ttf font:
my_font = pygame.font.Font("my_font.ttf", 16)
The advantage of this method is that you can package and distribute the font files with the game to avoid the problem that the font cannot be displayed on the player's computer.
Once you have a Font object, you can use the render method to write, and then use the bder method blit to the screen;
>>> text = font1.render("Input your text here",True,(0,0,0),(255,255,255))
The first parameter of the render method is the written text content, the second is a Boolean value, indicating whether anti-aliasing is enabled, the third is the color of the font itself, and the fourth is the background color. If you do not want a background color, that is, to make the background transparent, you do not need to add the fourth parameter.
In addition, if you want to display Chinese Characters in Python2, you must use a Chinese font and then use the u prefix string, that is, Unicode encoding. At last, you must add the annotation text such as #-*-coding: UTF-8-* to the file header.
The specific use of the font module, I will give you the following example to illustrate how to display all events:
#-*-Coding: UTF-8-*-import pygamefrom sys import exitpygame. init () # initialize pygameSCREEN_SIZE = (640,480) # store screen size screen = pygame. display. set_mode (SCREEN_SIZE, 0, 32) # create window my_font = pygame. font. sysFont ('arial', 16) # create a font object font_height = my_font.get_linesize () # obtain the font height value text = [] while True: # Main Loop event = pygame. event. wait () # The wait () method text is used here. append (str (event) # obtain the event name text = text [-SCREEN_SIZE [1]/font_height:] # This slicing operation ensures that only one screen text if event is retained in event_text. type = pygame. QUIT: pygame. quit () exit () screen. fill (255,255,255) y = SCREEN_SIZE [1]-font_height # find a suitable starting position. At the bottom, leave a blank line for line in reversed (text ): # Write the entire screen text screen in reverse order. benders (my_font.render (line, True, (, 0), (0, y) # display font y-= font_height # put the pen in a line of pygame. display. update ()
The specific explanation of this program can be understood by reading the annotations. So it is not described in detail. Pygame. event. wait () is executed until an event occurs. This method is not commonly used.
When writing a program, it is recommended that you read it and add your own comments to each line, then delete my source code and repeat it again, which makes it easier to master the use of pygame. Of course, this simple thing does not require so detailed learning for most skilled programmers. You can simply look at it.
Python error handling
The program will always go wrong, and pygame often runs like this. At that time, there was no way to force the program to be aborted, and the system still took the credit for the program to succeed. So how should we avoid completely unresponsive errors?
Python provides a good error handling mechanism and should be used as follows:
try: screen = pygame.display.set_mode(SCREEN_SIZE)except pygame.error, e: print "Can't create the display :-(" print e pygame.quit() exit()
This method is very useful, especially in the development of actual programs. Of course, this is only the processing method provided by Python, but it is very useful.
Today I will talk so much about it. Then I will explain how to use pygame by making a simple game step by step. The lecture is more basic and has limited value. It is a little interesting for beginners.
I am going to simulate the aircraft war production process, a very simple 2D game. It's just ugly.
The keyboard my girlfriend bought me today has just arrived, and the cylinder is really comfortable. I am happy for a moment.