Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

2/28/2021 The Classic Tic-Tac-Toe Game in Python 3 | by James Shah | Byte Tales | Medium

The Classic Tic-Tac-Toe Game in Python 3


James Shah Follow
Nov 14, 2019 · 3 min read

Hello There My Gorgeous Friends On The Internet!


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.

https://medium.com/byte-tales/the-classic-tic-tac-toe-game-in-python-3-1427c68b8874 1/10
2/28/2021 The Classic Tic-Tac-Toe Game in Python 3 | by James Shah | Byte Tales | Medium

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.

What we are going to do?


We are going to build a two-player tic-tac-toe game, which we can play in the command-
line. Initially, we’ll make an empty game board and then we’ll take inputs from the
players and we’ll check for the winning condition and if the whole board gets filled and
no one wins, we’ll declare the result as “Tie” and ask users if they want to restart the
game.

What will we use?


We will build this game using Python 3, so make sure you have it installed on your
laptop/computer and we are good to go.

What we’ll learn?


After building this game, we can get a pretty clear idea about dictionaries in python, how
to access dictionaries, how to iterate over dictionaries, for loop, if-else conditions and
functions in python.

How does the game work?


The board is numbered like the keyboard’s number pad. And thus, a player can make
their move in the game board by entering the number from the keyboard number pad.

https://medium.com/byte-tales/the-classic-tic-tac-toe-game-in-python-3-1427c68b8874 2/10
2/28/2021 The Classic Tic-Tac-Toe Game in Python 3 | by James Shah | Byte Tales | Medium

The board is numbered like the keyboard’s number pad.

Code Time💻
First, let’s see how we are going to use a dictionary to create our game board. A
dictionary is a primitive data type in python which stores data in “key: value” format.
and thus, we’ll create a dictionary of length 9 and each key will represent a block in the
board and its corresponding value will represent the move made by a player. and we’ll
create a function printBoard() which we can use every time we want to print the
updated board in the game.

1 theBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,
2 '4': ' ' , '5': ' ' , '6': ' ' ,
3 '1': ' ' , '2': ' ' , '3': ' ' }
4
5 def printBoard(board):
6 print(board['7'] + '|' + board['8'] + '|' + board['9'])
7 print('-+-+-')
8 print(board['4'] + '|' + board['5'] + '|' + board['6'])
9 print('-+-+-')
10 print(board['1'] + '|' + board['2'] + '|' + board['3'])

theBoard.py hosted with ❤ by GitHub view raw

Initially our game board will look like this:

| |
-+-+-
| |
-+-+-
| |

https://medium.com/byte-tales/the-classic-tic-tac-toe-game-in-python-3-1427c68b8874 3/10
2/28/2021 The Classic Tic-Tac-Toe Game in Python 3 | by James Shah | Byte Tales | Medium

Now, in the main function, we’ll first take the input from the player and check if the
input is a valid move or not. If the block that player requests to move to is valid, we’ll fill
that block else we’ll ask the user to choose another block.

1 def game():
2
3 turn = 'X'
4 count = 0
5
6 for i in range(10):
7 printBoard(theBoard)
8 print("It's your turn," + turn + ".Move to which place?")
9
10 move = input()
11
12 if theBoard[move] == ' ':
13 theBoard[move] = turn
14 count += 1
15 else:
16 print("That place is already filled.\nMove to which place?")
17 continue

user_input.py hosted with ❤ by GitHub view raw

Now, to check the winning condition, we’ll check a total of 8 conditions and whichever
player has made the last move, we’ll declare that player as a winner. And if no one wins,
we’ll declare ‘tie’

1 # Now we will check if player X or O has won,for every move after 5 moves.
2 if count >= 5:
3 if theBoard['7'] == theBoard['8'] == theBoard['9'] != ' ': # across the top
4 printBoard(theBoard)
5 print("\nGame Over.\n")
6 print(" **** " +turn + " won. ****")
7 break
8 elif theBoard['4'] == theBoard['5'] == theBoard['6'] != ' ': # across the middle
9 printBoard(theBoard)
10 print("\nGame Over.\n")
11 print(" **** " +turn + " won. ****")
12 break
13 elif theBoard['1'] == theBoard['2'] == theBoard['3'] != ' ': # across the bottom
14 printBoard(theBoard)
https://medium.com/byte-tales/the-classic-tic-tac-toe-game-in-python-3-1427c68b8874 4/10
2/28/2021 The Classic Tic-Tac-Toe Game in Python 3 | by James Shah | Byte Tales | Medium

15 print("\nGame Over.\n")
16 print(" **** " +turn + " won. ****")
17 break
18 elif theBoard['1'] == theBoard['4'] == theBoard['7'] != ' ': # down the left side
19 printBoard(theBoard)
20 print("\nGame Over.\n")
21 print(" **** " +turn + " won. ****")
22 break
23 elif theBoard['2'] == theBoard['5'] == theBoard['8'] != ' ': # down the middle
24 printBoard(theBoard)
25 print("\nGame Over.\n")
26 print(" **** " +turn + " won. ****")
27 break
28 elif theBoard['3'] == theBoard['6'] == theBoard['9'] != ' ': # down the right side
29 printBoard(theBoard)
30 print("\nGame Over.\n")
31 print(" **** " +turn + " won. ****")
32 break
33 elif theBoard['7'] == theBoard['5'] == theBoard['3'] != ' ': # diagonal
34 printBoard(theBoard)
35 print("\nGame Over.\n")
36 print(" **** " +turn + " won. ****")
37 break
38 elif theBoard['1'] == theBoard['5'] == theBoard['9'] != ' ': # diagonal
39 printBoard(theBoard)
40 print("\nGame Over.\n")
41 print(" **** " +turn + " won. ****")
42 break
43
44 # If neither X nor O wins and the board is full, we'll declare the result as 'tie'.
45 if count == 9:
46 print("\nGame Over.\n")
47 print("It's a Tie!!")
48
49 # we have to change the player after every move.
50 if turn =='X':
51 turn = 'O'
52 else:
53 turn = 'X'

game_functionality.py hosted with ❤ by GitHub view raw

And now, we’ll ask the players if they want to play again.

https://medium.com/byte-tales/the-classic-tic-tac-toe-game-in-python-3-1427c68b8874 5/10
2/28/2021 The Classic Tic-Tac-Toe Game in Python 3 | by James Shah | Byte Tales | Medium

1 board_keys = []
2
3 for key in theBoard:
4 board_keys.append(key)
5
6 restart = input("Do want to play Again?(y/n)")
7
8 if restart == "y" or restart == "Y":
9 for key in board_keys:
10 theBoard[key] = " "
11
12 game()

restart.py hosted with ❤ by GitHub view raw

And boom!! Now we have our game ready.😍😍

The Full Code:

1 #Implementation of Two Player Tic-Tac-Toe game in Python.


2
3 ''' We will make the board using dictionary
4 in which keys will be the location(i.e : top-left,mid-right,etc.)
5 and initialliy it's values will be empty space and then after every move
6 we will change the value according to player's choice of move. '''
7
8 theBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,
9 '4': ' ' , '5': ' ' , '6': ' ' ,
10 '1': ' ' , '2': ' ' , '3': ' ' }
11
12 board_keys = []
13
14 for key in theBoard:
15 board_keys.append(key)
16
17 ''' We will have to print the updated board after every move in the game and
18 thus we will make a function in which we'll define the printBoard function
19 so that we can easily print the board everytime by calling this function. '''
20
21 def printBoard(board):
22 print(board['7'] + '|' + board['8'] + '|' + board['9'])
23 print('-+-+-')
24 print(board['4'] + '|' + board['5'] + '|' + board['6'])
25 print('-+-+-')
https://medium.com/byte-tales/the-classic-tic-tac-toe-game-in-python-3-1427c68b8874 6/10
2/28/2021 The Classic Tic-Tac-Toe Game in Python 3 | by James Shah | Byte Tales | Medium

26 print(board['1'] + '|' + board['2'] + '|' + board['3'])


27
28 # Now we'll write the main function which has all the gameplay functionality.
29 def game():
30
31 turn = 'X'
32 count = 0
33
34
35 for i in range(10):
36 printBoard(theBoard)
37 print("It's your turn," + turn + ".Move to which place?")
38
39 move = input()
40
41 if theBoard[move] == ' ':
42 theBoard[move] = turn
43 count += 1
44 else:
45 print("That place is already filled.\nMove to which place?")
46 continue
47
48 # Now we will check if player X or O has won,for every move after 5 moves.
49 if count >= 5:
50 if theBoard['7'] == theBoard['8'] == theBoard['9'] != ' ': # across the top
51 printBoard(theBoard)
52 print("\nGame Over.\n")
53 print(" **** " +turn + " won. ****")
54 break
55 elif theBoard['4'] == theBoard['5'] == theBoard['6'] != ' ': # across the middle
56 printBoard(theBoard)
57 print("\nGame Over.\n")
58 print(" **** " +turn + " won. ****")
59 break
60 elif theBoard['1'] == theBoard['2'] == theBoard['3'] != ' ': # across the bottom
61 printBoard(theBoard)
62 print("\nGame Over.\n")
63 print(" **** " +turn + " won. ****")
64 break
65 elif theBoard['1'] == theBoard['4'] == theBoard['7'] != ' ': # down the left side
66 printBoard(theBoard)
67 print("\nGame Over.\n")
68 print(" **** " +turn + " won. ****")
69 break
70 lif th B d['2'] th B d['5'] th B d['8'] ! ' ' # d th iddl
https://medium.com/byte-tales/the-classic-tic-tac-toe-game-in-python-3-1427c68b8874 7/10
2/28/2021 The Classic Tic-Tac-Toe Game in Python 3 | by James Shah | Byte Tales | Medium
70 elif theBoard['2'] == theBoard['5'] == theBoard['8'] != ' ': # down the middle
71 printBoard(theBoard)
72 print("\nGame Over.\n")
73 print(" **** " +turn + " won. ****")
74 break
75 elif theBoard['3'] == theBoard['6'] == theBoard['9'] != ' ': # down the right side
76 printBoard(theBoard)
77 print("\nGame Over.\n")
78 print(" **** " +turn + " won. ****")
79 break
80 elif theBoard['7'] == theBoard['5'] == theBoard['3'] != ' ': # diagonal
81 printBoard(theBoard)
82 print("\nGame Over.\n")
83 print(" **** " +turn + " won. ****")
84 break
85 elif theBoard['1'] == theBoard['5'] == theBoard['9'] != ' ': # diagonal
86 printBoard(theBoard)
87 print("\nGame Over.\n")
88 print(" **** " +turn + " won. ****")
89 break
90
91 # If neither X nor O wins and the board is full, we'll declare the result as 'tie'.
92 if count == 9:
93 print("\nGame Over.\n")
94 print("It's a Tie!!")
95
96 # Now we have to change the player after every move.
97 if turn =='X':
98 turn = 'O'
99 else:
100 turn = 'X'
101
102 # Now we will ask if player wants to restart the game or not.
103 restart = input("Do want to play Again?(y/n)")
104 if restart == "y" or restart == "Y":
105 for key in board_keys:
106 theBoard[key] = " "
107
108 game()
109
110 if __name__ == "__main__":
111 game()

tictactoe.py hosted with ❤ by GitHub view raw

https://medium.com/byte-tales/the-classic-tic-tac-toe-game-in-python-3-1427c68b8874 8/10
2/28/2021 The Classic Tic-Tac-Toe Game in Python 3 | by James Shah | Byte Tales | Medium

Play Time:

| |
-+-+-
| |
-+-+-
| |
It's your turn,X.Move to which place?
7
X| |
-+-+-
| |
-+-+-
| |
It's your turn,O.Move to which place?
9
X| |O
-+-+-
| |
-+-+-
| |
It's your turn,X.Move to which place?
5
X| |O
-+-+-
|X|
-+-+-
| |
It's your turn,O.Move to which place?
3
X| |O
-+-+-
|X|
-+-+-
| |O
It's your turn,X.Move to which place?
6
X| |O
-+-+-
|X|X
-+-+-
| |O
It's your turn,O.Move to which place?
1
X| |O
-+-+-
|X|X
-+-+-
O| |O
It's your turn,X.Move to which place?
4
X| |O
https://medium.com/byte-tales/the-classic-tic-tac-toe-game-in-python-3-1427c68b8874 9/10
2/28/2021 The Classic Tic-Tac-Toe Game in Python 3 | by James Shah | Byte Tales | Medium

-+-+-
X|X|X
-+-+-
O| |O

Game Over.

**** X won. ****

Thanks For Scrolling, I hope you liked it. Hit me up with your views and suggestions in
the comment down below.🙌

Programming Python Games Technology James Shah

About Help Legal

Get the Medium app

https://medium.com/byte-tales/the-classic-tic-tac-toe-game-in-python-3-1427c68b8874 10/10

You might also like