1. 程式人生 > >pygame學習教程(二)初步瞭解pygame

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()

後一篇