0

我编写了一个 noughts 和 crosss 游戏,并且正在使用 while 循环来运行游戏。但是,我一定是做错了什么,因为当板上有 X 或 O 的行/列/对角线时,我无法让它打印“你赢”或“你输”。我知道检查板的功能就像我自己测试过的那样工作长。谢谢

import random

board = [
['1','-','-','-'],
['2','-','-','-'],
['3','-','-','-'],
['#','1','2','3'],
[' ',' ',' ',' ']
]

rows = {
    'top':
    board[0][1:],
    'mid':
    board[1][1:],
    'bottom':
    board[2][1:]
}

cols = {
    'left':
    [board[0][1],
    board[1][1],
    board[2][1]],
    'mid':
    [board[0][2],
    board[1][2],
    board[2][2]],
    'right':
    [board[0][3],
    board[1][3],
    board[2][3]]
}

diags = {
    'top-bottom':
    [board[0][1],
    board[1][2],
    board[2][3]],
    'bottom-top':
    [board[2][1],
    board[1][2],
    board[0][3]]
}

gamestate = 1

def print_board(board):
    for i in board:
        print " ".join(i)

def win_check(rows,cols,diags):
    plrWin = ['X','X','X']
    cpuWin = ['O','O','O']
    global gamestate
    for i in rows.values():
        if i == plrWin:
            return True
            gamestate = 0

        elif i == cpuWin:
            return False
            gamestate = 0


    for x in cols.values():
        if x == plrWin:
                return True
            gamestate = 0

        elif x == cpuWin:
            return False
            gamestate = 0



    for y in diags.values():
        if y == plrWin:
            return True
            gamestate = 0

    elif y == cpuWin:
        return False
        gamestate = 0





def game_entry():
    print "Your turn."
    coordY = input("Guess column: ")
    coordX = input("Guess row: ")
    board[coordX - 1][coordY] = 'X'

def random_location():
    while True:
        cpuX = random.randint(1,3)
        cpuY = random.randint(1,3)
        if (board[cpuX - 1][cpuY] == 'X') or (board[cpuX - 1][cpuY] == 'O'):
            continue
        else:
            board[cpuX - 1][cpuY] = 'O'
            break


while gamestate == 1:
    print_board(board)
    game_entry()
    random_location()
    if win_check(rows,cols,diags) == True:
        print "You win!"
        gamestate = 0
        break
    elif win_check(rows,cols,diags) == False:
        print "You lose."
        gamestate = 0
        break
    else:
        continue
4

1 回答 1

1

您的问题在于所有rowscols字典:

>>> l = [[1, 2, 3], [4, 5, 6]]
>>> x = l[0][1:]
>>> x
[2, 3]
>>> l[0][1] = 4
>>> x
[2, 3]

如您所见,它们不会在电路板更改时更新。你必须找到另一种方法来做到这一点。

我只会使用几个循环并手动检查对角线:

def has_someone_won(board):
    # Rows
    for row in board:
        if row[0] == row[1] == row[2] != '-':
            return True

    # Columns
    for i in range(3):
        if board[0][i] == board[1][i] == board[2][i] != '-':
            return True

    # Diagonal 1
    if board[0][0] == board[1][1] == board[2][2] != '-':
        return True

    # Diagonal 2
    if board[2][0] == board[1][1] == board[0][2] != '-':
        return True

    # There's no winner
    return False
于 2013-04-11T00:58:51.060 回答