当前位置: 首页 > 知识库问答 >
问题:

检查Tic tac toe while循环中的获胜者

姜景辉
2023-03-14

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

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

    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

共有2个答案

司徒寒
2023-03-14

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

叶德本
2023-03-14

对您的逻辑类游戏\uuuuu init\uuuuu方法进行了一些更改,并将输入提示更改为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

希望有帮助!

 类似资料:
  • 请原谅长标题。StackOverflow不会接受较短的。 我试图在科特林制作一个井字游戏。到目前为止,除了对角线检查之外,一切都运行得非常好。 基本上, 函数的作用是创建一个矩阵,其中包含井字棋棋盘中的所有容器,然后检查棋盘的行,列和对角线值是否相等。如果检测到获胜者,该函数会将文本设置为“您获胜”。行和列检查工作正常,但是如果我在对角线上有3个X-s,则没有任何反应。 代码对我来说似乎很好,所以

  • 问题内容: 在Java中的for循环中防止空值的最佳方法是什么? 这看起来很丑: 要么 可能没有其他办法。他们是否应该将它放在构造本身中,如果它为null,则不要运行循环? 问题答案: 您最好验证从哪里获得该列表。 空列表就是您所需要的,因为空列表不会失败。 如果您从其他地方获得此列表,并且不知道是否可以,则可以创建一个实用程序方法并像这样使用它: 当然是:

  • 问题内容: 我不明白如何在四连冠中找到获胜方式,请告诉我应该怎么想以及如何在四连冠中找到赢家。我应该如何使用for循环来找到他们。我应该如何使用方法寻找赢家? 问题答案: 在一个简短的Google之后,会弹出以下代码:https : //codereview.stackexchange.com/questions/100917/connect- four-game-in- java 或http:/

  • 我试图创建一个可以识别父子循环的函数<想象 对象A是对象B的父对象 对象B是对象C的父对象 创建一个可以防止父子循环的函数。该函数应该给出至少两个参数(ChilName、家长名),如果关系创建了一个循环,则会出错。在上面的例子中,如果我们通过(A、C)应该打印或传递字符串: “A是C的父级” 我知道如何创建这个函数(你可以用任何语言提供答案): 我的主要问题是如何在异常中提供正确的消息。(“A是C

  • 问题内容: 我的问题是关于在哪些Java检查的条件for循环时,有一个print语句的顺序做 在 该循环的“条件”。这似乎是不切实际的事情(我从未见过以任何实际方式使用它),尽管我对打印的内容缺乏理解,使我认为我可能不完全了解for循环的功能。在最近的一次考试中出现了以下问题: 输入n = 5时,以下方法将打印什么? 正确的答案是:0 1 2 3 4 5 在我看来,该循环应该打印-1,然后将i递增

  • 因此,我为DFS编写了以下代码: 现在,我读到,在一个无向图中,如果当DFS时,它再次返回到同一个顶点,有一个循环。所以我做的是这样,, 但是,我的检查周期函数返回true,即使他们没有周期。那是为什么呢?我的功能有问题吗?没有执行问题,否则我早就调试了,但他们似乎在我的逻辑中有问题。

  • 我想这一定是一个简单的修复,但我仍然熟悉编码,所以偶尔我会陷入一些愚蠢的事情(会赶上的,最终哈哈) (我已经实现了所有其他可能获胜的行和列。没有将它们粘贴在这里以使问题更短,但它们都遵循上面的逻辑) 当玩家放置标记时,我调用该函数,一旦满足一个获胜条件,我会打印消息: 但游戏不会中断(我猜会是,因为我在每个条件后都“Rest”)。我的IF里面会发生什么?就像我说的,猜测一定很简单,但现在卡住了。

  • 有人给了我一个井字游戏的代码。我制作了代码来检查垂直方向是否会赢,并尝试检查对角线。我能够检查主对角线,但似乎无法确定如何检查辅助对角线。我以为我拥有的代码会起作用,但事实并非如此。我的问题从第172行开始