一.绘制Hello Pygame
1.安装Pygame库,Pygame并不是和Python打包到一起,你需要独立安装它,安装命令如下:
pip install pygame
2.我们开始编写第一个Hello Pygame程序:
import pygamefrom pygame.locals import *
3.定义我们绘制Hello Pygame时使用的字体:
myfont = pygame.font.Font(None,60)
4.定义颜色变量:
blue = 0,0,255white = 255,255,255textImage = myfont.render("Hello Pygame",True,white) #我们要绘制的文字
5.要绘制文本,我们要清屏,进行绘制,然后再刷新显示:
screen.fill(blue)screen.blit(textImage,(100,100))pygame.display.update()
6.如果你现在运行程序,程序会立马闪退,所以我们需要设置一个延迟:
while True: for event in pygame.event.get(): if event.type in (QUIT,KEYDOWN): sys.exit()
7.下面,我们来展示一下完整代码:
import pygameimport sysfrom pygame.locals import *white = 255,255,255blue = 0,0,200pygame.init()screen = pygame.display.set_mode((600,500))myfont = pygame.font.Font(None,60)textImage = myfont.render("Hello Pygame",True,white)while True: for event in pygame.event.get(): if event.type in (QUIT,KEYDOWN): sys.exit() screen.fill(blue) screen.blit(textImage,(150,100)) pygame.display.update()