在pygame游戲開發(fā)中,一個(gè)友好的UI中,漂亮的字體是少不了的
今天就給大伙帶來有關(guān)pygame中字體的一些介紹說明
首先我們得判斷一下我們的pygame中有沒有font這個(gè)模塊
代碼如下:
我們可以這樣使用pygame中的字體:
代碼如下:
參數(shù)二:字體大小
比較一下上面兩個(gè)方法,一個(gè)是自定義的字體,一個(gè)是系統(tǒng)自帶的字體,相對(duì)而言
自定義的字體要好一點(diǎn),因?yàn)樵趐ygame打包的過程中,可以把自定義的字體打包進(jìn)去
這樣就可以進(jìn)行很好的移植;而系統(tǒng)自帶的字體, 畢竟不是每個(gè)系統(tǒng)都有相應(yīng)的字體,
所以他的移植性不是很好,依賴性很大。
如果定義好了字體,那么我們應(yīng)該把字體顯示到suiface上面去,我們應(yīng)該這樣操作:
代碼如下:
參數(shù)二:是否開啟抗鋸齒,就是說True的話字體會(huì)比較平滑,不過相應(yīng)的速度有一點(diǎn)點(diǎn)影響
參數(shù)三:字體顏色
參數(shù)四:字體背景顏色(可選)即可以這樣:
代碼如下:
在demo中,玩家可以使用鍵盤上的:上,下,左,右四個(gè)方向鍵進(jìn)行控制青蛙的移動(dòng),
在移動(dòng)的過程中,左下角會(huì)動(dòng)態(tài)記錄青蛙的位置情況。
代碼部分如下:
#python font import os, pygame from 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, 0 frog_move_x, frog_move_y = 0, 0 while 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()
完整實(shí)例代碼代碼點(diǎn)擊此處本站下載。
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com