pygame学习教程(二)初步了解pygame

前一篇
使用pygame的第一步是将pygame库导入到python程序中,以便来使用它
import pygame
然后需要引入pygame中的所有常量。
from pygame.locals import *
再经过初始化以后我们就可以尽情地使用pygame了。
初始化pygame: pygame.init()
通常来说我们需要先创建一个窗口,方便我们与程序的交互。下面创建了一个600 x 500的窗口
screen = pygame.display.set_mode((600,500))
pygame支持使用pygame.font将文打印到窗口。要打印文本的话首先需要创建一个文字对象
myfont = pygame.font.Font(None,60)
这个文本绘制进程是一个重量级的进程,比较耗费时间,常用的做法是先在内存中创建文本图像,然后将文本当作一个图像来渲染。
white = 255,255,255 blue = 0,0,200 textImage = myfont.render(“Hello Pygame”, True, white)
textImage 对象可以使用screen.blit()来绘制。上面代码中的render函数第一个参数是文本,第二个参数是抗锯齿字体,第三个参数是一个颜色值(RGB值)。
要绘制本文,通常的过程是清屏,绘制,然后刷新。
screen.fill(blue) screen.blit(textImage, (100,100)) pygame.display.update()
如果此时运行程序的话,会出现一个窗口一闪而过。为了让它长时间的显示,我们需要将它放在一个循环中。
这两个例子可以理解一下显示文字和键盘事件

# coding: utf8
import pygame
from pygame.locals import *
from sys import exit

pygame.init()
SCREEN_SIZE = (640, 480)
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)

font = pygame.font.SysFont("arial", 16);
font_height = font.get_linesize()
event_text = []

while True:

    event = pygame.event.wait()
    event_text.append(str(event))
    # 获得时间的名称
    event_text = event_text[-SCREEN_SIZE[1] // font_height:]
    # 这个切片操作保证了event_text里面只保留一个屏幕的文字

    if event.type == QUIT:
        exit()

    screen.fill((0,0,0))

    y = SCREEN_SIZE[1] - font_height
    # 找一个合适的起笔位置,最下面开始但是要留一行的空
    for text in reversed(event_text):
        screen.blit(font.render(text, True, (0, 255, 0)), (0, y))
        # 以后会讲
        y -= font_height
        # 把笔提一行

    pygame.display.update()

运行后动动鼠标。

在这里插入图片描述
这个做背景图片

# coding: utf8
background_image_filename = 'sushiplate.jpg'

import pygame
from pygame.locals import *
from sys import exit

pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
background = pygame.image.load(background_image_filename).convert()

x, y = 0, 0
move_x, move_y = 0, 0

while True:
    for event in pygame.event.get():
        print(event)
        print("type",event.type)
        if event.type == QUIT:
            exit()
        if event.type == KEYDOWN:
            # 键盘有按下?
            if event.key == K_LEFT:
                # 按下的是左方向键的话,把x坐标减一
                move_x = -1
            elif event.key == K_RIGHT:
                # 右方向键则加一
                move_x = 1
            elif event.key == K_UP:
                # 类似了
                move_y = -1
            elif event.key == K_DOWN:
                move_y = 1

        elif event.type == KEYUP:
            # 如果用户放开了键盘,图就不要动了
            move_x = 0
            move_y = 0

    # 计算出新的坐标
    x += move_x
    y += move_y

    screen.fill((0, 0, 0))
    screen.blit(background, (x, y))
    # 在新的位置上画图
    pygame.display.update()

后一篇

猜你喜欢

转载自blog.csdn.net/weixin_39462002/article/details/84970210