DEV Community

James Shah
James Shah

Posted on

10

Tic Tac Toe Python The Classic TicTacToe Game in Python

So, the best and the most fun way to learn any programming language for me has always been by developing a fun project like a simple game or some project that I would use in my daily life.

So, when I started to learn Python, I started with this No Starch Press published book “Automate The Boring Stuff With Python” which is just awesome and If you are looking for a book to get started learning python, I would recommend you to go through this book. Its very beginner-friendly and it covers almost all the basic topics of python. So, while solving the exercises in this book, I came across this TicTacToe game implementation in python.

#Implementation of Two Player Tic-Tac-Toe game in Python.
''' We will make the board using dictionary
in which keys will be the location(i.e : top-left,mid-right,etc.)
and initialliy it's values will be empty space and then after every move
we will change the value according to player's choice of move. '''
theBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,
'4': ' ' , '5': ' ' , '6': ' ' ,
'1': ' ' , '2': ' ' , '3': ' ' }
board_keys = []
for key in theBoard:
board_keys.append(key)
''' We will have to print the updated board after every move in the game and
thus we will make a function in which we'll define the printBoard function
so that we can easily print the board everytime by calling this function. '''
def printBoard(board):
print(board['7'] + '|' + board['8'] + '|' + board['9'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
print(board['1'] + '|' + board['2'] + '|' + board['3'])
# Now we'll write the main function which has all the gameplay functionality.
def game():
turn = 'X'
count = 0
for i in range(10):
printBoard(theBoard)
print("It's your turn," + turn + ".Move to which place?")
move = input()
if theBoard[move] == ' ':
theBoard[move] = turn
count += 1
else:
print("That place is already filled.\nMove to which place?")
continue
# Now we will check if player X or O has won,for every move after 5 moves.
if count >= 5:
if theBoard['7'] == theBoard['8'] == theBoard['9'] != ' ': # across the top
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['4'] == theBoard['5'] == theBoard['6'] != ' ': # across the middle
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['1'] == theBoard['2'] == theBoard['3'] != ' ': # across the bottom
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['1'] == theBoard['4'] == theBoard['7'] != ' ': # down the left side
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['2'] == theBoard['5'] == theBoard['8'] != ' ': # down the middle
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['3'] == theBoard['6'] == theBoard['9'] != ' ': # down the right side
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['7'] == theBoard['5'] == theBoard['3'] != ' ': # diagonal
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['1'] == theBoard['5'] == theBoard['9'] != ' ': # diagonal
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
# If neither X nor O wins and the board is full, we'll declare the result as 'tie'.
if count == 9:
print("\nGame Over.\n")
print("It's a Tie!!")
# Now we have to change the player after every move.
if turn =='X':
turn = 'O'
else:
turn = 'X'
# Now we will ask if player wants to restart the game or not.
restart = input("Do want to play Again?(y/n)")
if restart == "y" or restart == "Y":
for key in board_keys:
theBoard[key] = " "
game()
if __name__ == "__main__":
game()
view raw tictactoe.py hosted with ❤ by GitHub

And Now Play Time:

TicTacToe

Checkout the Full code explanation here.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (6)

Collapse
 
highcenburg profile image
Vicente G. Reyes

Could you please add more context to this post?

Collapse
 
jamesshah profile image
James Shah

Sure. Can you elaborate particularly what should i add/change?

Collapse
 
highcenburg profile image
Vicente G. Reyes

Sure. As a community mod, I find this purely promotional.

You can add at least 1 or 2 snippets of code with an explanation of what they do.

Cheers

Thread Thread
 
jamesshah profile image
James Shah

Okay. Changed it. Thanks for the suggestion.

Collapse
 
jarvissilva profile image
Jarvis Silva

Great python program here are some more python game programs for you with code.

Collapse
 
anik2000s profile image
anik2000s

if count == 9:
print("\nGame Over.\n")

print("It's a Tie!!")

I think after this line a break is missing.

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series