I'm trying to make an RPG game using PyGame and I've done some searching and can't find a simple way to display text on the screen with a "typewriter" effect (each letter appearing letter by letter as if it was being typed). I've been trying to use other modules, and looking at other answers on StackOverflow, but none of it has worked for me so far. Any help would be appreciated. I'm trying to do this with as little code as I can, as currently it's very messy. The code so far can be found on my Github. https://github.com/LucasGlennieOC/classroom I tried to work out how to use Typewriter Effect Pygame in my game, but it didn't work.
Asked
Active
Viewed 225 times
1 Answers
0
A simple way to implement this is to use a clock to periodically re-render the bitmap of the text to include more and more letters.
#! /usr/bin/python3
import pygame
import sys
WIDTH = 600
HEIGHT= 300
WHITE = (255,255,255)
BLACK = ( 0, 0, 0)
pygame.init()
window = pygame.display.set_mode( ( WIDTH, HEIGHT ) )
pygame.display.set_caption( "Typewriter Effect" )
font = pygame.font.Font( None, 30 )
text = 'The Owl and the Pussy-cat went to sea'
text_cursor = 0 # what length of text is shown
text_image = font.render( '*', True, BLACK ) # starting image
typing_speed = 50 # milliseconds, smaller is faster
next_update = 0 # time (in future) next letter is added
while True:
clock = pygame.time.get_ticks() # time now
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
# paint the window
window.fill( (0,0,0 ) ) # paint it black
window.blit( text_image, ( 0,0 ) )
# Is it time to type another letter
if ( clock > next_update ):
# Set the time for the *next* letter-add
next_update = clock + typing_speed # in the future
if ( text_cursor < len( text ) ):
# Update the text
text_cursor += 1
# Re-make the text-bitmap with another letter
text_image = font.render( text[0:text_cursor], True, WHITE )
pygame.display.flip()
The above demonstrates the algorithm, but it is not very efficient.

Kingsley
- 14,398
- 5
- 31
- 53