微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在python如SanctuaryRPG中同时显示图像和文本?

如何解决如何在python如SanctuaryRPG中同时显示图像和文本?

所以,我对 python 很陌生,但我目前正在编写一个文本冒险游戏。我想知道如何在屏幕底部显示文本,而 ASCII 图像显示在顶部,就像 SanctuaryRPG 一样。

解决方法

好的,基本上,您想打印带有文本的 ASCII 图像。这应该不会太难。

首先,将 ASCII 图像设置为变量。例如:

img = '''
                 __,__
        .--.  .-"     "-.  .--.
       / .. \/  .-. .-.  \/ .. \
      | |  '|  /   Y   \  |'  | |
      | \   \  \ 0 | 0 /  /   / |
       \ '-,\.-"`` ``"-./,-' /
        `'-' /_   ^ ^   _\ '-'`
        .--'|  \._   _./  |'--. 
      /`    \   \ `~` /   /    `\
     /       '._ '---' _.'       \
    /           '~---~'   |       \
   /        _.             \       \
  /   .'-./`/        .'~'-.|\       \
 /   /    `\:       /      `\'.      \
/   |       ;      |         '.`;    /
\   \       ;      \           \/   /
 '.  \      ;       \       \   `  /
   '._'.     \       '.      |   ;/_
    /__>     '.       \_ _ _/,'--.
   .'   '.   .-~~~~~-. /     |--'`~~-.  \
  // / .---'/  .-~~-._/ / / /---..__.'  /
 ((_(_/    /  /      (_(_(_(---.__    .'
           | |     _              `~~`
           | |     \'.
            \ '....' |
             '.,___.'
'''

接下来,将要打印的文本设置为另一个变量。

text = "Do you want to say hi to the monkey?"

最后,像这样打印两个:

print(img)
print(text)

或:

print(img + "\n\n" + text)

\n 只是表示换行。

,

要使用 Pygame 执行与 SanctuaryRPG 中相同的操作,您需要使用每个字符宽度相同的字体(例如 Courier):

font = pygame.font.SysFont("Courier",text_height)

使用 splitlines() 将文本分成几行(参见 How to split a python string on new line characters):

img_text = img.splitlines()

在循环中逐行渲染文本:

for i,line in enumerate(img_text):
    text_surf = font.render(line,True,(255,255,0))
    window.blit(text_surf,(50,20 + i * text_height))

使用以下函数:

def renderTextImage(surf,font,text,x,y,color):
    img_text = text.splitlines()
    for i,line in enumerate(img_text):
        text_surf = font.render(line,color)
        surf.blit(text_surf,(x,y + i * text_height))

最小示例:

repl.it/@Rabbid76/PyGame-AsciiTextImage

import pygame

img_text = r'''
                 __,___.'
'''

def renderTextImage(surf,y + i * text_height))

pygame.init()
window = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()

text_height = 16 
font = pygame.font.SysFont("Courier",text_height)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False          

    window.fill(0)
    renderTextImage(window,img_text,50,20,0))
    pygame.display.flip()

pygame.quit()
exit()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。