7

我希望这个问题本质上不是荒谬的。

我正在开发一个游戏。我已经从图形组件中分离出底层游戏引擎(在 Python 中)。我有一个脚本可以模糊一些参数,使用游戏引擎模拟游戏的一部分,然后使用 Pygame 将其可视化。

我想自动化以下过程:

  1. 作为 cronjob 运行模拟
  2. 使用 Pygame 可视化它(无头)
  3. 将可视化另存为短(约 10 秒)视频文件
  4. 以编程方式将视频上传到 Youtube

理想情况下,我希望每天执行几次,以便团队中的非技术成员可以观看视频并就游戏的视觉方面提供反馈。

我想使用 Pygame,因为我已经准备好代码了。但我怀疑我可能应该使用 PIL 之类的东西来创建一系列图像文件并从那里开始。

Pygame可以做到这一点吗?我应该只使用 PIL 吗?完成这样的事情还有其他想法吗?

4

2 回答 2

3

假设您在 linux 上运行,并且您的图形引擎在 X 中工作,您可以使用 Xvfb(X 虚拟帧缓冲区)无头运行任何您想要的应用程序。您可以运行虚拟(无头)帧缓冲会话的视频编码器。有几个实用程序可以使这项任务更容易:

您想要制作一个顶级脚本,它将:

  • 启动 Xvfb
  • 启动视频编码器(即 ffmpeg)
  • 在 Xvfb 中运行您的游戏。您不需要以任何方式修改您的游戏,假设它可以在没有用户输入的情况下运行,只需将 DISPLAY 环境变量设置为正确的值。
  • 结束视频编码
  • 将视频上传到 youtube

Xvfb 和 ffmpeg 绝对是无头录制游戏的方式,这确保您可以按原样录制游戏而无需修改。它应该是可行的,但不一定容易。上述脚本应该可以帮助您入门。

于 2013-01-22T03:43:01.367 回答
3

Anton 的回答激发了我对这个问题的深入挖掘。令人高兴的是,我发现可以无头运行 Pygame,使我能够比 Anton 的方法更简单地完成我想做的事情。

基本工作流程如下:

  1. 设置 pygame 以无头运行
  2. 运行我的游戏,使用Pygame为每一帧保存一个屏幕图像
  3. 使用ffmpeg从图像文件创建视频
  4. 使用youtube-upload 将视频上传到 Youtube

示例代码(我自己的代码的简化版本,因此尚未经过严格测试):

# imports
import os
import subprocess
import pygame
import mygame

# setup pygame to run headlessly
os.environ['SDL_VIDEODRIVER'] = 'dummy'
pygame.display.set_mode((1,1))

# can't use display surface to capture images for some reason, so I set up
# my own screen using a pygame rect
width, height = 400, 400
black = (0,0,0)
flags = pygame.SRCALPHA
depth = 32
screen = pygame.Surface((width, height), flags, depth)
pygame.draw.rect(screen, black, (0, 0, width, height), 0)

# my game object: screen becomes attribute of game object: game.screen
game = mygame.MyGame(screen)

# need this file format for saving images and encoding video with ffmpeg
image_file_f = 'frame_%03d.png'

# run game, saving images of each screen
game.init()
while game.is_running:
    game.update()   # updates screen
    image_path = image_file_f % (game.frame_num)
    pygame.image.save(game.screen, image_path)

# create video of images using ffmpeg
output_path = '/tmp/mygame_clip_for_youtube.mp4'

ffmpeg_command = (
    'ffmpeg',
    '-r', str(game.fps),
    '-sameq',
    '-y',
    '-i', image_file_f,
    output_path
)

subprocess.check_call(ffmpeg_command)
print "video file created:", output_path

# upload video to Youtube using youtube-upload
gmail_address='your.name@gmail.com'
gmail_password='test123'

upload_command = (
    'youtube-upload',
    '--unlisted',
    '--email=%s' % (gmail_address),
    '--password=%s' % (gmail_password),
    '--title="Sample Game Clip"',
    '--description="See https://stackoverflow.com/q/14450581/1093087"',
    '--category=Games',
    output_path
)

proc = subprocess.Popen(
    upload_command,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE
)
out, err = proc.communicate()

print "youtube link: %s" % (out)

创建视频后,您可能希望删除所有图像文件。

我确实在无头捕获屏幕截图时遇到了一点麻烦,我按照这里的描述解决了这个问题:在 Pygame 中,如何以无头模式保存屏幕图像?

我能够安排我的脚本作为 cronjob 运行而没有问题。

于 2013-01-25T05:03:09.247 回答