Skip to content

Instantly share code, notes, and snippets.

@Frenzycore
Created December 14, 2025 17:35
Show Gist options
  • Select an option

  • Save Frenzycore/61deb4a96ab9815d3ec8a5b7c823fe1b to your computer and use it in GitHub Desktop.

Select an option

Save Frenzycore/61deb4a96ab9815d3ec8a5b7c823fe1b to your computer and use it in GitHub Desktop.
# This constant contains all the space keys for a tic tac toe board:
ALL_SPACES = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
def printBoard(board):
print(' ' + board['1'] + '|' + board['2'] + '|' + board['3'] + ' 1 2 3')
print(' -+-+-')
print(' ' + board['4'] + '|' + board['5'] + '|' + board['6'] + ' 4 5 6')
print(' -+-+-')
print(' ' + board['7'] + '|' + board['8'] + '|' + board['9'] + ' 7 8 9')
def getNewBoard():
return {'1': ' ', '2': ' ', '3': ' ', '4': ' ',
'5': ' ', '6': ' ', '7': ' ', '8': ' ', '9': ' '}
def getPlayerMove(board, mark):
while True:
print('What is ' + mark + "'s move? (1-9)")
move = input()
if move in ALL_SPACES:
if board[move] == ' ':
return move
def boardIsFull(board):
for space in ALL_SPACES:
if board[space] == ' ':
return False
return True
def isWinner(board, mark):
# Check the horizontal rows:
if board['1'] == board['2'] == board['3'] == mark:
return True
if board['4'] == board['5'] == board['6'] == mark:
return True
if board['7'] == board['8'] == board['9'] == mark:
return True
# Check the vertical columns:
if board['1'] == board['4'] == board['7'] == mark:
return True
if board['2'] == board['5'] == board['8'] == mark:
return True
if board['3'] == board['6'] == board['9'] == mark:
return True
# Check the diagonals:
if board['1'] == board['5'] == board['9'] == mark:
return True
if board['3'] == board['5'] == board['7'] == mark:
return True
return False
print('Welcome to Tic Tac Toe!')
theBoard = getNewBoard()
turn = 'X'
printBoard(theBoard)
# Main game loop that asks for a player's move:
while True:
# Get the player's move:
playerMove = getPlayerMove(theBoard, turn)
# Update the dictionary that represents the board with this move:
theBoard[playerMove] = turn
# Display the updated board on the screen:
printBoard(theBoard)
# Detect if the player has three in a row and won:
if isWinner(theBoard, turn):
print(turn + ' is the winner!')
break
# Detect if the board is full, and the game is a tie:
if boardIsFull(theBoard):
print('The game is a tie!')
break
# Change whose turn it is.
if turn == 'X':
turn = 'O'
else:
turn = 'X'
# End of program:
print('Thanks for playing!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment