Python 一次显示一个字符

1 投票
1 回答
792 浏览
提问于 2025-04-17 21:05

我正在重做《口袋妖怪黄版》的一个部分,尽量让它和原版一样!这两天我一直在寻找一种聪明又高效的方法,想要在文本框中逐个显示字符串的字符,就像口袋妖怪游戏那样!(顺便说一下,我使用的是pygame和python)。有没有人知道怎么做到这一点?我试过很多方法,但每次逐个渲染字符时,它们之间总是留有不够的空间。

抱歉问题问得有点长!

谢谢大家的关注!我不太确定我是不是知道正确的方式来展示我的代码,是直接复制粘贴到这里,还是上传到Dropbox或者其他地方……

为了更清楚一点,我使用的字体大小是28,所以我现在尝试渲染字符的方式是,做一个列表,每个元素的格式是(要渲染的字符,x坐标,y坐标)。下一个字符的格式就是(要渲染的字符2,x坐标 + 28,y坐标)。但用这种方法处理问题时,有些字符之间的空间不够,而有些字符之间的空间就刚好。

谢谢大家的回答!经过仔细观察模拟器,我发现渲染字符之间的不当间距在模拟器中也很明显!所以我决定忽略这个问题,继续我的项目!!祝大家有个愉快的一天!

1 个回答

1

好的,这里是我目前想到的最佳解决方案。

你想要显示一段文字,但希望一次只显示一个字符。对于字符串,你可以用类似 string[0:len(string)] 的方式,这样会返回整个字符串。所以我在想,如果你降低帧率几秒钟,或者如果你不想这样做,因为你还想接受用户输入来跳过文本。

你可以使用一个循环,检查文本是否正在显示。如果正在显示,你就想在屏幕上显示的字符串中添加一个新字母。我建议为屏幕上显示的文本使用一个类。

surf = pygame.Surface(80, 80)
Text = TextBoxString("Hello World")
font = pygame.font.SysFont("Arial", 18)
while true:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()
        elif event.type == MOUSEBUTTONUP:
            Text.showAll()
    surf.fill((0,0,0))
    text = font.render(Text.currentString, (0,0,0))
    surf.blit(text, (0,0))
    Text.addOn()


class TextBoxString:
    def __init__(self, string):
        #string that you will be dealing with
        self.totalString = string
        self.currentString = string[0]
        #how many characters you want shown to the screen
        self.length = 0
        #this means that every four times through your 
        #while loop a new char is displayed
        self.speed = 4
    def addOn(self) #adds one to the loop num and then checks if the loop num equals the speed
        self.loopNum += 1
        if self.loopNum == self.speed:
            self.length += 1
            self.loopNum=0
        self.currentString = totalString[0: self.length]
    def showAll(self):
        self.length = len(self.totalString)
        self.currentString = [0: self.length]

撰写回答