└── tictactoe.py /tictactoe.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | x=['#',1,2,3,4,5,6,7,8,9] 4 | 5 | def chooseplayer(player1,player2): 6 | import random 7 | global p1,p2 8 | p1,p2="","" 9 | a=random.randint(0,1) 10 | if a==0: 11 | while True: 12 | p1=input(f"{player1}, choose(X/O): ") 13 | p1=p1.upper() 14 | if p1=='X' or p1=='O': 15 | break 16 | else: 17 | print('Choose only X or O') 18 | continue 19 | else: 20 | while True: 21 | p2=input(f"{player2}, choose(X/O): ") 22 | p2=p2.upper() 23 | if p2=='X' or p2=='O': 24 | break 25 | else: 26 | print('Choose only X or O') 27 | continue 28 | if p1!="": 29 | if p1=='X': 30 | p2='O' 31 | else: 32 | p2='X' 33 | else: 34 | if p2=='X': 35 | p1='O' 36 | else: 37 | p1='X' 38 | 39 | def displayboard(board,player1,player2): 40 | os.system('cls') 41 | print(f'{player1} is {p1}') 42 | print(f'{player2} is {p2}') 43 | print(f" {board[1]} | {board[2]} | {board[3]} ") 44 | print('-----|-----|-----') 45 | print(f" {board[4]} | {board[5]} | {board[6]} ") 46 | print('-----|-----|-----') 47 | print(f" {board[7]} | {board[8]} | {board[9]} ") 48 | 49 | def result(x): 50 | if x[1]==x[2]==x[3] or x[1]==x[5]==x[9] or x[1]==x[4]==x[7]: #x[1] is common 51 | print(f'{x[1]} has won') 52 | return 1 53 | elif x[3]==x[5]==x[7] or x[3]==x[6]==x[9]: #x[3] is common 54 | print(f'{x[3]} has won') 55 | return 1 56 | elif x[4]==x[5]==x[6] or x[2]==x[5]==x[8]: #x[5] is common 57 | print(f'{x[5]} has won') 58 | return 1 59 | elif x[7]==x[8]==x[9]: #used x[7] 60 | print(f'{x[7]} has won') 61 | return 1 62 | 63 | 64 | player1=input('enter PLAYER 1 name:') 65 | player1=player1.upper() 66 | player2=input('enter PLAYER 2 name:') 67 | player2=player2.upper() 68 | chooseplayer(player1,player2) 69 | 70 | displayboard(x,player1,player2) 71 | i=1 72 | for i in range(1,10): 73 | if i%2!=0: 74 | while True: 75 | y=int(input(f'{player1}, Select the location at which you want to put your symbol:')) 76 | if x[y]=='X' or x[y]=='O': 77 | print('ALREADY CHOSEN') 78 | continue 79 | else: 80 | x[y]=p1 81 | break 82 | displayboard(x,player1,player2) 83 | a=result(x) 84 | if a==1: 85 | break 86 | 87 | elif i==9: 88 | while True: 89 | y=int(input(f'{player2}, Select the location at which you want to put your symbol:')) 90 | if x[y]=='X' or x[y]=='O': 91 | print('ALREADY CHOSEN') 92 | continue 93 | else: 94 | x[y]=p2 95 | break 96 | displayboard(x,player1,player2) 97 | a=result(x) 98 | if a==1: 99 | break 100 | else: 101 | print("It's a draw") 102 | 103 | else: 104 | while True: 105 | y=int(input(f'{player2}, Select the location at which you want to put your symbol:')) 106 | if x[y]=='X' or x[y]=='O': 107 | print('ALREADY CHOSEN') 108 | continue 109 | else: 110 | x[y]=p2 111 | break 112 | displayboard(x,player1,player2) 113 | a=result(x) 114 | if a==1: 115 | break 116 | 117 | i+=1 118 | --------------------------------------------------------------------------------