#pygame基础笔记
首先需要理解pygame的机制: 如下图所示(图片来自make game with python and pygame一书)
##看示例代码,学习基本知识
<pre><code> import sys, pygame pygame.init() size = width, height = 320, 240 speed = [2, 2] black = 0, 0, 0 screen = pygame.display.set_mode(size) ball = pygame.image.load("ball.bmp") ballrect = ball.get_rect() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() ballrect = ballrect.move(speed) if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] screen.fill(black) screen.blit(ball, ballrect) pygame.display.flip() </code></pre>
pygame.display.set_mode(size)
: 生成一个窗口ball = pygame.image.load("ball.bmp")
: 加载一个球。他是一个surface对象,和简单的图像对象有区别ballrect = ball.get_rect()
: 看后面的代码大概知道有什么用- 这个是保证可以退出程序,并且释放资源。关于事件这个,我想后面应该会有详细介绍。
<pre><code> while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() </code></pre>
ballrect = ballrect.move(speed)
: 移动球,注意这里 = 和不加 =的区别screen.blit(ball, ballrect)
: 在ballrect的位置,在屏幕上把ball的像素值复制到屏幕上