如何在 pygame pan 中逐个字母地制作文本? [英] How can I make text in pygame pan letter by letter?

查看:41
本文介绍了如何在 pygame pan 中逐个字母地制作文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我正在制作的某个游戏,我认为如果每个字母一个一个出现,而不是一次出现会更好看.我该怎么做才能做到这一点?

For a certain game I'm making, I think it would look a lot better if each letter came one by one, rather than all at once. What can I do to do this?

推荐答案

您可以使用迭代器轻松完成此操作.只需从原始文本创建一个迭代器,调用 next(iterator) 获取下一个字符并一个接一个地添加到字符串变量中,直到其长度等于原始字符串的长度.

You can do this pretty easily with an iterator. Just create an iterator from the original text, call next(iterator) to get the next characters and add one after the other to a string variable until its length is equal to the length of the original string.

要重新开始动画或显示另一个文本,请创建一个新的迭代器 text_iterator = iter(text_orig) 并再次设置 text = ''.

To restart the animation or display another text, create a new iterator text_iterator = iter(text_orig) and set text = '' again.

我也在这里使用 ptext 库,因为它是能够识别换行符以创建多行文本.

I also use the ptext library here because it is able to recognize newline characters to create multiline text.

import pygame as pg
import ptext


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
BLUE = pg.Color('dodgerblue')
# Triple quoted strings contain newline characters.
text_orig = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum."""

# Create an iterator so that we can get one character after the other.
text_iterator = iter(text_orig)
text = ''

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        # Press 'r' to reset the text.
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_r:
                text_iterator = iter(text_orig)
                text = ''

    if len(text) < len(text_orig):
        # Call `next(text_iterator)` to get the next character,
        # then concatenate it with the text.
        text += next(text_iterator)

    screen.fill(BG_COLOR)
    ptext.draw(text, (10, 10), color=BLUE)  # Recognizes newline characters.
    pg.display.flip()
    clock.tick(60)

pg.quit()

另一种方法是对字符串进行切片:

An alternative would be to slice the string:

i = 0  # End position of the string.
done = False
while not done:
    # ...
    i += 1.5  # You can control the speed here.

    screen.fill(BG_COLOR)
    ptext.draw(text_orig[:int(i)], (10, 10), color=BLUE)

要重启这个,你只需要设置i = 0.

To restart this, you just need to set i = 0.

这篇关于如何在 pygame pan 中逐个字母地制作文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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