Skip to content

Week 2 03 30

fengttt edited this page Mar 30, 2020 · 2 revisions

Plan

  • Again, review homework :)
  • More on list, list of lists, indexing, negative indexing.
  • Programming style, on variable, arguments, and global variables.
  • TicTacToe. Introduce the concept of game loop.

Homework

  1. We know a string is not mutable, means you cannot change it.
>>> x = "abc"
>>> x[1] = '*'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> 

Now, write a function in your siplib.toy,

def replaceCharAt(s, i, c):
   ''' Replace the i-th character of string s with c, so replace('abc', 1, '*') should return 'a*c' '''
  1. Write a function rev, that will reverse a list
def rev(a):
   ''' Reverse list, for example a = [1, 2, 3], after calling rev(a), a should be [3, 2, 1] '''
  1. In the tictactoe game, how do you represent the state of your game? The game board is 3x3, and at each position, it can be either empty, or holds a x, or o.
  2. Create a directory m2 in your project. Create a file tictactoe.py. Follow the example code below. At this moment, I want your program to print an empty board on the screen. Note that, we only have one board in the game therefore, making it global is actually OK, but I would not do that, I pass board as parameter to the printBoard function. Avoid global variables if you can!
def initBoard():
    ''' b will be the board you designed in homework problem 3.  Initialize b, so that every position is empty. ''' 
    return b

def showBoard(b):
    ''' Print board.   With cordinates.   For example, empty board, should be printed out as
              012
             0...
             1...
             2...
    '''

if __name__ == '__main__':
    board = initBoard()
    showBoard(board)
Clone this wiki locally