Python pygame 将绘图转换为图像 [英] Python pygame converting drawing to an image

查看:100
本文介绍了Python pygame 将绘图转换为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个使用网格的游戏.但是我必须每帧计算那个网格.我可以保存网格吗?所以我只需要 blit 屏幕上的网格?

I am trying to make a game that is using a grid. But I have to calculate that grid every frame. Can I save the grid? So I just have to blit the grid on the screen?

这是我的代码:

import pygame
pygame.init()
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('grid')
running = True
def drawgrid():
    for x in range(0, width, 40):
        pygame.draw.rect(screen, (0, 0, 0), (x, 0, 2, height))
    for y in range(0, height, 40):
        pygame.draw.rect(screen, (0, 0, 0), (0, y, width, 2))
while running:
    screen.fill((255,255,120))
    drawgrid()
    pygame.display.flip()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running == False
            pygame.quit()

推荐答案

创建一个与显示大小和背景颜色相同的表面:

Create a surface with the same size as the display and the background color:

grid_surf = pygame.Surface((width, height))
grid_surf.fill((255,255,120))

在这个表面上绘制网格:

Draw the grid to this surface:

def drawgrid(surf):
    for x in range(0, width, 40):
        pygame.draw.rect(surf, (0, 0, 0), (x, 0, 2, height))
    for y in range(0, height, 40):
        pygame.draw.rect(surf, (0, 0, 0), (0, y, width, 2))

drawgrid(grid_surf)

并在主应用程序循环中对表面进行 blit,而不是绘制网格和背景:

And blit the surface in the main application loop instead of drawing the grid and background:

screen.blit(grid_surf, (0, 0))

示例代码:

import pygame
pygame.init()

width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('grid')

def drawgrid(surf):
    for x in range(0, width, 40):
        pygame.draw.rect(surf, (0, 0, 0), (x, 0, 2, height))
    for y in range(0, height, 40):
        pygame.draw.rect(surf, (0, 0, 0), (0, y, width, 2))

grid_surf = pygame.Surface((width, height))
grid_surf.fill((255,255,120))
drawgrid(grid_surf)

running = True
while running:

    screen.blit(grid_surf, (0, 0))
    pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running == False
            pygame.quit()

这篇关于Python pygame 将绘图转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆