-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat_log.py
73 lines (61 loc) · 1.99 KB
/
chat_log.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from typing import Iterable, List, Reversible, Tuple
import textwrap
from message_log import Message
import tcod
import color
class ChatLog:
def __init__(self) -> None:
self.messages: List[Message] = []
def add_message(
self,
text: str,
fg: Tuple[int, int, int] = color.white,
*,
stack: bool = True
) -> None:
"""
Add a message to this log.
'text' is the message text, 'fg' is the text color.
If 'stack' is True then the message can stack with a previous message of the same text.
"""
if stack and self.messages and text == self.messages[-1].plain_text:
self.messages[-1].count += 1
else:
self.messages.append(Message(text, fg))
def render(
self,
console: tcod.Console,
x: int,
y: int,
width: int,
height: int,
) -> None:
"""
Render this log over the given area.
'x', 'y', 'width', 'height' is the rectangular region to render onto the 'console'.
"""
self.render_messages(console, x, y, width, height, self.messages)
@staticmethod
def wrap(string: str, width: int) -> Iterable[str]:
"""Return a wrapped text message."""
for line in string.splitlines(): # Handle newlines in messages.
yield from textwrap.wrap(
line, width, expand_tabs=True,
)
@classmethod
def render_messages(
cls,
console: tcod.Console,
x: int,
y: int,
width: int,
height: int,
messages: Reversible[Message],
) -> None:
y_offset = 0
for message in messages:
for line in list(cls.wrap(message.full_text, width)):
console.print(x=x, y=y + y_offset, string=line, fg=message.fg)
y_offset += 1
if y_offset > height:
return # No more space to print messages