Hardware Reference
In-Depth Information
on the board but print on a new line when you have outputted squares 2 or 5. his irst pro-
gram is shown in Listing 3-1. Remember, all the code listings for the topic can be found at
www.wiley.com/go/raspberrypiprojects .
Listing 3-1 Printing the Simple Tic-Tac-Toe Board
#!/usr/bin/env python
# Tic-Tac-Toe 1 - print board
board = [ 'O', 'X', ' ', 'O', ' ', 'X', 'O', 'X', 'X' ]
def printBoard():
print
for square in range(0,9):
print board[square],
if square == 2 or square == 5 :
print
print
if __name__ == '__main__':
printBoard()
his is a simple for loop that prints out the contents of the board list one at a time. he print
statement ends in a comma that means that it will not go onto a new line. he variable square
will range through all the positions in the list and when it reaches 2 or 5 an extra print state-
ment is executed. his time it is without a comma at the end, so a new line is produced.
A Better Board
Although Listing 3-1 fulills the desire of printing out the board, it could be improved by add-
ing a grid using some text characters. his is shown in Listing 3-2.
Listing 3-2 Printing a Better Tic-Tac-Toe Board
#!/usr/bin/env python
# Tic-Tac-Toe 2 - print a better board
board = [ 'O', 'X', ' ', 'O', ' ', 'X', 'O', 'X', 'X' ]
def printBoard():
print
print '|',
for square in range(0,9):
print board[square],'|',
if square == 2 or square == 5 :
print
print '- - - - - - -'
print '|',
 
Search WWH ::




Custom Search