Python Forum
I am getting this TypeError: 'TreasureMap' object is not subscriptable.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I am getting this TypeError: 'TreasureMap' object is not subscriptable.
#1
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!
Larz60+ write May-25-2024, 09:45 AM:
Duplicate posts have been soft deleted. Please post only once.
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time, please use BBCode tags on future posts.
Reply
#2
(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.
« We can solve any problem by introducing an extra level of indirection »
Reply
#3
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  TypeError: cannot pickle ‘_asyncio.Future’ object Abdul_Rafey 1 653 Mar-07-2024, 03:40 PM
Last Post: deanhystad
  error in class: TypeError: 'str' object is not callable akbarza 2 692 Dec-30-2023, 04:35 PM
Last Post: deanhystad
Bug TypeError: 'NoneType' object is not subscriptable TheLummen 4 950 Nov-27-2023, 11:34 AM
Last Post: TheLummen
  TypeError: 'NoneType' object is not callable akbarza 4 1,315 Aug-24-2023, 05:14 PM
Last Post: snippsat
  [NEW CODER] TypeError: Object is not callable iwantyoursec 5 1,676 Aug-23-2023, 06:21 PM
Last Post: deanhystad
  TypeError: 'float' object is not callable #1 isdito2001 1 1,207 Jan-21-2023, 12:43 AM
Last Post: Yoriz
  TypeError: a bytes-like object is required ZeroX 13 5,034 Jan-07-2023, 07:02 PM
Last Post: deanhystad
  Help with python 'not subscriptable' error Extra 3 2,393 Dec-16-2022, 05:55 PM
Last Post: woooee
  TypeError: 'float' object is not callable TimofeyKolpakov 3 1,729 Dec-04-2022, 04:58 PM
Last Post: TimofeyKolpakov
  API Post issue "TypeError: 'str' object is not callable" makeeley 2 2,139 Oct-30-2022, 12:53 PM
Last Post: makeeley

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020