Skip to content

Files

Latest commit

a3c5fe4 · Nov 20, 2019

History

History
115 lines (78 loc) · 3.43 KB

107.md

File metadata and controls

115 lines (78 loc) · 3.43 KB

用 Pygame 开发游戏

原文: https://pythonspot.com/game-development-with-pygame/

Pygame Python

Pygame Python

欢迎来到该系列的第一篇教程:使用 Pygame 构建游戏。 使用 Pygame 创建的游戏可以在支持 Python 的任何计算机上运行,​​包括 Windows,Linux 和 Mac OS。

在本教程中,我们将解释使用 Pygame 构建游戏的基础。 我们将从基础开始,并教您如何创建基础框架。 在接下来的教程中,您将学习如何制作某些类型的游戏。

PyGame 简介

您将得到一个与右边的程序相似的程序:

游戏总是以与此类似的顺序(伪代码)开始:

initialize()
while running():
   game_logic() 
   get_input()
   update_screen()
deinitialize()

游戏从初始化开始。 已加载所有图形,已加载声音,已加载级别以及需要加载的任何数据。 游戏将继续运行,直到收到退出事件为止。 在此游戏循环中,我们更新游戏,获取输入并更新屏幕。 具体实现取决于游戏,但这种基本结构在所有游戏中都很常见。

在 Pygame 中,我们将其定义为:

import pygame
from pygame.locals import *

class App:

    windowWidth = 640
    windowHeight = 480
    x = 10
    y = 10

    def __init__(self):
        self._running = True
        self._display_surf = None
        self._image_surf = None

    def on_init(self):
        pygame.init()
        self._display_surf = pygame.display.set_mode((self.windowWidth,self.windowHeight), pygame.HWSURFACE)
        self._running = True
        self._image_surf = pygame.image.load("pygame.png").convert()

    def on_event(self, event):
        if event.type == QUIT:
            self._running = False

    def on_loop(self):
        pass

    def on_render(self):
        self._display_surf.blit(self._image_surf,(self.x,self.y))
        pygame.display.flip()

    def on_cleanup(self):
        pygame.quit()

    def on_execute(self):
        if self.on_init() == False:
            self._running = False

        while( self._running ):
            for event in pygame.event.get():
                self.on_event(event)
            self.on_loop()
            self.on_render()
        self.on_cleanup()

if __name__ == "__main__" :
    theApp = App()
    theApp.on_execute()

Pygame 程序以构造函数__init__()开始。完成后,将调用on_execute()。此方法运行游戏:更新事件,更新屏幕。最后,使用on_cleanup()对游戏进行初始化。

在初始化阶段,我们设置屏幕分辨率并启动 Pygame 库:

def on_init(self):
    pygame.init()
    self._display_surf = pygame.display.set_mode((self.windowWidth,self.windowHeight), pygame.HWSURFACE)

我们还加载图像。

self._image_surf = pygame.image.load("pygame.png").convert()

这不会将图像绘制到屏幕上,而是发生在on_render()中。

def on_render(self):
    self._display_surf.blit(self._image_surf,(self.x,self.y))
    pygame.display.flip()

blit方法将图像(image_surf)绘制到坐标(x, y)。 在 Pygame 中,坐标从(0, 0)左上角开始到(wind0wWidth, windowHeight)。 方法调用pygame.display.flip()更新屏幕。

继续下一个教程,并学习如何添加游戏逻辑和构建游戏 :-)