Advertisement
asweigart

Untitled

Apr 17th, 2019
328
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.61 KB | None | 0 0
  1. # A non-OOP Tic Tac Toe game.
  2. # By Al Sweigart al@inventwithpython.com
  3.  
  4. # Setting up constants:
  5. ALL_SPACES = ('1', '2', '3', '4', '5', '6', '7', '8', '9')
  6. X, O, BLANK = 'X', 'O', ' '
  7.  
  8. def main():
  9. """Runs a game of Tic Tac Toe."""
  10. print('Welcome to Tic Tac Toe!')
  11. gameBoard = getNewBoard()
  12. turn, nextTurn = X, O
  13.  
  14. while True:
  15. drawBoard(gameBoard)
  16. move = getPlayerMove(gameBoard, turn)
  17. setSpace(gameBoard, move, turn)
  18.  
  19. if isWinner(gameBoard, turn):
  20. drawBoard(gameBoard)
  21. print(turn + ' has won the game!')
  22. break
  23. elif isBoardFull(gameBoard):
  24. drawBoard(gameBoard)
  25. print('The game is a tie!')
  26. break
  27.  
  28. turn, nextTurn = nextTurn, turn
  29.  
  30. def getNewBoard():
  31. """Create a new, blank tic tac toe board."""
  32. board = {}
  33. for space in ALL_SPACES:
  34. board[space] = BLANK
  35. return board
  36.  
  37. def drawBoard(board):
  38. """Display a text-representation of the board."""
  39. print(f'''
  40. {board['7']}|{board['8']}|{board['9']} 7 8 9
  41. -+-+-
  42. {board['4']}|{board['5']}|{board['6']} 4 5 6
  43. -+-+-
  44. {board['1']}|{board['2']}|{board['3']} 1 2 3''')
  45.  
  46. def isWinner(board, mark):
  47. """Return True if mark is a winner on board."""
  48. bo, m = board, mark # Shorter names for "syntactic sugar".
  49. # Check for 3 marks across the 3 rows, 3 columns, and 2 diagonals.
  50. return ((bo['7'] == m and bo['8'] == m and bo['9'] == m) or
  51. (bo['4'] == m and bo['5'] == m and bo['6'] == m) or
  52. (bo['1'] == m and bo['2'] == m and bo['3'] == m) or
  53. (bo['7'] == m and bo['4'] == m and bo['1'] == m) or
  54. (bo['8'] == m and bo['5'] == m and bo['2'] == m) or
  55. (bo['9'] == m and bo['6'] == m and bo['3'] == m) or
  56. (bo['7'] == m and bo['5'] == m and bo['3'] == m) or
  57. (bo['9'] == m and bo['5'] == m and bo['1'] == m))
  58.  
  59. def getPlayerMove(board, player):
  60. """Let the player type in their move."""
  61. space = None
  62. while space not in ALL_SPACES or not board[space] == BLANK:
  63. print(f'What is {player}\'s move? (1-9)')
  64. space = input().upper()
  65. return space
  66.  
  67. def isBoardFull(board):
  68. """Return True if every space on the board has been taken."""
  69. for space in ALL_SPACES:
  70. if board[space] == BLANK:
  71. return False
  72. return True
  73.  
  74. def setSpace(board, space, mark):
  75. """Sets the space on the board to mark."""
  76. board[space] = mark
  77.  
  78. if __name__ == '__main__':
  79. main() # Call main() if this module is run, but not when imported.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement