65 lines
1.8 KiB
Python
65 lines
1.8 KiB
Python
"""
|
|
This module contains the Map class.
|
|
"""
|
|
|
|
import numpy as np
|
|
|
|
def is_on_border(i, j, w ,h):
|
|
return i == 0 or i == w - 1 or j == 0 or j == h - 1
|
|
|
|
class Map:
|
|
"""
|
|
The map of the game.
|
|
|
|
It basically consists of a matrix with a certain width and height. You can
|
|
access its items by using the [] operator.
|
|
"""
|
|
def __init__(self, w, h, empty, wall):
|
|
"""
|
|
Creates a new map from its width and its height.
|
|
|
|
The map will contain (height + 2) * (width + 2) tiles, by having a
|
|
border. The matrix is initialized with `empty` in the inside and
|
|
`wall` on the borders.
|
|
"""
|
|
self.width = w
|
|
self.height = h
|
|
self._data = np.array([[wall if is_on_border(i, j, w + 2, h + 2) else empty for i in range(h + 2)] for j in range(w + 2)])
|
|
|
|
def clone(self):
|
|
"""
|
|
Creates a clone of the map.
|
|
"""
|
|
clone = Map(self.width, self.height, 0, 0)
|
|
clone._data = np.copy(self._data)
|
|
return clone
|
|
|
|
def apply(self, converter):
|
|
"""
|
|
Converts a map by applying a function to each element.
|
|
"""
|
|
converted = Map(self.width, self.height, 0, 0)
|
|
converted._data = np.array([[converter(self._data[i][j]) for i in range(self.height + 2)] for j in range(self.width + 2)])
|
|
return converted
|
|
|
|
def array(self):
|
|
"""
|
|
Returns the inner array of the map.
|
|
"""
|
|
return self._data
|
|
|
|
def clone_array(self):
|
|
"""
|
|
Returns a copy of the inner array of the map.
|
|
"""
|
|
return np.array([[converter(self._data[i][j]) for i in range(self.height + 2)] for j in range(self.width + 2)])
|
|
|
|
def __getitem__(self, index):
|
|
(i, j) = index
|
|
return self._data[i+1][j+1]
|
|
|
|
def __setitem__(self, position, other):
|
|
(i, j) = position
|
|
self._data[i+1][j+1] = other
|
|
|