Jim Hodgen wrote:
I am learning Python with a minesweeper-engine project. Future activities turn my attention to exploring the use of dictionaries as sparse matrices, hence the representation of the gameboard. Why can't I fill the dictionary-as-a-matrix with an instance of class Square? Why do I need a custom method to make the assignment? What am I not understanding?
You don't have a sparse matrix here. There is a dictionary entry for every square. You might as well use a nested list or an array from one of the array modules.

If you want a Baseboard instance to directly accept keyed assignment use:

class Basebaord(dict)

and drop boardsquares.

*_# basics module (mineswobj1)contents..._*
class Square:
mined = True # False if empty, True if mined, no other values allowed marked = 0 # False if 0, marked-as-mined if 1, marked-as-unknown if 2, no other values allowed displaystate = 0 # covered if 0, marked if 1, exposed if 2, selected if 3, no other values allowed

marked and display state are in conflict and overlap. Consider instead:
   selected = False
   displaystate is one of covered-blank, covered-marked, mined, exposed
minedneighbors = 0 # number of mined neighboring squares, max legit value = 8 class Baseboard: xdimension = 0 # x-dimension of the gameboard, integer value greater than 0 ydimension = 0 # y-dimension of the gameboard, integer value greater than 0 minenumber = 0 # number of mines on the board for play, value from 0 to (xdimension * ydimension) state = 0 # playable if 0, not-playable-exploded if 1, not-playable-solved if 2 boardsquares = {} # dictionary used to emulate an addressable 2 dimensional grid where an instance of class Square # is inserted with a key consisting of a tuple describing its zero-based address in the grid

def initializeboard(xdim, ydim, minenum):
    gameboard = Baseboard()
    for yct in range(ydim):
        for xct in range(xdim):
            gameboard[(xct,yct)] = Square()
            print 'gameboard[(',xct,yct, ')] =', gameboard[(xct,yct)]

*_# driver module contents_*
import basics

mineswobj1.initializeboard(3, 4, 5)

_*#error message*_
Traceback (most recent call last):
  File "C:\jmh\Python\minedriver0.py", line 6, in <module>
    mineswobj1.initializeboard(3, 4, 5)
  File "C:\jmh\Python\mineswobj1.py", line 26, in initializeboard
    gameboard[(xct,yct)] = Square()
AttributeError: Baseboard instance has no attribute '__setitem__'
------------------------------------------------------------------------

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


--
Bob Gailer
Chapel Hill NC 919-636-4239

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to