本文介绍了Python的tic tac脚趾游戏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 #Tic-Tac -Toe 
#针对人类对手玩井字游戏

#全局常量
X =X
O =O$
EMPTY =
TIE =TIE
NUM_SQUARES = 9


def display_instruct():
显示游戏说明。
print(

欢迎来到史上最伟大的智力挑战:Tic-Tac-Toe
这将是你人类大脑和我的硅片处理器

您将通过输入一个数字0-8来确定您的移动。数字
将对应于所示的板位置:

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

准备好自己,人类。最终的战斗即将开始。\




def ask_yes_no(问题):
询问是或否的问题。
response =无
,而响应不在(y,n)中:
response =输入(问题).lower()
返回响应


def ask_number(question,low,high):
询问一个范围内的数字。
response =无
,而响应不在范围内(低,高):
响应= int(输入(问题))
返回响应


def pieces():
确定播放器或计算机是首先播放。
go_first = ask_yes_no(你需要第一步? (y / n):)
if go_first ==y:
print(\\\
然后采取第一步,您将需要它。)
human = X
computer = O
else:
print(\\\
你的英勇将会是你的失败......我会先走。)
computer = X
human = O
返回电脑,人类

$ b $ def new_board():
创建新的游戏板。
board = [] $ (NUM_SQUARES):
board.append(EMPTY)
退货板



def display_board(board):
在屏幕上显示游戏板。
print(\\\
\t,board [0],|,board [1],|,board [ 2])
print(\ t,---------)
print(\t,board [3],|,board [ (\ t,---------)
print(\t,board [4],|,board [5])
print 6),|,董事会[7],|,董事会[8])

def legal_moves(董事会):
创建法律动议列表。
moves = [ ]
(NUM_SQUARES):
如果board [square] == EMPTY:
moves.append(square)
返回动作


def赢家(棋盘):
确定游戏赢家。
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))

用于WAYS_TO_WIN中的行:
如果board [row [0]] = = board [row [1]] == board [row [2]]!= EMPTY:
赢家= board [row [0]]
返回赢家

如果EMPTY不在董事会:
返回TIE

返回无


def human_move(board,human):
Get human move 。
legal = legal_moves(board)
move = None
移动时不合法:
move = ask_number(你会在哪里移动? (0-8):,0,NUM_SQUARES)
如果移动不合法:
print(\\\
该方块已经被占用,愚蠢的人选择另一个.\\\

print(Fine ...)
return move


def computer_move(board,computer,human):
让电脑移动。
#制作副本,因为函数会改变列表
board = board [:]
#最佳位置,以
为单位BEST_MOVES =( 4,0,2,6,8,1,3,5,7)

print(我将采用方形数字,end =)

#如果计算机能够赢,那么在法律移动(棋盘)中移动

棋盘[移动] =计算机
如果赢家(棋盘)==计算机:
打印移动)
返回移动
#完成检查这个移动,撤销它
board [移动] = EMPTY

#如果人类能赢,阻止那个移动
在legal_moves(board)中移动:
board [move] =嗡嗡声
如果赢家(棋盘)==人类:
打印(移动)
返回移动
#完成检查此移动,撤消它
board [move] = EMPTY

#因为没有人能在下一步赢得胜利,所以选择最好的开放广场
在BEST_MOVES中移动:
如果在legal_moves(棋盘)中移动:
print(move )
返回移动


def next_turn(转):
开关转向。
if == X:
return O
else:
return X


def congrat_winner(the_winner,computer,human):
恭喜获胜者。
如果the_winner!= TIE:
print(the_winner,won!\\\

else:
print(这是一条领带!\\\


如果the_winner ==电脑:
print(正如我预测的那样,人类,我再一次得意洋洋。 \ n\
证明电脑在所有方面都优于人类。)

elif the_winner == human:
print(不,不!不能!不知何故,你欺骗了我,人类。\\\
\
但是再也不会!我,电脑,发誓!)

elif the_winner == TIE:
print(你是最幸运的人,并且设法和我结婚。\\ \\\
今天庆祝......因为这是你将达到的最好成绩。)

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

而不是赢家(board):
if turn == human:
move = human_move(board,human)
board [move] =人
else:
move = computer_move(board,computer,human)
board [move] = computer
display_board(board )
转= next_turn(转)

the_winner =获奖者(董事会)
congrat_winner(the_winner,computer,human)


#启动程序
main()
input(\\\
\\\
按Enter键退出)

这是我正在阅读的一本书中的一个例子,我并不完全理解,我想了解所有这些知识直到:

<$对于WAYS_TO_WIN中的行,为

如果board [row [0]] == board [row [1]] == board [row [2]]!= EMPTY:
赢家= board [row [0]]
赢家

有人可以请解释此函数的作用,更具体地说,如果board [row [0]] == board [row [1]] == board [row [2]]!= EMPTY,条件
正在测试?

解决方案

(如行数组中所列)具有(a)相同的值注意:在Python中,如果a == b == c!= d,那么检查a == b和b是否为空。

== c AND c!= d



因此,如果单元格0,1和2都具有X,那么在第一次通过循环时,将返回X来自胜利者的例程。

I am unsure if all of the code will be necessary or not so i will post it:

# 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.")

This is an example in a book i am reading and i am not fully understanding, i think understand all of it up until:

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

Can somebody please explain what this function does and more specifically what the conditionif board[row[0]] == board[row[1]] == board[row[2]] != EMPTY: is testing?

解决方案

It's just checking the current board to see if any winning combination of cells (as listed in the row array) have (a) the same value and (b) that value is not EMPTY.

Note: in Python, if a == b == c != d, checks that a ==b AND b == c AND c != d

So if cells 0, 1, and 2, all have X, then on the first pass through the loop, it will return X from the winner routine.

这篇关于Python的tic tac脚趾游戏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 04:00