Files
textual/docs/examples/guide/widgets/checker03.py
2023-02-03 11:23:14 +01:00

67 lines
1.7 KiB
Python

from __future__ import annotations
from textual.app import App, ComposeResult
from textual.geometry import Size
from textual.strip import Strip
from textual.scroll_view import ScrollView
from rich.segment import Segment
class CheckerBoard(ScrollView):
COMPONENT_CLASSES = {
"checkerboard--white-square",
"checkerboard--black-square",
}
DEFAULT_CSS = """
CheckerBoard .checkerboard--white-square {
background: #A5BAC9;
}
CheckerBoard .checkerboard--black-square {
background: #004578;
}
"""
def get_content_width(self, container: Size, viewport: Size) -> int:
return 64
def get_content_height(self, container: Size, viewport: Size, width: int) -> int:
return 32
def on_mount(self) -> None:
self.virtual_size = Size(64, 32)
def render_line(self, y: int) -> Strip:
"""Render a line of the widget. y is relative to the top of the widget."""
scroll_x, scroll_y = self.scroll_offset
y += scroll_y
row_index = y // 4 # four lines per row
white = self.get_component_rich_style("checkerboard--white-square")
black = self.get_component_rich_style("checkerboard--black-square")
if row_index >= 8:
return Strip.blank(self.size.width)
is_odd = row_index % 2
segments = [
Segment(" " * 8, black if (column + is_odd) % 2 else white)
for column in range(8)
]
strip = Strip(segments, 8 * 8)
strip = strip.crop(scroll_x, scroll_x + self.size.width)
return strip
class BoardApp(App):
def compose(self) -> ComposeResult:
yield CheckerBoard()
if __name__ == "__main__":
app = BoardApp()
app.run()