Skip to content

Week 2 04 01

fengttt edited this page Apr 1, 2020 · 2 revisions

Plan

  • Continue tictactoe. Explain state, data structure, game loop.
  • Coordinate system, lists, lists of lists, indexing.
  • Kids should run into some trouble by now -- time to introduce debugging.

Homework

  1. We will continue exercises on list, list of list, etc etc. Write the following functions
def zip(a, b):
   '''a, b are two lists, return a list that zip them.  For example, if 
          a = [1, 2, 3, 4], b = ['ok', 'foo', 'bar']
      zip should return [(1, 'ok'), (2, 'foo'), (3, 'bar'), (4, None)]
      Note that a and b may have different length, you need to pack the shorter list with None
   '''
  1. As we said, a function is also a value. For example
def isOdd(x):
    return x % 2 == 1

def isEven(x):
    return x % 2 == 0

def beginWithA(x):
    return x[0] == 'a' or x[0] == 'A'

myfunc = isOdd
myfunc(2)  # this should return False

myfunc = beginWithA
myfunc(2)  # should fail
myfunc('abc')   # should return True

You can pass function as parameters to another function. For example

def filter(a, pred):
    ''' Return filter list of a with pred.  For example, 
        filter([1, 2, 3, 4, 5], isOdd) should return [1, 3, 5]
        filter(['abc', 'def', 'A0'], beginWithA) should return ['abc', 'A0']
    '''
  1. Test your function, rev, zip, filter? Make sure you tested some interesting case, like empty list, etc. Do you find a bug? Try debug and fix it.
  2. This is a big one. Finish your tictactoe.py -- here is a review of what the game looks like,
    1. write your initBoard function, which should return an empty 3x3 board.
    2. write your printBoard function,
    3. game loop, in the loop, read from input and process input. Note that you should handle invalid input, do not let a typo crash your game. According to the input command, put a piece on the board (you should only put a piece on empty position, otherwise, it is an invalid input)
    4. Check if someone wins the game, break out of the game loop if there is a winner
    5. Also, all 9 positions are taken, you should break out the loop and declare a draw.
Clone this wiki locally