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.
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.
for k in range (0, len(board.keys()), 3): #check if keys are equal hereBut dictionary do not have order, is that right?
How can I rewrite method testForAWin to minimize code duplication -while still using a dictionary?
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)