Source code for bruhanimate.bruheffect.base_effect
"""Copyright 2023 Ethan ChristensenLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License."""importrandomfromabcimportABC,abstractmethodimportnumpyasnpfrom..bruhutil.bruhfferimportBufferfrom..resizeimport_size
[docs]classBaseEffect(ABC):"""A simulation with a persistent private raster and explicit resource ownership. Built-in simulations advance one step per update. Set updates_per_second on the Player to choose their speed independently of presentation FPS. Custom effects can use dt (seconds) for continuous motion instead. """
[docs]def__init__(self,buffer:Buffer,background:str,*,seed:int|None=None):""" Base class for all effects. Args: buffer (Buffer): Effect buffer to push updates to. background (str): character or string to use for the background. seed: Non-negative integer for independent Python and NumPy random streams. None uses fresh entropy. Global RNG state is untouched. """ifseedisnotNone:iftype(seed)isnotint:raiseTypeError("seed must be an integer or None")ifseed<0:raiseValueError("seed must be non-negative")self.rng=random.Random(seed)self.np_rng=np.random.default_rng(seed)self.buffer=bufferself.background=backgroundself.background_length=len(background)self._viewport:tuple[int,int]|None=Noneself._started=False
[docs]defstart(self)->None:"""Acquire runtime resources. Construction must not open devices or threads. Players and scenes call this before the first update and own cleanup for the duration of playback. Overrides should tolerate repeated calls. """self._started=True
[docs]defstop(self)->None:"""Release runtime resources; safe to call before start or more than once."""self._started=False
[docs]defclose(self)->None:"""Release resources through stop(); safe before start and on repeats."""self.stop()
[docs]@abstractmethoddefupdate(self,dt:float)->None:"""Advance simulation by one tick; dt is the tick duration in seconds."""
[docs]defresize(self,size:tuple[int,int])->None:"""Change the drawing viewport, retaining the original simulation raster. Shrinking clips from the bottom/right; growing reveals the original raster again. Cells beyond it remain transparent to the owner. Random streams, resource handles and simulation coordinates are unchanged. Subclasses can override this typed hook to adapt simulation arrays and repaint the private raster at the current tick, then call super().resize. Built-in adapters use this contract; draw must still never advance time. """_size(size)self._viewport=size
[docs]defdraw(self,buffer:Buffer)->None:"""Copy the latest raster without advancing or sharing mutable cells."""ifself._viewportisNone:buffer._validate_dimensions(self.buffer)elif(buffer.width(),buffer.height())!=self._viewport:raiseValueError("Drawing buffer must match the resized viewport")foryinrange(min(buffer.height(),self.buffer.height())):forxinrange(min(buffer.width(),self.buffer.width())):cell=self.buffer.buffer[y][x]ifcellisnotNone:buffer.buffer[y][x]=str(cell)