Apr-21-2019, 07:48 AM
Hello,
I have a question about "a tic-tac-toe game" using dictionary in automate the boring stuff.
https://automatetheboringstuff.com/chapter5/
Instead of checking if the game has a winner by looking specifically at all rows, all columns and all diagonals, I wish to do it by iterating over keys to detect if three values were equal to each other.
But dictionary do not have order, is that right?
How can I rewrite method testForAWin to minimize code duplication -while still using a dictionary?
I have a question about "a tic-tac-toe game" using dictionary in automate the boring stuff.
https://automatetheboringstuff.com/chapter5/
Instead of checking if the game has a winner by looking specifically at all rows, all columns and all diagonals, I wish to do it by iterating over keys to detect if three values were equal to each other.
1 2 |
for k in range ( 0 , len (board.keys()), 3 ): #check if keys are equal here |
How can I rewrite method testForAWin to minimize code duplication -while still using a dictionary?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
turn = 'X' theBoard = { 'top-L' : ' ' , 'top-M' : ' ' , 'top-R' : ' ' , 'mid-L' : ' ' , 'mid-M' : ' ' , 'mid-R' : ' ' , 'low-L' : ' ' , 'low-M' : ' ' , 'low-R' : ' ' } def printBoard(board): print (board[ 'top-L' ] + '|' + board[ 'top-M' ] + '|' + board[ 'top-R' ]) print ( '-+-+-' ) print (board[ 'mid-L' ] + '|' + board[ 'mid-M' ] + '|' + board[ 'mid-R' ]) print ( '-+-+-' ) print (board[ 'low-L' ] + '|' + board[ 'low-M' ] + '|' + board[ 'low-R' ]) def testForAWin(board): won = False if ((board[ 'top-L' ] = = board[ 'top-M' ] = = board[ 'top-R' ]) and board[ 'top-L' ] ! = ' ' ): won = True elif (board[ 'mid-L' ] = = board[ 'mid-M' ] = = board[ 'mid-R' ] and board[ 'mid-L' ] ! = ' ' ): won = True #to be done for diagonals and columns as well, and lowest row return won for i in range ( 9 ): printBoard(theBoard) print ( 'Turn for :' + turn + ' Choose a space : ' ) move = input () while not theBoard[move] = = ' ' : print ( 'Do not try to steal a place! ' ) move = input () theBoard[move] = turn won = testForAWin(theBoard) if won: print (turn + ' wins the game!' ) break elif turn = = 'X' : turn = '0' else : turn = 'X' printBoard(theBoard) |