Professional Documents
Culture Documents
Project -1
Tic-Tac-Toe in Python
Two player Version
import os
import sys
game=[" "," "," ", " ", " "," "," ", " "," "]
def print_game():
os.system('cls')
print("__|__|__")
print("__|__|__")
print(" | | ")
def begin():
n=2
tr=int(input())
if tr==1:
player1='X'
player2='O'
else:
player1='O'
player2='X'
while True:
player(player1)
n=check_result(player1,player2)
if n==1:
sys.exit()
player(player2)
n=check_result(player1,player2)
if n==1:
sys.exit()
def player(p):
t=int(input())
player(p)
else:
game[t-1]=p
print_game()
def check_result(p1,p2):
value=6
for i in range(8):
if game[i]==" ":
game[i]=6
solution1=list(set((game[0],game[4],game[8])))
solution2=list(set((game[0],game[3],game[6])))
solution3=list(set((game[1],game[4],game[7])))
solution4=list(set((game[3],game[4],game[5])))
solution5=list(set((game[2],game[5],game[8])))
solution6=list(set((game[2],game[4],game[6])))
solution7=list(set((game[6],game[7],game[8])))
solution8=list(set((game[0],game[1],game[2])))
result=[solution1,solution2,solution3,solution4,solution5,solution6,solution7,solution8]
for i in range(8):
if result[i][0]==p1:
print("Player 1 wins")
else:
print("Player 2 wins")
value=5
for i in range(8):
if game[i]==6:
game[i]=" "
if value == 5:
return 1
else:
return 2
print("1 |2 |3")
print("__|__|__")
print("4 |5 |6")
print("__|__|__")
print("7 |8 |9")
begin()
import os
import sys
import random
game=[" "," "," ", " ", " "," "," ", " "," "]
movecount = 0
def print_game():
os.system('cls')
print("__|__|__")
print("__|__|__")
print(" | | ")
def begin():
n=2
tr=int(input())
if tr==1:
player1='X'
player2='O'
else:
player1='O'
player2='X'
while True:
player(player1)
n=check_result(player1,player2)
if n==1:
sys.exit()
player_computer(player1,player2)
n=check_result(player1,player2)
if n==1:
sys.exit()
def player(p):
t=int(input())
player(p)
else:
game[t-1]=p
print_game()
def player_computer(p1,p2):
t=random.randint(1,9)
while True:
t=random.randint(1,9)
else:
break
game[t-1]=p2
print_game()
def check_result(p1,p2):
for i in range(8):
if game[i]==" ":
game[i]=6
solution1=list(set((game[0],game[4],game[8])))
solution2=list(set((game[0],game[3],game[6])))
solution3=list(set((game[1],game[4],game[7])))
solution4=list(set((game[3],game[4],game[5])))
solution5=list(set((game[2],game[5],game[8])))
solution6=list(set((game[2],game[4],game[6])))
solution7=list(set((game[6],game[7],game[8])))
solution8=list(set((game[0],game[1],game[2])))
result=[solution1,solution2,solution3,solution4,solution5,solution6,solution7,solution8]
for i in range(8):
if result[i][0]==p1:
print("Player 1 wins")
sys.exit
else:
print("Player 2 wins")
sys.exit
value=5
for i in range(8):
if game[i]==6:
game[i]=" "
if value == 5:
return 1
else:
return 2
print("1 |2 |3")
print("__|__|__")
print("4 |5 |6")
print("__|__|__")
print("7 |8 |9")
begin()