简体   繁体   中英

Checking for winner in Tic tac toe while loop

I am writing a text-based tic-tac toe Object oriented programming game but the I'm having problem with declaring the winner

I wrote this code to check for the winner

    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

Initially i use this

        while not board().check_result():
            game_play().plyr()
            game_play().com()

to call the the funtion that check for the winner,

But even after the game_play().plyr() condition has been met, it still goes to game_play().com() before terminating the loop which is against the rules of the game.

So i modify the code as thus so that whenever the player win, the loop terminates

        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 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

Did some changes to your logic class game __init__ method and changed input prompt to 1-9, Draw condition was also not working, reset available positions when played again:

FULL CODE

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 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
        x=0
        for pos in board.sample:
            if pos == 'X' or pos == '0':
                x = x + 1
        if 9==x : # for pos in board.sample if pos=='X' or pos=='0' :x=x+1 :
            print('Draw')
            return True
        return False


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 1 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()
        board.sample = ['-', '-', '-', '-', '-', '-', '-', '-', '-']
        game_play.choose=[1,2,3,4,5,6,7,8,9]

        while True:
            game_play().plyr()
            if(board().check_result()==True):
                board().show()
                break
            game_play().com()
            if (board().check_result() == True):
                board().show()
                break
            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

Sample Run

Welcome that's the board layout
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
Input between 1 and 9: 1
The computer play  8

X   |   -   |   -
-   |   -   |   -
-   |   0   |   -
Input between 1 and 9: 2
The computer play  6

X   |   X   |   -
-   |   -   |   0
-   |   0   |   -
Input between 1 and 9: 4
The computer play  3

X   |   X   |   0
X   |   -   |   0
-   |   0   |   -
Input between 1 and 9: 9
The computer play  7

X   |   X   |   0
X   |   -   |   0
0   |   0   |   X
Input between 1 and 9: 5
You Won

X   |   X   |   0
X   |   X   |   0
0   |   0   |   X
Play Again [y/n] :y
Welcome that's the board layout
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
Input between 1 and 9: 9
The computer play  6

-   |   -   |   -
-   |   -   |   0
-   |   -   |   X
Input between 1 and 9: 3
The computer play  2

-   |   0   |   X
-   |   -   |   0
-   |   -   |   X
Input between 1 and 9: 1
The computer play  7

X   |   0   |   X
-   |   -   |   0
0   |   -   |   X
Input between 1 and 9: 8
The computer play  5

X   |   0   |   X
-   |   0   |   0
0   |   X   |   X
Input between 1 and 9: 4
Draw

X   |   0   |   X
X   |   0   |   0
0   |   X   |   X
Play Again [y/n] :n

Hope it helps !

i would have made a variable outside of all the functions and loops and make it so that 1 = player and 2 = computer, so after winning you would add the number to the variable and make a check before the game that checks if the variable is 0, 1 or 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM