Python:while循环中的noughts和crosses

时间:2013-04-11 00:53:10

标签: python loops while-loop

我编写了一个不存在和交叉的游戏,我正在使用while循环来运行游戏。但是,我必须做错事,因为当X或O的行/列/对角线在板上时,我无法打印出“你赢了”或“你输了”。我知道检查电路板的功能是因为我自己测试了它,手动将X放在电路板上,但是当正常播放游戏时它完全忽略了3中的任何X或Os。这是代码,对不起它是abit长。感谢

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

1 个答案:

答案 0 :(得分: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