Renders texts that fades out after some seconds that the user specifies
| 192 | |
| 193 | |
| 194 | class FadingText(object): |
| 195 | """Renders texts that fades out after some seconds that the user specifies""" |
| 196 | |
| 197 | def __init__(self, font, dim, pos): |
| 198 | """Initializes variables such as text font, dimensions and position""" |
| 199 | self.font = font |
| 200 | self.dim = dim |
| 201 | self.pos = pos |
| 202 | self.seconds_left = 0 |
| 203 | self.surface = pygame.Surface(self.dim) |
| 204 | |
| 205 | def set_text(self, text, color=COLOR_WHITE, seconds=2.0): |
| 206 | """Sets the text, color and seconds until fade out""" |
| 207 | text_texture = self.font.render(text, True, color) |
| 208 | self.surface = pygame.Surface(self.dim) |
| 209 | self.seconds_left = seconds |
| 210 | self.surface.fill(COLOR_BLACK) |
| 211 | self.surface.blit(text_texture, (10, 11)) |
| 212 | |
| 213 | def tick(self, clock): |
| 214 | """Each frame, it shows the displayed text for some specified seconds, if any""" |
| 215 | delta_seconds = 1e-3 * clock.get_time() |
| 216 | self.seconds_left = max(0.0, self.seconds_left - delta_seconds) |
| 217 | self.surface.set_alpha(500.0 * self.seconds_left) |
| 218 | |
| 219 | def render(self, display): |
| 220 | """ Renders the text in its surface and its position""" |
| 221 | display.blit(self.surface, self.pos) |
| 222 | |
| 223 | |
| 224 | # ============================================================================== |