【问题标题】:Checking for winner in Tic tac toe while loop在 Tic tac toe while 循环中检查获胜者
【发布时间】:2025-11-28 17:40:01
【问题描述】:

我正在编写一个基于文本的井字游戏面向对象的编程游戏,但我在宣布获胜者时遇到了问题

我写了这段代码来检查获胜者

    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

一开始我用这个

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

调用检查获胜者的函数,

但是即使在满足game_play().plyr()条件之后,它仍然会在终止循环之前进入game_play().com(),这是违反游戏规则的。

所以我修改了代码,这样每当玩家获胜时,循环就会终止

        while not board().check_result():
            game_play().plyr()
            if(board().check_result()==True):
                break
            game_play().com()

但我现在遇到的问题是它会打印两次“你不会”,这是我不想要的

完整代码如下


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

【问题讨论】:

    标签: python python-3.x oop while-loop break


    【解决方案1】:

    对你的逻辑类游戏__init__方法进行了一些更改并将输入提示更改为1-9,绘制条件也不起作用,再次播放时重置可用位置:

    完整代码

    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
    

    样本运行

    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
    

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      我会在所有函数和循环之外创建一个变量,并使其成为 1 = 玩家和 2 = 计算机,因此在获胜后,您会将数字添加到变量中并在游戏前进行检查以检查是否变量是 0、1 或 2。

      【讨论】:

        最近更新 更多