Created
January 21, 2012 23:16
-
-
Save Djexus/1654472 to your computer and use it in GitHub Desktop.
A script which simulate a person who writes a text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import pygame | |
import itertools | |
from pygame.locals import * | |
NULLCHAR = '\0' | |
BACKSPACE = '\b' | |
LEFT = '\1' | |
RIGHT = '\2' | |
pygame.init() | |
pygame.font.init() | |
class TextWriter(pygame.surface.Surface): | |
''' | |
Class which simulate a person who writes a text | |
Usage: | |
>>> writer = TextWriter() | |
>>> writer.push('PRESS ENTER\0\0\0\b\b\b\b\bKEY\1\1\1A \2\2\2') | |
>>> writer.update() | |
''' | |
def __init__(self, font=None, size=30, color=(255, 255, 255)): | |
self.textiter = iter('') | |
self.textwritten = [] | |
self.font = pygame.font.Font(font, size) | |
self.color = color | |
self.cursortime = 3 | |
self.cursorfreq = 2 | |
self.cursorblink = 0 | |
self.cursorindex = 0 | |
self.update() | |
def push(self, text): | |
self.textiter = itertools.chain(self.textiter, text) | |
def update(self): | |
try: | |
char = next(self.textiter) | |
except StopIteration: | |
pass | |
else: | |
if char == BACKSPACE: | |
if self.textwritten: | |
self.cursorindex -= 1 | |
self.textwritten.pop(self.cursorindex) | |
elif char == LEFT: | |
self.cursorindex -= 1 | |
elif char == RIGHT: | |
self.cursorindex += 1 | |
elif char != NULLCHAR: | |
self.textwritten.insert(self.cursorindex, char) | |
self.cursorindex += 1 | |
self.cursorblink += 1 | |
self.cursorblink %= (self.cursortime + self.cursorfreq) | |
text = self.font.render(''.join(self.textwritten), True, self.color) | |
cursor = self.font.render((self.textwritten + ['_'])[self.cursorindex], True, self.color, self.color) | |
cursor.set_alpha(255 if self.cursorblink < self.cursortime else 0) | |
cursorrect = cursor.get_rect() | |
cursorrect.bottomright = self.font.size(''.join(self.textwritten[:self.cursorindex]) + '_') | |
super(TextWriter, self).__init__((max(text.get_width(), cursorrect.right), text.get_height()), SRCALPHA) | |
self.fill((0, 0, 0, 0)) | |
self.blit(text, (0, 0)) | |
self.blit(cursor, cursorrect) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment