个性化阅读
专注于IT技术分析

Python Pygame(游戏开发库)介绍和用法详细图解

点击下载

本文概述

Python Pygame教程

Python是最流行的编程语言, 或者可以肯定地说它是下一代编程语言。在计算机科学的每个新兴领域, Python都积极参与其中。 Python在各种领域都有庞大的库, 例如机器学习(Numpy, Pandas, Matplotlib), 人工智能(Pytorch, TensorFlow)和游戏开发(Pygame, Pyglet)。

在本教程中, 我们将学习使用Pygame(Python库)进行游戏开发的知识。

Pygame

  • Pygame是一组跨平台的Python模块, 用于创建视频游戏。
  • 它由旨在与Python编程语言一起使用的计算机图形和声音库组成。
  • Pygame由Pete Shinners正式编写, 以取代PySDL。
  • Pygame适合于创建客户端应用程序, 这些应用程序可以包装在独立的可执行文件中。

Pygame的先决条件:

在学习pygame之前, 我们需要了解我们要开发哪种游戏。

  • 要学习pygame, 必须具有Python的基本知识。

Pygame安装

在Windows中安装pygame

在安装Pygame之前, 应先在系统中安装Python, 最好安装3.6.1或更高版本, 因为它对初学者更友好, 并且运行速度更快。主要有两种安装Pygame的方法, 如下所示:

1.通过pip安装:安装Pygame的好方法是使用pip工具(这是python用于安装软件包的工具)。命令如下:

py -m pip install -U pygame --user

2.通过IDE安装:第二种方法是通过IDE安装, 这里我们使用Pycharm IDE。在pycharm中安装pygame很简单。我们可以通过在终端中运行以上命令来安装它, 或使用以下步骤:

  • 打开文件选项卡, 然后单击设置选项。
Pygame安装
  • 选择项目解释器, 然后单击+图标。
Pygame安装
  • 它将显示搜索框。搜索pygame并单击安装包按钮。
Pygame安装

要检查pygame是否已正确安装, 请在IDLE解释器中键入以下命令, 然后按Enter:

import pygame

如果该命令成功运行且未引发任何错误, 则表明我们已经成功安装了Pygame, 并找到了用于pygame编程的正确IDLE版本。

Pygame安装

在Mac中安装pygame

按照以下步骤在Mac中安装pygame

  • 访问pygame pygame.org的官方网站, 它将显示以下窗口, 下载pygame-1.9.1release-python.org-32bit-py2.7-macosx10.3.dmg:
Pygame安装

注意:如果你使用的是其他版本的Python, 请下载最后一个链接。

  • 双击下载的文件并解压缩。现在, 双击显示为运行安装程序的解压缩的mpkg文件。按照说明安装pygame。
  • 启动终端(Cmd + Space, 然后在搜索框中输入” terminal”)。在终端中, 键入” python2.7″, 然后按Enter。
  • Python应该启动, 将版本显示为2.7.2(也可以使用2.7.1), 并提示你。在Python提示符下, 输入” import pygame”。如果你没有任何错误, 则一切正常。

简单的pygame示例

这是pygame的简单程序, 给出了语法的基本概念。

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 500))
done = False

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    pygame.display.flip()

输出

成功执行后, 它将显示以下窗口作为输出:

Pygame安装

让我们逐行了解上述程序的基本语法:

import pygame-可以访问pygame框架并导入pygame的所有功能。

pygame.init()-用于初始化pygame的所有必需模块。

pygame.display.set_mode((width, height))-用于显示所需大小的窗口。返回值是一个Surface对象, 这是我们将在其中执行图形操作的对象。

pygame.event.get()-用于清空事件队列。如果我们不这样做, 则窗口消息将开始堆积, 并且游戏将变得对操作系统无响应。

pygame.QUIT-当我们单击窗口角处的关闭按钮时, 它用于终止事件。

pygame.display.flip()-Pygame是双缓冲的, 因此会移动缓冲区。调用此功能对于使你在游戏屏幕上所做的任何更新都可见是很重要的。

pygame表面

pygame Surface用于显示任何图像。 Surface具有预定义的分辨率和像素格式。默认情况下, 表面颜色为黑色。通过传递size参数定义其大小。

表面可以具有许多额外的属性, 例如Alpha平面, 颜色键, 源矩形剪切等。否则, 他们将使用高度增强的软件发短信方法。

pygame时钟

在pygame中, 时间以毫秒(1/1000秒)表示。 Pygame时钟用于跟踪时间。时间对于创建动作, 播放声音或对任何事件做出反应至关重要。通常, 我们不会以秒为单位计算时间。我们以毫秒为单位。时钟还提供各种功能来帮助控制游戏的帧频。几个功能如下:

蜱()

此功能用于更新时钟。语法如下:

tick(framerate=0)

每帧应调用一次此方法。它将计算自上次调用以来经过了多少毫秒。 framerate参数是传递给函数的可选参数, 如果将其作为参数传递, 则该函数将延迟以使游戏的运行速度低于给定的每秒滴答声。

tick_busy_loop()

tick_busy_loop()与tick()相同。通过每帧调用一次Clock.tick_busy_loop(20), 该程序将永远不会以超过每秒20帧的速度运行。语法如下:

tick_busy_loop()

get_time()

get_time()用于获取上一个刻度。在Clock.tick()的最后两个调用之间传递的isdra的毫秒数。

get_time()

Pygame Blit

pygame blit是将游戏对象渲染到表面上的过程, 此过程称为blitting。创建游戏对象时, 需要渲染它。如果我们不渲染游戏对象并运行程序, 则它将提供黑色窗口作为输出。

盲打是任何游戏中最慢的操作之一, 因此, 我们需要注意不要在每一帧中都在屏幕上过分刺眼。 blitting中使用的主要功能是blit(), 它是:

闪光灯()

blit(source, dest, area=None, special_flags=0)

此功能用于将一个图像绘制到另一个图像中。可以使用dest参数放置平局。 dest参数可以是代表源左上角的一对坐标。

Pygame添加图片

要在窗口上添加图像, 首先, 我们需要通过调用带有宽度和高度元组的Surface构造函数来实例化空白表面。

surface = pygame.Surface((100, 100))

上一行使用默认的黑色创建100 * 100像素的空白24位RGB图像。

对于Surface的透明初始化, 请传递SRCALPHA参数。

surface = pygame.Surface((100, 100), pygame.SRCALPHA)

考虑以下示例以在表面上显示图像:

import pygame
pygame.init()
white = (255, 255, 255)
# assigning values to height and width variable 
height = 400
width = 400
# creating the display surface object 
# of specific dimension..e(X, Y). 
display_surface = pygame.display.set_mode((height, width))

# set the pygame window name 
pygame.display.set_caption('Image')

# creating a surface object, image is drawn on it. 
image = pygame.image.load(r'C:\Users\DEVANSH SHARMA\Desktop\download.png')

# infinite loop 
while True:
    display_surface.fill(white)
    display_surface.blit(image, (0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            # quit the program. 
            quit()
        # Draws the surface object to the screen. 
        pygame.display.update()

输出

Pygame添加图片

pygame直肠

Rect用于在Pygame中绘制矩形。 Pygame使用Rect对象存储和操纵矩形区域。 Rect可以由left, top, width和height值的组合形成。也可以从已经是Rect或具有名为” rect”的属性的Python对象创建它。

rect()函数用于更改矩形的位置或大小。它返回带有受影响的更改的Rect的新副本。在原始矩形中不会进行任何修改。

Rect对象具有各种虚拟属性, 可用于移动和对齐Rect:

x, y
top, left, right, bottom
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w, h

可以通过分配大小, 宽度或高度来更改矩形的尺寸。所有其他分配都将移动矩形而不调整其大小。

如果宽度或高度是Rect的非零值, 则对于非零测试将返回True。一些方法返回大小为0的Rect表示无效的矩形。

让我们使用Rect在pygame窗口上创建一个Rectangle:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    pygame.draw.rect(screen, (0, 125, 255), pygame.Rect(30, 30, 60, 60))  

    pygame.display.flip()

执行以上代码后, 它将在pygame窗口上显示矩形。

pygame直肠

Pygame Keydown

如果实际按下并释放一个键, Pygame的KEYDOWN和KEYUP会检测到该事件。 KEYDOWN检测到按键按下, 而KEYUP检测到按键释放。这两个事件(按键和按键释放)都具有以下两个属性:

  • key:key是一个整数ID, 代表关键字上的每个键。
  • mod:这是事件发生时处于按下状态的所有修改键的位掩码。

考虑以下按键和释放键的示例。

import pygame
pygame.init()
# sets the window title
pygame.display.set_caption(u'Keyboard events')
# sets the window size
pygame.display.set_mode((400, 400))

while True:
    # gets a single event from the event queue
    event = pygame.event.wait()
    # if the 'close' button of the window is pressed
    if event.type == pygame.QUIT:
        # stops the application
        break
    # Detects the 'KEYDOWN' and 'KEYUP' events
    if event.type in (pygame.KEYDOWN, pygame.KEYUP):
        # gets the key name
        key_name = pygame.key.name(event.key)
        # converts to uppercase the key name
        key_name = key_name.upper()
        # if any key is pressed
        if event.type == pygame.KEYDOWN:
            # prints on the console the key pressed
            print(u'"{}" key pressed'.format(key_name))
        # if any key is released
        elif event.type == pygame.KEYUP:
            # prints on the console the released key
            print(u'"{}" key released'.format(key_name))

输出

Pygame Keydown

让我们看另一个例子

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
is_blue = True
x = 30
y = 30

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            is_blue = not is_blue

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]: y -= 3
    if pressed[pygame.K_DOWN]: y += 3
    if pressed[pygame.K_LEFT]: x -= 3
    if pressed[pygame.K_RIGHT]: x += 3

    if is_blue:
        color = (0, 128, 255)
    else: 
        color = (255, 100, 0)
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))

    pygame.display.flip()

在上面的代码中, 该矩形将显示在pygame窗口中。

Pygame Keydown

当我们按下”向下”键时, 矩形将在向下调整形状。输出如下:

Pygame Keydown

pygame抽奖

Pygame提供了几何功能, 可以在表面绘制简单的形状。这些功能可用于以任何格式渲染到曲面。大多数函数接受width参数, 以表示形状边缘周围的厚度大小。如果宽度通过0, 则形状将为实心(填充)。

所有绘图函数均采用color参数, 该参数可以是以下格式之一:

  • pygame.Color对象
  • (RGB)三元组(元组/列表)
  • (RGBA)四联体(元组/列表)
  • 映射到曲面像素格式的整数值

画一个矩形

以下功能用于在给定的表面上绘制矩形。

pygame.draw.rect(surface, color, rect)
pygame.draw.rect(surface, color, rect, width=0)

参数:

  • surface-要绘制的屏幕。
  • color-此参数用于给定形状着色。如果我们使用元组, 则alpha值是可选的。
  • rect(Rect)-绘制矩形, 位置和尺寸。
  • width(int)-这是可选的, 以使用线宽或指示矩形已填充。
if width == 0, (default) fill the rectangle
if width > 0, used for line thickness
if width < 0, nothing will be drawn

画一个多边形

以下功能用于在给定的表面上绘制多边形。

  • pygame.draw.polygon(表面, 颜色, 点)
  • pygame.draw.polygon(表面, 颜色, 点, 宽度= 0)

参数:

  • surface-要绘制的屏幕。
  • color-此参数用于给定形状着色。如果我们使用元组, 则alpha值是可选的。
  • points(tuple(coordinate)or list(coordinate)):组成多边形顶点的3个或更多(x, y)坐标的序列。序列中的每个坐标必须是元组/列表。

注意:-如果len(points)<3或points不是序列或points不包含数字对, 则将引发值错误

画一个椭圆

以下功能用于在给定的曲面上绘制椭圆。

pygame.draw.ellipse(surface, color, rect)
pygame.draw.ellipse(surface, color, rect, width=0)

参数:

  • surface-要绘制的屏幕。
  • color-此参数用于给定形状着色。如果我们使用元组, 则alpha值是可选的。
  • rect(Rect)-绘制矩形, 位置和尺寸。

画一条直线

此方法用于在给定的表面上绘制一条直线。没有封顶。

pygame.draw.line(surface, color, start_pos, end_pos, width)
pygame.draw.line(surface, color, start_pos, end_pos, width=1)

参数:

  • surface-要绘制的屏幕。
  • color-此参数用于给定形状着色。如果我们使用元组, 则alpha值是可选的。
  • start_pos-线的起始位置(x, y)
  • end_pos-行的结束位置

画一个圆

以下是用于在给定表面上绘制圆的函数。

  • 圆(表面, 颜色, 中心, 半径)
  • 圆(表面, 颜色, 中心, 半径, 宽度= 0)

参数:

  • surface-要绘制的屏幕。
  • color-此参数用于给定形状着色。如果我们使用元组, 则alpha值是可选的。
  • center-圆的中心点, 以两个int / float的序列表示, 例如[x, y)
  • radius(int或float)-圆的半径, 从中心参数开始测量, 如果半径为零, 则将仅绘制中心像素。

画一个椭圆弧

以下功能用于在给定的表面上绘制椭圆弧。

?  arc(surface, color, rect, start_angle, stop_angle) 
?  arc(surface, color, rect, start_angle, stop_angle, width=1)

参数:

  • surface-要绘制的屏幕。
  • color-此参数用于给定形状着色。如果我们使用元组, 则alpha值是可选的。
  • rect(Rect)-绘制矩形, 位置和尺寸。
  • start_angle-弧的起始角度(弧度)。
  • stop_angle-弧的停止角(以弧度为单位)。

start_angle和stop_angle参数具有三个条件:

  1. 如果start_angle <stop_angle, 则将从start_angle到end_angle沿逆时针方向绘制弧。
  2. 如果start_angle> stop_angle, 则tau(tau = 2 * pi)将添加到停止角。
  3. 如果start_angle == stop_angle, 则不会绘制任何内容。

让我们考虑一个例子:

import pygame
from math import pi
pygame.init()
# size variable is using for set screen size
size = [400, 300]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Example program to draw geometry")
# done variable is using as flag 
done = False
clock = pygame.time.Clock()
while not done:
    # clock.tick() limits the while loop to a max of 10 times per second.
        clock.tick(10)

    for event in pygame.event.get():  # User did something
        if event.type == pygame.QUIT:  # If user clicked on close symbol 
            done = True  # done variable that we are complete, so we exit this loop

    # All drawing code occurs after the for loop and but
    # inside the main while done==False loop.

    # Clear the default screen background and set the white screen background
    screen.fill((0, 0, 0))

    # Draw on the screen a green line which is 5 pixels wide.
    pygame.draw.line(screen, (0, 255, 0), [0, 0], [50, 30], 5)
    # Draw on the screen a green line which is 5 pixels wide.
    pygame.draw.lines(screen, (0, 0, 0), False, [[0, 80], [50, 90], [200, 80], [220, 30]], 5)

    # Draw a rectangle outline
    pygame.draw.rect(screen, (0, 0, 0), [75, 10, 50, 20], 2)

    # Draw a solid rectangle
    pygame.draw.rect(screen, (0, 0, 0), [150, 10, 50, 20])

    # This draw an ellipse outline, using a rectangle as the outside boundaries
    pygame.draw.ellipse(screen, (255, 0, 0), [225, 10, 50, 20], 2)

    # This draw a solid ellipse, using a rectangle as the outside boundaries
    pygame.draw.ellipse(screen, (255, 0, 0), [300, 10, 50, 20])

    # Draw a triangle using the polygon function
    pygame.draw.polygon(screen, (0, 0, 0), [[100, 100], [0, 200], [200, 200]], 5)

    # This draw a circle
    pygame.draw.circle(screen, (0, 0, 255), [60, 250], 40)

    # This draw an arc
    pygame.draw.arc(screen, (0, 0, 0), [210, 75, 150, 125], 0, pi / 2, 2)

    # This function must write after all the other drawing commands.
    pygame.display.flip()

# Quite the execution when clicking on close
pygame.quit()

输出

pygame抽奖

Pygame文字和字体

Pygame还提供了呈现字体和文本的功能。我们可以使用pygame.font.SysFont()函数从系统加载字体。 Pygame带有内置的默认字体, 可以通过传递字体名称或”无”来访问。有许多功能可以帮助使用字体。

字体对象是使用pygame.font.Font()创建的。实际的字体对象完成了大部分字体工作。字体对象通常用于将文本呈现为新的Surface对象。几个重要的字体功能如下:

render()

此功能用于在新的Surface上绘制文本。 Pygame无法在现有Surface上绘制文本。这将创建一个具有指定文本渲染的新Surface。语法如下:

render(text, antialias, color, background=None)

尺寸()

此功能用于确定渲染文本所需的空间或位置数量。它也可以用于自动换行和其他布局效果。语法如下:

size(bool)

set_bold()

此功能用于粗体显示文本。语法如下:

set_bold(bool)

让我们考虑以下示例:

import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
done = False

#load the fonts
font = pygame.font.SysFont("Times new Roman", 72)
# Render the text in new surface
text = font.render("Hello, Pygame", True, (158, 16, 16))
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            done = True
    screen.fill((255, 255, 255))
    #We will discuss blit() in the next topic
    screen.blit(text, (320 - text.get_width() // 2, 240 - text.get_height() // 2))

    pygame.display.flip()

输出

Pygame文字和字体

注意:必须记住, 特定字体必须安装在用户计算机上。如果你不知道是否安装了字体, pygame具有以下功能可以枚举机器上所有可用的字体:

all_font = pygame.font.get_fonts()

还有另一个函数可以实例化默认系统字体:

font = pygame.font.Font(None, size)

使用上述任何功能, 我们都可以使用游戏中吸引人的字体。

Pygame精灵和碰撞检测

pygame精灵是属于大型图形场景的二维图像。通常, 子画面将是场景中的某些对象。

使用Sprite的最大优势之一是可以分组使用Sprite。如果它们位于组中, 我们可以使用一个命令轻松移动和绘制所有精灵。

Sprite模块包含要在游戏中使用的各种简单类。使用pygame时可以选择使用Sprite类和不同的组类。

Pygame提供了有助于碰撞检测的精灵和精灵组。碰撞检测是屏幕上的两个对象相互碰撞时的过程。例如, 如果玩家被敌人的子弹击中, 则可能会丧生, 或者程序需要知道玩家何时触摸硬币, 以便他们自动捡起。

让我们考虑以下示例:

import pygame
import sys
#Sprite class 
class Sprite(pygame.sprite.Sprite):
    def __init__(self, pos):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([20, 20])
        self.image.fill((255, 0, 255))
        self.rect = self.image.get_rect()
        self.rect.center = pos
def main():
    pygame.init()
    clock = pygame.time.Clock()
    fps = 50
    bg = [0, 0, 0]
    size =[300, 300]
    screen = pygame.display.set_mode(size)
    player = Sprite([40, 50])
    # Define keys for player movement
    player.move = [pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN]
    player.vx = 5
    player.vy = 5

    wall = Sprite([100, 60])

    wall_group = pygame.sprite.Group()
    wall_group.add(wall)

    player_group = pygame.sprite.Group()
    player_group.add(player)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False
        key = pygame.key.get_pressed()
        for i in range(2):
            if key[player.move[i]]:
                player.rect.x += player.vx * [-1, 1][i]

        for i in range(2):
            if key[player.move[2:4][i]]:
                player.rect.y += player.vy * [-1, 1][i]
        screen.fill(bg)
        # first parameter takes a single sprite
        # second parameter takes sprite groups
        # third parameter is a kill command if true
        hit = pygame.sprite.spritecollide(player, wall_group, True)
        if hit:
        # if collision is detected call a function to destroy
            # rect
            player.image.fill((255, 255, 255))
        player_group.draw(screen)
        wall_group.draw(screen)
        pygame.display.update()
        clock.tick(fps)
    pygame.quit()
    sys.exit
if __name__ == '__main__':

输出

Pygame精灵和碰撞检测

按下箭头键后, 一个矩形将与另一个矩形碰撞, 然后输出为:

Pygame精灵和碰撞检测

Pyglet

Python提供了另一个名为pyglet的游戏库, 该库是适用于Python的跨平台窗口和多媒体库。它用于开发游戏和其他视觉效果丰富的应用程序。它支持用户界面事件处理, 开窗, OpenGL图形, 加载图像和视频以及播放声音和音乐。

pyglet的几个功能如下:

  • 没有外部安装要求或依赖性。
  • 充分利用多个窗口和多个显示器。
  • 它可以加载任何格式的图像, 声音, 音乐和视频。
  • Pyglet是根据BSD开源许可证提供的。
  • 它同时支持Python 2和3。

pyglet的安装很简单;可以通过键入以下命令来安装它。

pip install pyglet

考虑以下示例。

import pyglet
window = pyglet.window.Window()
lable = pyglet.text.Label('Hello world', font_name='Times New Roman', font_size=36, x= window.width//2, y=window.height//2, anchor_x='center', anchor_y='center')
@window.event
def on_draw():
    window.clear()
    lable.draw()
pyglet.app.run()

输出

Pyglet

Pygame和Pyglet之间的比较

Pyglet Pygame
3d支持由于pyglet与OpenGL牢固地融合在一起。它支持3D绘图。 简单的Python语法Pygame使用Python作为其脚本语言。 Python被广泛视为即使是初学者也要掌握的最自然的语言之一。
跨平台它可以与Window, Linux和OS X一起使用。 用法API该API非常简单。
用纯Python编写的可以使用其他Python解释器进行编译。 最佳画布系统Pygame提供了一个绘图系统, 允许用户创建和绘制无限数量的画布。
人气较低Pyglet的人气较低, 因为它的社区支持较少。 Pygame比Pyglet更受欢迎。

在本教程中, 我们通过将开源模块pygame安装到Python 3编程环境中, 讨论了简单的游戏开发编程方法。


赞(13)
未经允许不得转载:srcmini » Python Pygame(游戏开发库)介绍和用法详细图解

评论 抢沙发

评论前必须登录!