Advertisement
asweigart

Tic Tac Toe 2-player

Aug 18th, 2022
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. # This constant contains all the space keys for a tic tac toe board:
  2. ALL_SPACES = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
  3.  
  4. def printBoard(board):
  5. print(' ' + board['1'] + '|' + board['2'] + '|' + board['3'] + ' 1 2 3')
  6. print(' -+-+-')
  7. print(' ' + board['4'] + '|' + board['5'] + '|' + board['6'] + ' 4 5 6')
  8. print(' -+-+-')
  9. print(' ' + board['7'] + '|' + board['8'] + '|' + board['9'] + ' 7 8 9')
  10.  
  11.  
  12. def getNewBoard():
  13. return {'1': ' ', '2': ' ', '3': ' ', '4': ' ',
  14. '5': ' ', '6': ' ', '7': ' ', '8': ' ', '9': ' '}
  15.  
  16.  
  17. def getPlayerMove(board, mark):
  18. while True:
  19. print('What is ' + mark + "'s move? (1-9)")
  20. move = input()
  21. if move in ALL_SPACES:
  22. if board[move] == ' ':
  23. return move
  24.  
  25.  
  26. def boardIsFull(board):
  27. for space in ALL_SPACES:
  28. if board[space] == ' ':
  29. return False
  30. return True
  31.  
  32.  
  33. def isWinner(board, mark):
  34. # Check the horizontal rows:
  35. if board['1'] == board['2'] == board['3'] == mark:
  36. return True
  37. if board['4'] == board['5'] == board['6'] == mark:
  38. return True
  39. if board['7'] == board['8'] == board['9'] == mark:
  40. return True
  41. # Check the vertical columns:
  42. if board['1'] == board['4'] == board['7'] == mark:
  43. return True
  44. if board['2'] == board['5'] == board['8'] == mark:
  45. return True
  46. if board['3'] == board['6'] == board['9'] == mark:
  47. return True
  48. # Check the diagonals:
  49. if board['1'] == board['5'] == board['9'] == mark:
  50. return True
  51. if board['3'] == board['5'] == board['7'] == mark:
  52. return True
  53. return False
  54.  
  55.  
  56.  
  57. print('Welcome to Tic Tac Toe!')
  58. theBoard = getNewBoard()
  59. turn = 'X'
  60.  
  61. printBoard(theBoard)
  62.  
  63. # Main game loop that asks for a player's move:
  64. while True:
  65. # Get the player's move:
  66. playerMove = getPlayerMove(theBoard, turn)
  67.  
  68. # Update the dictionary that represents the board with this move:
  69. theBoard[playerMove] = turn
  70.  
  71. # Display the updated board on the screen:
  72. printBoard(theBoard)
  73.  
  74. # Detect if the player has three in a row and won:
  75. if isWinner(theBoard, turn):
  76. print(turn + ' is the winner!')
  77. break
  78.  
  79. # Detect if the board is full, and the game is a tie:
  80. if boardIsFull(theBoard):
  81. print('The game is a tie!')
  82. break
  83.  
  84. # Change whose turn it is.
  85. if turn == 'X':
  86. turn = 'O'
  87. else:
  88. turn = 'X'
  89.  
  90. # End of program:
  91. print('Thanks for playing!')
  92.  
  93.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement