Checking for winner in Tic tac toe while loop | Sololearn: Learn to code for FREE!

+1

Checking for winner in Tic tac toe while loop

I am writing a text-based tic-tac toe Object oriented programming game but the problem I'm having problem with declaring the winner It print 'You Win' Twice ``` while not board().check_result(): game_play().plyr() if(board().check_result()==True): break game_play().com() ``` But the problem I'm having now is it prints 'You won' twice which I don't want The full code below ``` from random import choice class board: sample=['-','-','-','-','-','-','-','-','-'] win_comb=[ (0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6) ] def board_layout(self): print("Welcome that's the board layout") print(1,'|',2,'|',3) print(4,'|',5,'|',6) print(7,'|',8,'|',9) def show(self): print() print(board.sample[0],' | ',board.sample[1],' | ',board.sample[2]) print(board.sample[3],' | ',board.sample[4],' | ',board.sample[5]) print(board.sample[6],' | ',board.sample[7],' | ',board.sample[8]) def check_result(self): for a,b,c in

6/7/2020 11:25:43 AM

maleeqB

1 Answer

New Answer

0

The remaining part of the code ``` def check_result(self): for a,b,c in self.win_comb: if(board.sample[a]==board.sample[b]==board.sample[c]=='X'): print('You Won') return True elif(board.sample[a]==board.sample[b]==board.sample[c]=='0'): print('You Lost') return True if 9==(sum(pos=='X' or pos=='0') for pos in board.sample): print('Draw') return True class game_play: choose=[1,2,3,4,5,6,7,8,9] def __init__(self): pass def inp(self): while True: try: self.x=int(input("Input between 0 and 9: ")) if self.x in game_play.choose: game_play.choose.remove(self.x) return self.x-1 else: print('pos unavailable') continue except ValueError: print ('invalid char') continue def plyr(self): board.sample[self.inp()]='X' def com(self): try: self.choice=choice(self.choose) board.sample[self.choice-1]='0' self.choose. remove(self.choice) print('The computer play ', self.choice) except IndexError: print() class game: def __init__(self): board().board_layout() while not board().check_result(): game_play().plyr() if(board().check_result()==True): break game_play().com() board().show() else: board.sample=['-','-','-','-','-','-','-','-','-'] game_play.choose=[1,2,3,4,5,6,7,8,9] while True: game() if input('Play Again [y/n] :') != 'y': break ```