11# Tic Tac Toe
22
33import random
4- import sys
54
6- def get_input ():
7- if sys .version_info >= (3 , 0 ):
8- return input ()
9- else :
10- return raw_input ()
5+ try :
6+ input = raw_input
7+ except NameError :
8+ pass
119
1210def drawBoard (board ):
1311 # This function prints out the board that it was passed.
@@ -23,27 +21,21 @@ def inputPlayerLetter():
2321 # Lets the player type which letter they want to be.
2422 # Returns a list with the player's letter as the first item, and the computer's letter as the second.
2523 letter = ''
26- while not (letter == 'X' or letter == 'O' ):
27- print ('Do you want to be X or O?' )
28- letter = get_input ().upper ()
24+ while letter not in ('X' , 'O' ):
25+ letter = input ('Do you want to be X or O? ' ).upper ()
2926
3027 # the first element in the tuple is the player's letter, the second is the computer's letter.
31- if letter == 'X' :
32- return ['X' , 'O' ]
33- else :
34- return ['O' , 'X' ]
28+
29+ return ['X' , 'O' ] if letter == 'X' else ['O' , 'X' ]
3530
3631def whoGoesFirst ():
3732 # Randomly choose the player who goes first.
38- if random .randint (0 , 1 ) == 0 :
39- return 'computer'
40- else :
41- return 'player'
33+ return random .choice (('computer' , 'player' ))
4234
4335def playAgain ():
4436 # This function returns True if the player wants to play again, otherwise it returns False.
4537 print ('Do you want to play again? (yes or no)' )
46- return get_input ().lower ().startswith ('y' )
38+ return input ().lower ().startswith ('y' )
4739
4840def makeMove (board , letter , move ):
4941 if isSpaceFree (board ,move ):
@@ -81,28 +73,18 @@ def getPlayerMove(board):
8173 move = ' '
8274 while move not in '1 2 3 4 5 6 7 8 9' .split () or not isSpaceFree (board , int (move )):
8375 print ('What is your next move? (1-9)' )
84- move = get_input ()
76+ move = input ()
8577 return int (move )
8678
8779def chooseRandomMoveFromList (board , movesList ):
8880 # Returns a valid move from the passed list on the passed board.
8981 # Returns None if there is no valid move.
90- possibleMoves = []
91- for i in movesList :
92- if isSpaceFree (board , i ):
93- possibleMoves .append (i )
94-
95- if len (possibleMoves ) > 0 :
96- return random .choice (possibleMoves )
97- else :
98- return None
82+ possibleMoves = [i for i in movesList if isSpaceFree (board , i )]
83+ return random .choice (possibleMoves ) if possibleMoves else None
9984
10085def getComputerMove (board , computerLetter ):
10186 # Given a board and the computer's letter, determine where to move and return that move.
102- if computerLetter == 'X' :
103- playerLetter = 'O'
104- else :
105- playerLetter = 'X'
87+ playerLetter = 'O' if computerLetter == 'X' else 'X'
10688
10789 # Here is our algorithm for our Tic Tac Toe AI:
10890 # First, check if we can win in the next move
0 commit comments