Week 13, Monday: More Classes



Designing classes

If you were writing a tic-tac-toe game, using the Zelle graphics library, what objects would you use? Take a few minutes and jot down a main() function that might play the tic-tac-toe game (create the board, user goes, computer goes, etc). Just like the TDD we did earlier in the semester, it helps if you have some idea of the objects you need to create, what data is stored in each object, and what methods you will need to call of each object.

One way to write a game like tic-tac-toe, or any board game with squares that the user clicks on (sudoku, scrabble, nonograms, 2048, etc), is to have two classes: a Cell or Tile class, and a Board class that uses the Cell class. For example, in tic-tac-toe, we could have a Board class the contains a python list of Cell objects, where each Cell object can be clicked on, and display a character ("X" or "O"), or change colors.

tic-tac-toe board

the Cell class

Here is one way you could write the Cell class:

testing the cell

Once you have __init__(self,cp,size,gw) written, write some test code to see if it works!

def main():
  w = 600
  h = w
  gw = GraphWin("cell test",w,h)
  cp = Point(w/2, h/2)
  size = w/4
  c = Cell(cp,size,gw)
  c.setChar("X")
  assert(c.getChar() == "X")
  assert(c.clicked(cp) == True)
  pt = gw.getMouse()
  if c.clicked(pt):
    c.setColor("red")
  click = gw.getMouse()

if __name__ == "__main__":
  main()