Python Forum

Full Version: I am getting this TypeError: 'TreasureMap' object is not subscriptable.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Thank you in advance
I am getting this TypeError: 'TreasureMap' object is not subscriptable.

This is my code
i = 0
k = 0

class TreasureMap:
    def __init__(self , map ):
        self.map = map
        self.rows = len(map)
        self.columns = len(hiddenmap1[2]) 
        

    def create_hunter_map(self):
        empty_map = []

        for i in range(self.rows):
            row = []
            for k in range(self.columns):
                row.append('-')
            empty_map.append(row)
         
        return empty_map
            
 #return [["-" for _ in range(self.columns)] for _ in range(self.rows)]

#ta row kai coloum einai ta simia pou dialego na paw
#ftiaxno prwta to updated xarti
#meta ftiaxno xarti opou tha lipouin tixon thisauroi
    def update_hunter_map( self , Hmap , location):
        row , column  = location
        
        if self.map[row][column] == 'x':
            Hmap[row][column] = 'x'
            self.map[row][column] = 'o'
            return 1
        else:
            Hmap[row][column] = 'o'
            return 0
        

class TreassureHunter():
    def __init__(self , name , map):
        self.name = name
        self.map = map
        self.h_map = treasure_map.create_hunter_map()
        self.treassures = 0

    def move_on_map(self , location):
        
        row , column  = location

        if self.map[row][column] == 'x':
            self.h_map[row][column] = 'x'
            self.treassures += 1
        else:
            self.h_map[row][column] = 'o'
        #return self.h_map
        
    def check_status(self):
        print(f'{self.name} status')
        for row in self.h_map:
           print(' '.join(row))
        print(f"βρέθηκαν {self.treassures} θησαυροίe")
        return self.h_map , self.treassures
        

 hiddenmap1=[['o','o','o','o','x'],
            ['o','x','x','o','x'],
            ['o','o','o','o','x']]


treasure_map = TreasureMap(hiddenmap1)

hunter_map = treasure_map.create_hunter_map()

#updated_map = treasure_map.update_hunter_map(hunter_map ,[0,4])

Hunter1 = TreassureHunter('denis' , treasure_map)


Hunter1.move_on_map([2,1])
Hunter1.check_status()

Hunter1.move_on_map([0,0])
Hunter1.check_status()

Hunter1.move_on_map([1,1])
Hunter1.check_status()

Hunter1.move_on_map([0,3])
Hunter1.check_status()

Hunter2 = TreassureHunter('Vagg' , treasure_map)

Hunter2.move_on_map([1,1])
Hunter2.check_status()
MY GOAL IT TO GET THIS RESULT
Output:
Vaggstatus Map ----- ----- -o--- Acquired 0 treasures so far! Vaggstatus Map ----x ----- -o--- Acquired 1 treasures so far! Vaggstatus Map o---x ----- -o--- Acquired 1 treasures so far! Robstatus Map ----o ----- ----- Acquired 0 treasures so far!
(May-25-2024, 09:36 AM)makilakos Wrote: [ -> ]I am getting this TypeError: 'TreasureMap' object is not subscriptable.
If you post the complete error message sent by Python (full traceback), we could see where the error comes from.
This is the reason for the index error.
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