pygame简介
pygame可以实现python游戏的一个基础包。
pygame实现窗口
初始化pygame,init()类似于java类的初始化方法,用于pygame初始化。
pygame.init()
设置屏幕,(500,400)设置屏幕初始大小为500 * 400的大小, 0和32 是比较高级的用法。这样我们便设置了一个500*400的屏幕。
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)
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.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)
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.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))
 早安!
|