使用 Pygame 创建第一个程序实例

  • Post category:Python

以下是 Pygame 的第一个 Hello World 程序示例:

import pygame

pygame.init()

# 设置游戏窗口
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption("Hello, Pygame!")

# 主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    # 绘制文字
    font = pygame.font.Font(None, 36)
    text = font.render("Hello World!", True, (255, 0, 0))
    screen.blit(text, (150, 100))

    # 刷新显示
    pygame.display.update()

该程序的作用是在游戏窗口中显示一串文字“Hello World!”,并且可通过点击关闭窗口来退出程序。下面详细解释该程序。

导入模块

import pygame

pygame.init()

这里通过 import 导入 Pygame 模块,并通过 pygame.init() 来初始化 Pygame。

设置游戏窗口

screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption("Hello, Pygame!")

这里通过 pygame.display.set_mode() 来设置游戏窗口,并且将窗口标题设置为“Hello, Pygame!”。

主循环

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    # 绘制文字
    font = pygame.font.Font(None, 36)
    text = font.render("Hello World!", True, (255, 0, 0))
    screen.blit(text, (150, 100))

    # 刷新显示
    pygame.display.update()

这里使用了一个常用的主循环结构,用于在游戏运行时不断执行一定的操作。在循环中使用了 pygame.event.get() 来获取用户输入事件,并判断是否为关闭窗口事件,如果是,则通过 pygame.quit() 关闭 Pygame,并通过 exit() 退出程序。

在循环中使用了 pygame.font.Font() 创建了一个字体对象 font,并使用该字体对象调用 render() 方法,将文字“Hello World!”渲染为一个 Surface 对象 textTrue 参数表示文字是否需要抗锯齿处理,(255, 0, 0) 表示文字的颜色。然后再调用 screen.blit() 方法将渲染好的文字绘制到游戏窗口上。

最后通过 pygame.display.update() 刷新游戏窗口,将所有变化显示出来。

这便是 Pygame 的第一个 Hello World 程序示例的详细讲解。