pygame簡介 pygame可以實作python游戲的一個基礎包, pygame實作視窗 初始化pygame,init()類似于java類的初始化方法,用于pygame初始化,
設定螢屏,(500,400)設定螢屏初始大小為500 * 400的大小, 0和32 是比較高級的用法,這樣我們便設定了一個500*400的螢屏,pygame.init()
surface = pygame.display.set_mode((500, 400), 0, 32)如果不設定pygame事件的話,視窗會一閃而逝,這里去捕捉pygame的事件,如果沒有按退出,那么視窗就會一直保持著,這樣方便我們去設定不同的內容展示,
pygame.display.set_caption(“我的pygame游戲”)pygame.display,set_caption設定視窗的標題
import pygame, sys from pygame.locals import * pygame.init() surface = pygame.display.set_mode((500, 400), 0, 32) pygame.display.set_caption("我的pygame游戲") while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit()設定螢屏背景色 這里設定背景顏色為 (255, 255,255) ,然后更新螢屏
# 設定背景顏色 surface.fill((255, 255, 255)) # 更新螢屏 pygame.display.update()

添加文字 首先獲取Font物件,渲染Font物件,然后設定文本位置即可,pygame.font.SysFont(None, 40) 獲取到文字物件,然后渲染文字為surface物件,basicFont.render 方法第一個引數是文字,第二個是是否去除鋸齒,第三個和第四個是文字的顏色和文字的背景顏色,然后一個螢屏的區域,使用 blit將文字渲染到螢屏上,注意這里渲染的必須在螢屏的填充顏色之后,不然會覆寫文字,
# 獲取字體物件 basicFont = pygame.font.SysFont(None, 40) # surface物件 text = basicFont.render('秀兒', True, (255,255,255), (0,255,0)) # 設定文本位置 textRect = text.get_rect() textRect.centerx = surface.get_rect().centerx textRect.centery = surface.get_rect().centery # 將渲染的surface物件更新到螢屏上 surface.blit(text,textRect)

如上圖所示,中文顯示亂碼,這里我們獲取系統的字體,并將其中一種中文字體設定為默認字體即可,
# 獲取當前系統字體 fonts = pygame.font.get_fonts() print(fonts)完整代碼
import pygame,sys from pygame.locals import * pygame.init() surface = pygame.display.set_mode((500, 400), 0, 32) pygame.display.set_caption("我的pygame游戲") surface.fill((255, 255, 255)) # 獲取字體物件 basicFont = pygame.font.SysFont("方正粗黑宋簡體", 48) # surface物件 text = basicFont.render('秀兒', True, (255,255,255), (0,255,0)) # 設定文本位置 textRect = text.get_rect() textRect.centerx = surface.get_rect().centerx textRect.centery = surface.get_rect().centery # 將渲染的surface物件更新到螢屏上 surface.blit(text,textRect) pygame.display.update() while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit()繪制多邊形 polygon 來繪制多邊形,第一個引數是螢屏物件,第二個是顏色,第三個是用點串連的一個元組,最后一個點有和第一個是一致的
import pygame,sys from pygame.locals import * pygame.init() surface = pygame.display.set_mode((500, 400), 0, 32) pygame.display.set_caption("我的pygame游戲") surface.fill((255, 255, 255)) pygame.draw.polygon(surface, (0, 0, 255), ((50, 40), (100, 100), (120, 80), (50, 40))) pygame.display.update() while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit()
繪制直線 line方法,第一個引數是螢屏物件,之后是顏色和兩個點,最后一個引數是線條寬度
pygame.draw.line(surface, (0, 0, 255), (50, 40), (100, 100), 10)
繪制圓形 circle用來繪制圓形,第一個引數和第二個引數是螢屏物件和顏色,之后是圓心和半徑,最后一個表示寬度,如果設定為0,則是一個實園,
pygame.draw.circle(surface, (0, 0, 255), (50, 40), 20, 10)

繪制橢圓 第一個引數和第二個引數同上,第三個引數分別指定x和y軸的左上角,之后是x和y的半徑,最后一個是寬度
pygame.draw.ellipse(surface, (0, 0, 255), (50, 40, 20, 10), 2)

繪制矩形
rect來繪制矩形,第一個和第二個引數同上,第三個引數分別制定左上角和右下角pygame.draw.rect(surface, (0, 0, 255), (50, 40, 20, 10))

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/518842.html
標籤:其他
上一篇:golang中的map
