Python 井字游戏

2024-02-27

我不确定所有代码是否都是必要的,所以我将发布它:

# Tic-Tac-Toe
# Plays the game of tic-tac-toe against a human opponent

# global constants
X = "X"
O = "O"
EMPTY = " "
TIE = "TIE"
NUM_SQUARES = 9


def display_instruct():
    """Display game instructions."""  
    print(
    """
    Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe.  
    This will be a showdown between your human brain and my silicon processor.  

    You will make your move known by entering a number, 0 - 8.  The number 
    will correspond to the board position as illustrated:

                    0 | 1 | 2
                    ---------
                    3 | 4 | 5
                    ---------
                    6 | 7 | 8

    Prepare yourself, human.  The ultimate battle is about to begin. \n
    """
    )


def ask_yes_no(question):
    """Ask a yes or no question."""
    response = None
    while response not in ("y", "n"):
        response = input(question).lower()
    return response


def ask_number(question, low, high):
    """Ask for a number within a range."""
    response = None
    while response not in range(low, high):
        response = int(input(question))
    return response


def pieces():
    """Determine if player or computer goes first."""
    go_first = ask_yes_no("Do you require the first move? (y/n): ")
    if go_first == "y":
        print("\nThen take the first move.  You will need it.")
        human = X
        computer = O
    else:
        print("\nYour bravery will be your undoing... I will go first.")
        computer = X
        human = O
    return computer, human


def new_board():
    """Create new game board."""
    board = []
    for square in range(NUM_SQUARES):
        board.append(EMPTY)
    return board



def display_board(board):
    """Display game board on screen."""
    print("\n\t", board[0], "|", board[1], "|", board[2])
    print("\t","---------")
    print("\t",board[3], "|", board[4], "|", board[5])
    print("\t","---------")
    print("\t",board[6], "|", board[7], "|", board[8])

def legal_moves(board):
    """Create list of legal moves."""
    moves = []
    for square in range(NUM_SQUARES):
        if board[square] == EMPTY:
            moves.append(square)
    return moves


def winner(board):
    """Determine the game winner."""
    WAYS_TO_WIN = ((0, 1, 2),
                   (3, 4, 5),
                   (6, 7, 8),
                   (0, 3, 6),
                   (1, 4, 7),
                   (2, 5, 8),
                   (0, 4, 8),
                   (2, 4, 6))

    for row in WAYS_TO_WIN:
        if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
            winner = board[row[0]]
            return winner

    if EMPTY not in board:
        return TIE

    return None


def human_move(board, human):
    """Get human move."""  
    legal = legal_moves(board)
    move = None
    while move not in legal:
        move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES)
        if move not in legal:
            print("\nThat square is already occupied, foolish human.  Choose another.\n")
    print("Fine...")
    return move


def computer_move(board, computer, human):
    """Make computer move."""
    # make a copy to work with since function will be changing list
    board = board[:]
    # the best positions to have, in order
    BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7)

    print("I shall take square number,", end="")

    # if computer can win, take that move
    for move in legal_moves(board):
        board[move] = computer
        if winner(board) == computer:
            print(move)
            return move
        # done checking this move, undo it
        board[move] = EMPTY

    # if human can win, block that move
    for move in legal_moves(board):
        board[move] = human
        if winner(board) == human:
            print(move)
            return move
        # done checkin this move, undo it
        board[move] = EMPTY

    # since no one can win on next move, pick best open square
    for move in BEST_MOVES:
        if move in legal_moves(board):
            print(move)
            return move


def next_turn(turn):
    """Switch turns."""
    if turn == X:
        return O
    else:
        return X


def congrat_winner(the_winner, computer, human):
    """Congratulate the winner."""
    if the_winner != TIE:
        print(the_winner, "won!\n")
    else:
        print("It's a tie!\n")

    if the_winner == computer:
        print("As I predicted, human, I am triumphant once more.  \n" \
              "Proof that computers are superior to humans in all regards.")

    elif the_winner == human:
        print("No, no!  It cannot be!  Somehow you tricked me, human. \n" \
              "But never again!  I, the computer, so swear it!")

    elif the_winner == TIE:
        print("You were most lucky, human, and somehow managed to tie me.  \n" \
              "Celebrate today... for this is the best you will ever achieve.")


def main():
    display_instruct()
    computer, human = pieces()
    turn = X
    board = new_board()
    display_board(board)

    while not winner(board):
        if turn == human:
            move = human_move(board, human)
            board[move] = human
        else:
            move = computer_move(board, computer, human)
            board[move] = computer
        display_board(board)
        turn = next_turn(turn)

    the_winner = winner(board)
    congrat_winner(the_winner, computer, human)


# start the program
main()
input("\n\nPress the enter key to quit.")

这是我正在阅读的一本书中的一个例子,我没有完全理解,我认为理解所有内容直到:

for row in WAYS_TO_WIN:
            if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
                winner = board[row[0]]
                return winner

有人可以解释一下这个函数的作用吗?更具体地说,条件是什么if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:正在测试?


它只是检查当前的棋盘,看看是否有任何获胜的单元格组合(如行数组中列出的)具有(a)相同的值并且(b)该值不为空。

注意:在 Python 中,如果 a == b == c != d,则检查 a ==b AND b == c AND c != d

因此,如果单元格 0、1 和 2 都有 X,那么在第一次通过循环时,它将从获胜例程返回 X。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 井字游戏 的相关文章

随机推荐

  • 使用 ngrok 进行隧道传输时如何获取请求的真实客户端 IP

    如何确保客户端IP地址被ngrok转发 由于 ngrok 我的测试代码一直坚持所有请求都来自 127 0 0 1 但我想记录实际的客户端 IP 负载均衡器通常在 X Forwarded For 或 x real ip 中设置标头 但我不确定
  • ICS 上的 TimePicker NullPointerException

    好吧 所以我刚刚切换了我的TimePickerDialog to a TimePicker由于客户需求 小部件在我正在处理的活动中直接可见 问题是当我按所述上的任何箭头时TimePicker 我得到一个 NullPointerExcepti
  • 从android中的通知栏启动应用程序

    我有一个应用程序 我想在我的应用程序运行时向通知栏显示我的应用程序图标 并且我还希望用户何时单击通知栏中存在的我的应用程序图标 我的应用程序将打开 这个怎么做 请帮忙 已接受的答案已被弃用 这是显示对话框的方法 来自谷歌文档 http de
  • 奇怪的空合并运算符自定义隐式转换行为

    注意 这似乎已修复Roslyn https github com dotnet roslyn 这个问题是在我写答案的时候出现的this one https stackoverflow com questions 6238074 它讨论了关联
  • Spring Boot 2 NoSuchMethodException:org.springframework.mobile.device.Device.()

    最近我尝试将 Spring Boot 应用程序版本从 1 5 10 RELEASE 更新到 2 0 0 RELEASE 项目环境 JDK版本1 8 Gradle 中的 jcenter 存储库 IDE Spring工具套件 STS 版本 3
  • Ember CLI - 在路线中使用 moment.js 时出错

    我已将 moment js 导入到我的项目中 它似乎在我的控制器中工作得很好 但由于某种原因它在我的路线中不起作用 控制器 controllers users js import Ember from ember export defaul
  • 如何在 numpy 中构造向量所有可能差异的矩阵

    我有一个一维数组 可以说 import numpy as np inp vec np array 1 2 3 现在 我想构造一个形式的矩阵 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 当然可以用for循环来完成
  • 使用 Emscripten 导出所有函数

    我想通过 JavaScript 以简单的方式使用 C 源代码 仅使用免费 自由软件 所以 Emscripten 似乎是一个不错的选择 https kripken github io emscripten site docs porting
  • 正则表达式提取具有匹配单词的整个句子

    我想在全文中提取带有 flung 一词的句子 例如 在下面的文本中 我想提取句子 It was just as if a hand had紧紧抓住它们并将它们扔到一边 使用正则表达式 我尝试用这个 flung
  • java中是否可以用三元运算符添加0?

    嗨 我已经尝试了从三元运算符 if else 语句并将 int 解析为字符串的所有内容 我正在制作一个读取 4 01 4 02 的时钟 但它输出 4 1 这是我的java代码 可以添加0吗 或者我需要别的东西 package bank im
  • Xcode 8 模拟器崩溃

    我最近下载了 Xcode 8 beta 当我尝试打开模拟器时 它卡在黑色的 Apple 屏幕上 并且收到 SpringBoard 的崩溃消息 有任何想法吗 如果我遗漏了任何内容 我很乐意进行编辑 提前致谢 这是发行说明中提到的已知问题 与下
  • Android 8.1 屏幕方向问题:翻转为横向屏幕

    除了用于播放始终为横向的视频的活动外 我的所有活动都处于纵向模式 我发现在 Android 8 1 上 每次打开视频 Activity 并关闭它时 上一个 Activity 都会转为横向 即使它在清单上设置为 纵向 也是如此 有时先转到肖像
  • 在 jodaTime 中获取主格月份名称

    我需要根据不同的数字获取月份名称Locales 为此 我创建了一个DateTime or YearMonth 没关系 对象并获取它的monthOfYear财产 YearMonth md new YearMonth 1992 month Sy
  • android中debug.keystore有什么用?

    我有一个小小的澄清 我有以下问题 1 每次正常构建工程时是否使用debug keystore生成apk 2 我已经解压生成的apk文件 我发现 META INF 文件夹中提供了证书 这些证书是用debug keystore生成的 用于识别系
  • C# 中重载方法的 MethodInfo 调用

    我正在使用 MethodInfo 调用重载方法 该方法引发异常 TargetParameterCount 不匹配 下面是我的代码 public class Device public bool Send byte d int l int t
  • Django MongoDB引擎运行tellsiteid时出错

    所以我按照教程创建了一个 django 项目和应用程序 并且我拥有 MongoDB 引擎所需的所有依赖项 在我尝试启用管理界面之前 一切似乎都工作正常 我取消注释了 require 位 并将 django mongodb engine 和
  • 将 H2 数据库与 Android 集成 [关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 有没有关于将 H2 数据库与 Android 集成并开始使用的教程 我正在寻找执行此操作的指南 Thanks The H2 中的 Android 文档
  • 未使用的数据成员是否占用内存?

    初始化数据成员而不引用 使用它是否会在运行时进一步占用内存 或者编译器是否只是忽略该成员 struct Foo int var1 int var2 Foo var1 5 std cout lt lt var1 在上面的例子中 成员var1获
  • 通用 O 数据控制器未返回预期结果

    我正在尝试创建一个通用的 OData 控制器 我是根据做的this https www strathweb com 2018 04 generic and dynamically generated controllers in asp n
  • Python 井字游戏

    我不确定所有代码是否都是必要的 所以我将发布它 Tic Tac Toe Plays the game of tic tac toe against a human opponent global constants X X O O EMPT