【问题标题】:Checking for a draw in Tic Tac Toe [Python]在井字游戏中检查平局 [Python]
【发布时间】:2015-10-23 18:32:44
【问题描述】:

我有一个 Python 程序,可以在两个人类玩家之间玩井字游戏。如果玩家 A 或玩家 B 获胜,则会宣布并终止程序。但是,如果程序以平局结束,它将继续请求用户输入。

我不知道如何检查平局。它必须在 while 循环内还是需要它自己的单独函数?

import sys

## Define and create tic tac toe gameboard
board = range(0,9)

def show_board():
    print board[0], '|', board[1], '|', board[2]
    print '---------'
    print board[3], '|', board[4], '|', board[5]
    print '---------'
    print board[6], '|', board[7], '|', board[8]

# Function used to check for winner
def line(char, box1, box2, box3):
    if board[box1] == char and board[box2] == char and board[box3] == char:
        return True

# Function used to automate process for checking every possible way to win
def all(char):
    # Horizontal check
    if line(char, 0, 1, 2):
        return True
    if line(char, 3, 4, 5):
        return True
    if line(char, 6, 7, 8):
        return True
    # Vertical check
    if line(char, 0, 3, 6):
        return True
    if line(char, 1, 4, 7):
        return True
    if line(char, 2, 5, 8):
        return True
    # Diagnol check
    if line(char, 0, 4, 8):
        return True
    if line(char, 2, 4, 6):
        return True

show_board()

# Initial while loop will ask for player A input and show the board as well
# check conditions to see whether or not player A wins. If player A wins,
# the program will terminate so it does not ask for player B input after.
while True:
    player_a = int(raw_input('Player A, please select a spot that is not taken \
(0-8): '))
    # Checks for empty spot and places an 'X' if it exists, otherwise
    # asks again.
    if board[player_a] != 'X' and board[player_a] != 'O':
        board[player_a] = 'X'
        show_board()
        # Check to see if Player A wins.
        if all('X') == True:
            print "Player A wins."
            sys.exit()
            break;

# While loop to ask for player B input and display the board as well as check
# the conditions as to whether or not player B wins. If player B wins, the
# program will terminate so it does not ask for player A input after.
        while True:
            player_b = int(raw_input('Player B, please select a spot that is \
not taken (0-8): '))
            # Checks for empty spot and places an 'O' if it exists, otherwise
            # asks again.
            if board[player_b] != 'O' and board[player_b] != 'X':
                board[player_b] = 'O'
                # Check to see if Player B wins.
                if all('O') == True:
                    show_board()
                    print "Player B wins."
                    sys.exit()
                    break;

                break;

    show_board()

【问题讨论】:

  • 请将代码添加到您的问题中,而不是链接到它。
  • 旁白:all 是函数名的错误选择,因为它也是内置函数的名称。

标签: python


【解决方案1】:

无需深入研究代码,我可以告诉您,9 回合后会发生平局,并且只有玩家 A 和 B 在最后一回合均未获得胜利时才会发生平局。对于您的简单程序,我要做的是创建一个名为 ELAPSED_TURNS 或类似名称的全局变量,每次玩家进入角色时都会递增,然后在检查两个玩家的获胜条件后,如果没有获胜,检查 ELAPSED_TURNS。如果等于 9,那么比赛一定是平局。

【讨论】:

  • 我想我在展示位置上有困难。我会在while循环之前初始化turns = 0。然后我会在最后一直将回合计数器增加1?但是,尝试这样做会破坏代码,它只会不断要求玩家 B 输入。
  • 在程序开始时初始化转数 = 0,如果 A 或 B 都没有赢得该回合,则增加转数,然后检查转数 9。
  • 您的 while 循环有点令人困惑,但如果您知道程序的结构,这应该很容易。
【解决方案2】:

这是执行您想要的功能的功能。

def is_tie():
    for position in board:
        if isinstance(position, int):
            return False
    print "The game is a tie."
    sys.exit()

在这样的两个while循环之后直接调用is_tie()...

while True:
    is_tie()    
    player_a = int(raw_input(...

while True:
    is_tie()    
    player_b = int(raw_input(...

如果这对您来说是一个学习练习,我建议您重构您的代码,以找到一种方法将您的所有逻辑块包装到函数中,并在不使用 sys.exit() 的情况下让一切顺利进行。这样做会增加可读性并更容易拼接新逻辑。

编辑您的评论:

您可以使用类似这样的 try / except 语句来创建整数测试函数...

def is_int(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False

来源:Python: Check if a string represents an int, Without using Try/Except?

您的is_tie() 函数将如下所示:

def is_tie():
    for position in board:
        if is_int(position):
            return False
    print "The game is a tie."
    sys.exit()

【讨论】:

  • isinstance 有“更简单”的版本吗?我还没有了解这个功能,所以我不想包含我不知道的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-22
  • 1970-01-01
  • 1970-01-01
  • 2019-11-24
  • 1970-01-01
相关资源
最近更新 更多