问题描述
所以,我对 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()