Source code for bruhanimate.bruheffect.sand_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."""importrandomimportnumpyasnpfrombruhcolorimportbruhcoloredasbcfrom..bruhutilimportBufferfrom.base_effectimportBaseEffectfrom.settingsimportSandSettingsdef_heat(r:float)->int:r=max(0.0,min(1.0,r))ifr<0.25:return17+int(r*4*18)elifr<0.5:return51+int((r-0.25)*4*12)elifr<0.75:return82+int((r-0.5)*4*12)else:return220+int((r-0.75)*4*3)
[docs]classSandEffect(BaseEffect):""" Falling-sand cellular automaton. Particles spawn randomly at the top of the screen and fall downward, cascading diagonally when blocked. Color indicates height — hotter at the top, cooler toward the bottom. Particles drain from the bottom row to keep the simulation flowing indefinitely. """
[docs]defset_spawn_rate(self,rate:float):"""Set the per-column probability of spawning a new particle each frame (0–1)."""self.spawn_rate=max(0.0,min(1.0,rate))
[docs]defrender_frame(self,frame_number:int):self.buffer.clear_buffer(val=self.background)# Drain bottom row so the simulation never stallsself._grid[self._h-1,:]=0# Spawn new particles at the topforcolinrange(self._w):ifrandom.random()<self.spawn_rateandself._grid[0,col]==0:self._grid[0,col]=1# Update: process non-empty cells bottom-to-topocc_r,occ_c=np.where(self._grid>0)iflen(occ_r):order=np.argsort(-occ_r)foridxinorder:r,c=int(occ_r[idx]),int(occ_c[idx])ifr>=self._h-1orself._grid[r,c]==0:continueifself._grid[r+1,c]==0:self._grid[r,c]=0self._grid[r+1,c]=1else:dirs=(-1,1)ifrandom.random()<0.5else(1,-1)fordindirs:nc=c+dif0<=nc<self._wandself._grid[r+1,nc]==0:self._grid[r,c]=0self._grid[r+1,nc]=1break# Drawlit_r,lit_c=np.where(self._grid>0)forr,cinzip(lit_r,lit_c):ratio=1.0-float(r)/self._hcolor=_heat(ratio)ifself.colorelseNonech=bc(self.char,color=color)ifcolorisnotNoneelseself.charself.buffer.put_char(int(c),int(r),ch)