May-25-2024, 07:58 PM
(This post was last modified: May-25-2024, 07:58 PM by deanhystad.)
This is the reason for the index error.
The TreasureMap class does nothing useful. It's two methods are a better fit in the TreasureHunter class.
You could make a useful TreasureMap, something that supports better indexing and printing.
if self.map[row][column] == 'x':self.map is a TreasureMap, but this treats it like a list of lists. You could change to self.map.map[row][column], but I think a better solution is to get rid of the TreasureMap class.
The TreasureMap class does nothing useful. It's two methods are a better fit in the TreasureHunter class.
You could make a useful TreasureMap, something that supports better indexing and printing.
class TreasureMap: """A xy map for treasure hunting.""" def __init__(self, map): self.map = map.copy() def __getitem__(self, pos): """Get value using indexing; self[x, y]""" x, y = pos return self.map[y][x] def __setitem__(self, pos, value): """Set valu using indexing; self[x, y] = value""" x, y = pos self.map[y][x] = value def size(self): """Return dimensions of map x, y or columns, rows.""" return len(self.map[0]), len(self.map), def take(self, x, y): """Remove item at x, y. Is it treasure?""" item = self[x, y] self[x, y] = "o" return item def empty_copy(self): """Return empy may the same size as me.""" rows, columns = self.size() return TreasureMap([['-'] * columns for _ in range(rows)]) def __str__(self): """Return string appropriate for printing,""" return "\n".join(" ".join(row) for row in self.map)To use:
class TreasureHunter(): """Hunts for treasure on a map. Keeps notes on where looked.""" def __init__(self, name, map): self.name = name self.map = map self.notes = map.empty_copy() self.treasures = 0 def move(self, x, y): """Move to x, y and dig for treasure.""" self.notes[x, y] = self.map[x, y] if self.notes[x, y] == 'x': self.treasures += 1 return self