【问题标题】:Tic Tac Toe Winner Function is Buggy井字游戏获胜者功能是越野车
【发布时间】:2021-01-21 03:04:22
【问题描述】:

我是 Python 的初学者(有点)。在我的井字游戏中,我被困在获胜者(棋盘)功能上,因为每当我运行程序并在任何地方放置一个 X 时,它都会立即显示“Y O U W O N !”当我删除 make_computer_move(board) 下的代码以尝试调试我的获胜者(board) 函数时,从右上角到左下角的对角线不起作用,但从左上角到右下角的获胜者确定代码有效。下面是我的代码:

"""
    Author: Victor Xu
    
    Date: Jan 12, 2021

    Description: An implementation of the game Tic-Tac-Toe in Python,
    using a nested list, and everything else we've learned this quadmester!
"""

import random


def winner(board):
    """This function accepts the Tic-Tac-Toe board as a parameter.
    If there is no winner, the function will return the empty string "".
    If the user has won, it will return 'X', and if the computer has
    won it will return 'O'."""

    # Check rows for winner
    for row in range(3):
        if (board[row][0] == board[row][1] == board[row][2]) and \
                (board[row][0] != " "):
            return board[row][0]

    # COMPLETE THE REST OF THE FUNCTION CODE BELOW
    for col in range(3):
        if (board[0][col] == board[1][col] == board[2][col]) and \
                (board[0][col] != " "):
            return board[0][col]

    # Check diagonal (top-left to bottom-right) for winner
    if (board[0][0] == board[1][1] == board[2][2]) and \
            (board[0][0] != " "):
        return board[0][0]

    # Check diagonal (bottom-left to top-right) for winner
    if (board[0][2] == board[1][1] == board[2][0]) and \
            (board[0][0] != " "):
        return board[0][0]

    # No winner: return the empty string
    return ""


def display_board(board):
    """This function accepts the Tic-Tac-Toe board as a parameter.
    It will print the Tic-Tac-Toe board grid (using ASCII characters)
    and show the positions of any X's and O's.  It also displays
    the column and row numbers on top and beside the board to help
    the user figure out the coordinates of their next move.
    This function does not return anything."""

    print("   0   1   2")
    print("0: " + board[0][0] + " | " + board[0][1] + " | " + board[0][2])
    print("  ---+---+---")
    print("1: " + board[1][0] + " | " + board[1][1] + " | " + board[1][2])
    print("  ---+---+---")
    print("2: " + board[2][0] + " | " + board[2][1] + " | " + board[2][2])
    print()


def make_user_move(board):
    """This function accepts the Tic-Tac-Toe board as a parameter.
    It will ask the user for a row and column.  If the row and
    column are each within the range of 0 and 2, and that square
    is not already occupied, then it will place an 'X' in that square."""

    valid_move = False
    while not valid_move:
        row = int(input("What row would you like to move to (0-2):"))
        col = int(input("What col would you like to move to (0-2):"))
        if (0 <= row <= 2) and (0 <= col <= 2) and (board[row][col] == " "):
            board[row][col] = 'X'
            valid_move = True
        else:
            print("Sorry, invalid square. Please try again!\n")


def make_computer_move(board):
    """This function accepts the Tic-Tac-Toe board as a parameter.
    It will randomly pick row and column values between 0 and 2.
    If that square is not already occupied it will place an 'O'
    in that square.  Otherwise, another random row and column
    will be generated."""

    computer_valid_move = False
    while not computer_valid_move:
        row = random.randint(0, 2)
        col = random.randing(0, 2)
        if (0 <= row <= 2) and (0 <= col <= 2) and (board[row][col] == " "):
            board[row][col] = 'O'
            computer_valid_move = True


def main():
    """Our Main Game Loop:"""

    free_cells = 9
    users_turn = True
    ttt_board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]

    while not winner(ttt_board) and (free_cells > 0):
        display_board(ttt_board)
        if users_turn:
            make_user_move(ttt_board)
            users_turn = not users_turn
        else:
            make_computer_move(ttt_board)
            users_turn = not users_turn
        free_cells -= 1

    display_board(ttt_board)
    if (winner(ttt_board) == 'X'):
        print("Y O U   W O N !")
    elif (winner(ttt_board) == 'O'):
        print("I   W O N !")
    else:
        print("S T A L E M A T E !")
    print("\n*** GAME OVER ***\n")


# Start the game!
main()

TL;DR

请查看右上角到左下角的对角线获胜确定代码以及每当我按下 X 并显示“你赢了!”时的问题

【问题讨论】:

  • 通过传递性,你可以写a == b == c != d而不是a == b == c and a != d

标签: python


【解决方案1】:

您的从左下角到右上角的对角线检查是错误的。您正在检查正确的对角线元素是否彼此相等,但随后您检查了错误的角元素以查看它是否不是空格。应该是:

    # Check diagonal (bottom-left to top-right) for winner
    if (board[0][2] == board[1][1] == board[2][0]) and \
            (board[0][2] != " "):
        return board[0][2]

【讨论】:

  • 天哪,我以为我是正确的...非常感谢您向我解释这一点,我真的很感激!当冷却结束时,我会接受这个作为答案:) 再次感谢您!
  • board[0][2] == board[1][1] == board[2][0] != " " 可以避免这个错误。
【解决方案2】:

首先:我看到你有一个错字(“randing”,我猜它又是 randint 作为上一行? 第二:代码在这里运行良好,直到我将我的第一个 X 放置在所有崩溃的地方(AttributeError: 'module' object has no attribute 'randing' due to the randing error) 第三:在为你改错之后,我完成了游戏并战胜了机器(幸运的是,直到你/某人(呵呵,我可能曾经)在游戏中实现了人工智能)。

祝你好运 Python,它是一门非常有趣的语言,但当出现问题时很难。

问候

【讨论】:

  • 是的,在我纠正了我的获胜者(董事会)函数中的错误后,我看到了错字。大声笑!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多