本文實例講述了Python基于pygame實現的font游戲字體。分享給大家供大家參考,具體如下:
在pygame游戲開發中,一個友好的UI中,漂亮的字體是少不了的
今天就給大伙帶來有關pygame中字體的一些介紹說明
首先我們得判斷一下我們的pygame中有沒有font這個模塊
我們可以這樣使用pygame中的字體:
參數二:字體大小
比較一下上面兩個方法,一個是自定義的字體,一個是系統自帶的字體,相對而言
自定義的字體要好一點,因為在pygame打包的過程中,可以把自定義的字體打包進去
這樣就可以進行很好的移植;而系統自帶的字體, 畢竟不是每個系統都有相應的字體,
所以他的移植性不是很好,依賴性很大。
如果定義好了字體,那么我們應該把字體顯示到suiface上面去,我們應該這樣操作:
參數二:是否開啟抗鋸齒,就是說True的話字體會比較平滑,不過相應的速度有一點點影響
參數三:字體顏色
參數四:字體背景顏色(可選)即可以這樣:
在demo中,玩家可以使用鍵盤上的:上,下,左,右四個方向鍵進行控制青蛙的移動,
在移動的過程中,左下角會動態記錄青蛙的位置情況。
代碼部分如下:
- #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()
完整實例代碼代碼點擊此處本站下載。
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答