Dec-26-2021, 12:39 PM
Hello,
I'm going through an introductory book on Python and there's a chapter in which the author presents code for a simple tic-tac-toe game (see below):
- Line 10: I understand that there needs to be some sort of loop in order for the game to work, but I'm not sure what the for loop here is doing. Range(9) in Python generates 10 numbers, correct: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9? If that's right, why is the main code in the program (which is indented under the for loop) set to run 10 times? I thought this might have something to do with the layout of the tac-tac-toe board, but that only has nine (not 10) slots.
- Line 14: I understand that the game takes the user's move as input and then needs to apply that move to the existing tic-tac-toe board somehow. I also understand somewhat intuitively how lines 15-18 alternate the turns between the two players. But I don't think I understand the actual mechanics of how the board (which is a dictionary) is being modified by the use of the brackets in "theBoard[move] = turn."
Thank you so much in advance for any help.
I'm going through an introductory book on Python and there's a chapter in which the author presents code for a simple tic-tac-toe game (see below):
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']) turn = 'X' for i in range(9): printBoard(theBoard) print('Turn for ' + turn + '. Move on which space?') move = input() theBoard[move] = turn if turn == 'X': turn = '0' else: turn = 'X' printBoard(theBoard)I think I understand everything that is going on in this code except for lines 10 and 14:
- Line 10: I understand that there needs to be some sort of loop in order for the game to work, but I'm not sure what the for loop here is doing. Range(9) in Python generates 10 numbers, correct: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9? If that's right, why is the main code in the program (which is indented under the for loop) set to run 10 times? I thought this might have something to do with the layout of the tac-tac-toe board, but that only has nine (not 10) slots.
- Line 14: I understand that the game takes the user's move as input and then needs to apply that move to the existing tic-tac-toe board somehow. I also understand somewhat intuitively how lines 15-18 alternate the turns between the two players. But I don't think I understand the actual mechanics of how the board (which is a dictionary) is being modified by the use of the brackets in "theBoard[move] = turn."
Thank you so much in advance for any help.