asciigame/render.py

81 lines
2.2 KiB
Python

class RendererLoopBreak(BaseException):
pass
class Renderer:
"""
Class responsible for updating tiles, their states, animations, etc.
In the future, also takes in a WaterLayer and updates it with the game map.
"""
def __init__(self):
self.tiles = []
# location of the top left corner of the viewpoint
self.pos = [0, 0]
self.viewport = [80, 24]
def addTile(self, tile):
self.tiles.append(tile)
def massUpdate(self):
for i in self.tiles:
if i.ttype == "standard":
i.update(self.tiles)
def inViewport(self, pos):
if pos[0] < 0 or pos[0] > self.viewport[0] - 1:
return False
if pos[1] < 0 or pos[1] > self.viewport[1] - 1:
return False
return True
def selectForRendering(self):
"""
Returns what tiles are in the viewport.
"""
tilesInScene = []
for i in self.tiles:
dims = i.dims
pos = i.getCoords()
try:
for j in range(dims[0]):
for k in range(dims[1]):
if self.inViewport([pos[0] + j, pos[1] + k]):
tilesInScene.append(i)
raise RendererLoopBreak
except RendererLoopBreak:
pass
self.cachedTiles = tilesInScene
return tilesInScene
def render(self):
board = [
["." for i in range(self.viewport[1])]
for i in range(self.viewport[0])
]
toRender = self.selectForRendering()
for tile in toRender:
rendered = tile.render()
coords = tile.getCoords()
for j in range(len(rendered[0])):
for i in range(len(rendered)):
board[i + coords[0]][j + coords[1]] = rendered[j][i]
return board
def finalRender(self, rendered=None):
if not rendered:
rendered = self.render()
for i in range(len(rendered[0])):
buf = []
for j in range(len(rendered)):
buf.append(rendered[j][i])
print(''.join(buf))