开发者

Efficient way of adding one character at a time from one string to another in Python

开发者 https://www.devze.com 2023-01-08 21:43 出处:网络
I\'m currently making a function using pygame that draws a message on the screen, adding one character each frame (i.e. The Hunt for Red October).I know that I could simply copy (or pass) gradually bi

I'm currently making a function using pygame that draws a message on the screen, adding one character each frame (i.e. The Hunt for Red October). I know that I could simply copy (or pass) gradually bigger slices from the original string, but I know that it would be very resource-intensive. Is there a better way to do this?

Code, using gradually bigger slices:

def full_screen_dialog_tt(thesurface, thefont, theclock, message, thebeep):
 i = 0
 while(i < len(message)): # Initialize the string display
  theclock.tick(60)
  thesurface.fill((0, 0, 0))
  thesurface.blit(thefont.render(message[i]+"_"))
  pygame.display.flip()
  thebeep.play()
 while(1): # Whole string is here now
  theclock.开发者_运维百科tick(60)
  for event in pygame.events.get():
   if event.type == MOUSEBUTTONDOWN: return


In a place where you are intentionally slowing down the game (for the text fade-in) - does it really matter? You could pass the whole string, and change the display routine to display one more letter in every frame.


Can't you just print the characters one at a time displaced without clearing the background? You can get the character using slicing.


Assuming you're having a screen object available, this might work:

import time
text = 'The Hunt for Red October'
myfont = pygame.font.SysFont("arial", 16)
for index, ch in enumerate(text): 
    letter = myfont.render(ch, True, (0, 0, 0), (255, 255, 255))
    screen.blit(letter, (index * 20, 20))
    time.sleep(1)


You can access a single character from a string using indexes:

>>> s = 'string'
>>> s[2]
'r'
0

精彩评论

暂无评论...
验证码 换一张
取 消