Skip to content

Instantly share code, notes, and snippets.

@ErrorBot1122
Created March 5, 2024 21:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ErrorBot1122/a41f4bcb4fcba040e36fec8b750b8160 to your computer and use it in GitHub Desktop.
Save ErrorBot1122/a41f4bcb4fcba040e36fec8b750b8160 to your computer and use it in GitHub Desktop.
Simple Python Tic-Tac-Toe Game

A Simple Python Tic-Tac-Toe Game

This is a simple Tic-Tac-Toe Game I made as a school assignment.

The programing took only 3 days (about 3 hours total) and I'm pretty proud about how readable it is!

The game includes all the criteria for a average Tic-Tac-Toe player, plus some overwrite pretection. (so players can't place a symbol on a tile with one already there)



ASSIGNMENT CRITERIA
# Implement the Tic Tac Toe game using a single list
Create this game again using lists and indexes. Updated rules are below.

 * Use a SINGLE LIST!
 * Allow users to keep playing (max 9 times).
 * Print the diagram before play begins:
     1 | 2 | 3  
    -----------
     4 | 5 | 6  
    -----------
     7 | 8 | 9

 * Use variables to decide whose turn it is. Greet the players as “X's” or “O's”.
 * User picks a location on the board by entering a number.
 * Depending on the location that the user chose, update the corresponding board position.
 * Print the updated board out.
 * You will not need to determine the winner at this point.

## Bonus
There are eight possible ways to win a Tic-Tac-Toe game.

 * After each turn in the game, check to see if the most recent player has won the game.
 * Print appropriate messages if the X's player wins, or if the O's player wins.
 * If no one has won the game after 9 moves, declare the game to be a draw.
from time import sleep
# Inizalize the empty board
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] # Normaly i would use a 2d list but a 1d list is eseiest for the criteria
winner = None
player1_turn = True
player1_symbol = "X"
player2_symbol = "O"
def printBoardState():
'''
A small function that just outputs the current board VISUALY for the player to see.
'''
# Use a templeate string so i dont have to use 1,000,000 +'s (f-string)
print(f"""CURRENT BOARD STATE:
{board[0]} | {board[1]} | {board[2]}
-----------
{board[3]} | {board[4]} | {board[5]}
-----------
{board[6]} | {board[7]} | {board[8]}
""")
def playBoard(symbol):
'''
Runs the steps to play allow to user to place a symbol on the game board!
'''
# Show the user the current board state so the user so they dont need to memories.
printBoardState()
# Ask the user where they want to place there symble and place it there
x_placement = int(input(f"Where you you want to place your {symbol}? (# = 1-9) "))
# Thats an invalid board placememt!
if (x_placement > 9) or (x_placement < 1):
print("\n\nYou can't place your symbol there!")
print("Here is the board mapping if you dont remember:")
print("""
1 | 2 | 3
-----------
4 | 5 | 6
-----------
7 | 8 | 9""")
sleep(2)
print() # New line B)
playBoard(symbol)
return
symbol_at_placement = board[x_placement - 1] # Find out if that space the user chose has ben taken
# Check if the space has already been taken
if symbol_at_placement == " ":
board[x_placement - 1] = symbol # Overide the empty space with the new symbol
else:
print(f"This position {x_placement} already contains an '{symbol_at_placement}'... Please try again!")
playBoard(symbol)
def cheakBoard():
'''
Checks the board to see who won or if it was a tie.
Updates the `winner` varable with the symbol who won, or the word 'TIE' accordingly.
'''
global winner # Stupid python with its stupid global >:(
# Check for all 3 Horisontal Line Wins
for row_starting_index in range(0, 9, 3): # BC the list is 1d, we have to go to skip 3 slots at a time for rows
# Get each slot in the row
row_slot_1 = board[row_starting_index]
row_slot_2 = board[row_starting_index + 1]
row_slot_3 = board[row_starting_index + 2]
# Check If all the slots have the same symbol (meaning someone wins)
if ((row_slot_1 == row_slot_2) and (row_slot_2 == row_slot_3)) and row_slot_1 != " ": # BUT make sure we did not match 3 empty slots!
winner = row_slot_1 # We can do this as the row slot has to contain the symbol who won.
return
# Check for all 3 Vertical Line Wins
for column_starting_index in range(3):
# Get each slot in the column
column_slot_1 = board[column_starting_index]
column_slot_2 = board[column_starting_index + 3]
column_slot_3 = board[column_starting_index + 6]
# Check If all the slots have the same symbol (meaning someone wins)
if ((column_slot_1 == column_slot_2) and (column_slot_2 == column_slot_3)) and column_slot_1 != " ": # BUT make sure we did not match 3 empty slots!
winner = column_slot_1 # We can do this as the column slot has to contain the symbol who won.
return
# Check for Both posible Diaganal Wins
top_left_slot = board[0]
top_right_slot = board[2]
middle_slot = board[4]
bottom_left_slot = board[6]
bottom_right_slot = board[8]
# If the middle slot is empty, then its imposible so eny diaganal 3 in a row!
if middle_slot == " ": return # This is called a GAURD (ooooooooooooooooooooooooooh)
# Check both possible diaganal wins at the same time!
if (((top_left_slot == middle_slot) and (middle_slot == bottom_right_slot)) or
((top_right_slot == middle_slot) and (middle_slot == bottom_left_slot))):
winner = middle_slot # We can do this as middle slot will always contain the wining symbol for diaganal wins...
# Tell the user where each number corrisponds to on the board
print("""
1 | 2 | 3
-----------
4 | 5 | 6
-----------
7 | 8 | 9
""")
# There are a max of 9 turns untill its a tie
for _ in range(9):
## PLAY THE BOARD ##
# Determine the current symbol that is playing by knowing who is playing...
current_symbol = player1_symbol if player1_turn else player2_symbol
# Allow the user to chose were to play and play it!
playBoard(current_symbol)
print() # New Line for next turn
## HANDLE WINNER LOGIC ##
# Check if enyone won...
cheakBoard()
# Was there a winner?
if winner:
# OMG SOMEONE ACCUALY WON!!!!!
printBoardState()
print(f"\n\n{current_symbol} WON THE GAME!!!!")
exit() # The game ended... Stop the program.
## GET READY FOR THE NEXT TURN ##
# Swap the player's turn to the next
player1_turn = not player1_turn
# The game ended without a winner :(
printBoardState()
print("THE GAME ENDED IN A TIE!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment