Skip to content

Commit b84c068

Browse files
committed
Tic Tac Toe Game
1 parent aa89184 commit b84c068

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

Programs/P75_TicTacToe.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Author: OMKAR PATHAK
2+
3+
# A simple example of tic tac toe game
4+
5+
# For storing user choices
6+
choices = []
7+
8+
# For initializing the board with numbers
9+
for i in range(0, 9):
10+
choices.append(str(i))
11+
12+
firstPlayer = True
13+
winner = False
14+
iterations = 0 # To terminate the loop
15+
16+
# For drawing board on to the terminal
17+
def printBoard():
18+
print('\n=============')
19+
print('| ' + choices[0] + ' | ' + choices[1] + ' | ' + choices[2] + ' |')
20+
print('=============')
21+
print('| ' + choices[3] + ' | ' + choices[4] + ' | ' + choices[5] + ' |')
22+
print('=============')
23+
print('| ' + choices[6] + ' | ' + choices[7] + ' | ' + choices[8] + ' |')
24+
print('=============\n')
25+
26+
# Play the game while the winner is not decided or the game is drawn
27+
while not winner and iterations < 9:
28+
printBoard()
29+
30+
iterations += 1
31+
32+
if firstPlayer == True:
33+
print('Player 1: ', end = '')
34+
else:
35+
print('Player 2: ', end = '')
36+
37+
try:
38+
playerInput = int(input())
39+
except:
40+
print('Please enter a valid number from the board')
41+
continue
42+
43+
# Check if userInput already has 'X' or 'O'
44+
if choices[playerInput] == 'X' or choices[playerInput] == 'O':
45+
print('Illegal move, try again!')
46+
continue
47+
48+
if firstPlayer:
49+
choices[playerInput] = 'X'
50+
else:
51+
choices[playerInput] = 'O'
52+
53+
firstPlayer = not firstPlayer
54+
55+
# Winning conditions
56+
for index in range(0, 3):
57+
# For [0,1,2], [3,4,5], [6,7,8]
58+
if (choices[index * 3] == choices[((index * 3) + 1)] and choices[index * 3] == choices[((index * 3) + 2)]):
59+
winner = True
60+
printBoard()
61+
62+
# For [0,3,6], [1,4,7], [2,5,8]
63+
if(choices[index] == choices[index + 3] and choices[index + 3] == choices[index + 6]):
64+
winner = True
65+
printBoard()
66+
67+
if((choices[0] == choices[4] and choices[4] == choices[8]) or
68+
(choices[2] == choices[4] and choices[4] == choices[6])):
69+
winner = True
70+
printBoard()
71+
72+
if winner:
73+
print('Player ' + str(int(firstPlayer + 1)) + ' wins!')
74+
else:
75+
print('Game drawn')

0 commit comments

Comments
 (0)