本文執行個體講述了Python基於pygame實現的font遊戲字型。分享給大家供大家參考,具體如下:
在pygame遊戲開發中,一個友好的UI中,漂亮的字型是少不了的
今天就給大夥帶來有關pygame中字型的一些介紹說明
首先我們得判斷一下我們的pygame中有沒有font這個模組
複製代碼 代碼如下:
if not pygame.font: print('Warning, fonts disabled')
如果有的話才可以進行接下來的操作:-)
我們可以這樣使用pygame中的字型:
複製代碼 代碼如下:
tork_font = pygame.font.Font('data\\font\\TORK____.ttf', 20)
當然也可以使用系統中內建的字型:
複製代碼 代碼如下:
my_font = pygame.font.SysFont("arial", 10)
參數一:字型名稱
參數二:字型大小
比較一下上面兩個方法,一個是自訂的字型,一個是系統內建的字型,相對而言
自訂的字型要好一點,因為在pygame打包的過程中,可以把自訂的字型打包進去
這樣就可以進行很好的移植;而系統內建的字型, 畢竟不是每個系統都有相應的字型,
所以他的移植性不是很好,依賴性很大。
如果定義好了字型,那麼我們應該把字型顯示到suiface上面去,我們應該這樣操作:
複製代碼 代碼如下:
position = tork_font.render('Hello,I\'m Hongten', True, (255, 255,255), (23, 43,234))
參數一:顯示的內容
參數二:是否開啟消除鋸齒,就是說True的話字型會比較平滑,不過相應的速度有一點點影響
參數三:字型顏色
參數四:字型背景顏色(可選)即可以這樣:
複製代碼 代碼如下:
position = tork_font.render('Hello,I\'m Hongten', True, (255, 255,255))
下面給出一個demo,說說pygame中字型的使用
在demo中,玩家可以使用鍵盤上的:上,下,左,右四個方向鍵進行控制青蛙的移動,
在移動的過程中,左下角會動態記錄青蛙的位置情況。
代碼部分如下:
#python fontimport os, pygamefrom pygame.locals import *from sys import exit__author__ = {'name' : 'Hongten', 'mail' : 'hongtenzone@foxmail.com', 'Version' : '1.0'}if not pygame.font: print('Warning, fonts disabled')pygame.init()SCREEN_DEFAULT_SIZE = (500, 500)BG_IMAGE_NAME = 'bg.gif'FROG_IMAGE_NAME = 'frog.gif'TORK_FONT_NAME = 'TORK____.ttf'bg_image_path = os.path.join('data\\image', BG_IMAGE_NAME)frog_image_path = os.path.join('data\\image', FROG_IMAGE_NAME)tork_font_path = os.path.join('data\\font', TORK_FONT_NAME)if not os.path.exists(bg_image_path): print('Can\'t found the background image:', bg_image_path)if not os.path.exists(frog_image_path): print('Can\'t fount the frog image:', frog_image_path)if not os.path.exists(tork_font_path): print('Can\'t fount the font:', tork_font_path)screen = pygame.display.set_mode(SCREEN_DEFAULT_SIZE, 0, 32)bg = pygame.image.load(bg_image_path).convert()frog = pygame.image.load(frog_image_path).convert_alpha()tork_font = pygame.font.Font(tork_font_path, 20)frog_x, frog_y = 0, 0frog_move_x, frog_move_y = 0, 0while 1: for event in pygame.event.get(): if event.type == QUIT: exit() elif event.type == KEYDOWN: if event.key == K_LEFT: frog_move_x = -1 elif event.key == K_UP: frog_move_y = -1 elif event.key == K_RIGHT: frog_move_x = 1 elif event.key == K_DOWN: frog_move_y = 1 elif event.type == KEYUP: frog_move_x = 0 frog_move_y = 0 frog_x += frog_move_x frog_y += frog_move_y #print(frog_x, frog_y) screen.blit(bg, (0, 0)) position_str = 'Position:' + str(frog_x) + ',' + str(frog_y) position = tork_font.render(position_str, True, (255, 255,255), (23, 43,234)) screen.blit(position, (0, 480)) screen.blit(frog, (frog_x, frog_y)) pygame.display.update()
完整執行個體代碼代碼點擊此處本站下載。
希望本文所述對大家Python程式設計有所協助。