【问题标题】:How can I integrate a Line Chart Viewer in PyGame?如何在 PyGame 中集成折线图查看器?
【发布时间】:2022-01-26 07:52:38
【问题描述】:

我在 Pygame 中有一个用于游戏的 AI,我想创建一个图表来跟踪演变。

我只需要 X 轴上的 Gen 和 Y 轴上的 Points。

我已经尝试过了,但我不知道如何让它适合游戏中的表面,而不是作为单独的窗口弹出(最终会停止游戏)

import matplotlib.pyplot as plt

plt.plot(Generation=[], Points=[])
    plt.title('Points per Generation')
    plt.xlabel('Generation')
    plt.ylabel('Points')
    plt.show()

有什么想法吗?

【问题讨论】:

    标签: python matplotlib pygame pygame-surface


    【解决方案1】:

    一种方法是将pyplot 渲染并存储到Buffered Steam。这个流可以用pygame.image.load加载到pygame.Surface对象中:

    plot_stream = io.BytesIO()
    plt.savefig(plot_stream, formatstr='png')
    plot_stream.seek(0)
    
    plot_surface = pygame.image.load(plot_stream, 'PNG')
    

    小例子:

    import matplotlib.pyplot as plt
    import pygame
    import io
    
    plt.plot(Generation=[], Points=[])
    plt.title('Points per Generation')
    plt.xlabel('Generation')
    plt.ylabel('Points')
    
    plot_stream = io.BytesIO()
    plt.savefig(plot_stream, formatstr='png')
    plot_stream.seek(0)
    
    pygame.init()
    plot_surface = pygame.image.load(plot_stream, 'PNG')
    
    window = pygame.display.set_mode(plot_surface.get_size())
    clock = pygame.time.Clock()
    
    run = True
    while run:
        clock.tick(100)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False 
    
        window.fill(0)
        window.blit(plot_surface, (0, 0))
        pygame.display.flip()
    
    pygame.quit()
    exit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 2021-03-30
      • 2021-03-05
      • 2015-05-30
      • 1970-01-01
      • 2016-11-11
      相关资源
      最近更新 更多