井字棋将随机执行获胜功能

问题描述 投票:0回答:1

我正在尝试制作一款井字棋游戏,但有时它会无缘无故地执行获胜函数,但有时游戏还没有结束,也没有人获胜。这是为您提供额外信息的程序:

from numpy import array

board = array([
    [0,0,0],
    [0,0,0],
    [0,0,0]
])

turn = 1

def win():
    print(board)
    print('\nYou Win!\n')

while True:
    print(board)

    row = int(input('Row: '))
    column = int(input('Column: '))

    board[row,column] = turn

    if (board[0,0] == turn and board[1,1] == turn and board[2,2] == turn) or (board[0,2] == turn and board[1,1] == turn and board[2,0]): #diagonals
    win()
    break

    if (board[0,0] == turn and board[0,1] == turn and board[0,2] == turn) or (board[1,0] == turn and board[1,1] == turn and board[1,2] == turn) or (board[2,0] == turn and board[2,1] == turn and board[2,2] == turn): #columns
    win()
    break

    if (board[0,0] == turn and board[1,0] == turn and board[2,0] == turn) or (board[0,1] == turn and board[1,1] == turn and board[2,1] == turn) or (board[0,2] == turn and board[1,2] == turn and board[2,2] == turn): #rows
    win()
    break

    if turn == 1:
        turn += 1
    else:
        turn -= 1
python tic-tac-toe
1个回答
1
投票

当所有获胜条件都为真时,您会打印 Win,因为您嵌套了所有获胜 if 情况。

if(..diagonals..):
    if(..columns..): # this works only when the diagonals and columns case is true
        if(..rows..): # this works when diagonals, rows and columns case is true
            print("You win") # this works when all the above cases are true

因此,一次检查一个条件,而不是一次检查所有获胜条件,因此如果任何一个条件为真,则用户获胜。

if(...diagonals...):
    print("You win")
    break
if(...columns...):
    print("You win")
    break
if(...rows...):
    print("You win")
    break

使用 isWin 变量简化上述代码

isWin = True
if(...diagonals...):
    isWin = True
if(...columns...):
    isWin = True
if(...rows...):
    isWin = True

if(isWin):
    print("You Win")
    break;

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.