0
votes

I have written a Tic Tac Toe program that is working, but I am stuck on how to go about writing the chekDraw function (checking the game for a tie). All other functions are working, and I can play the game. My thought is that a for in range loop will go through the board indices, counting the x's and o's until the whole board is full. In main, I have the condition that if it is not a win (checkWin) then it is a tie. I have been staring at this so for so long, I would love fresh eyes on my code. Any insight/advice would be appreciated!

Edit: specifically what is happening with checkDraw is nothing- if the board is full and no winner, the game continually asks for a move, but any move at that point is illegal because all spots are taken (validation from getMove function).

# display instructions
def displayInstructions():
    print()
    print("This is a game of Tic-Tac-Toe. You will select an empty location")
    print("and enter its index to select a move. The first player will be X")
    print("and the second player will be O.")
    print()


# display current state
# pass in board
# does not return anything
def showBoard(board):
    for i in range(len(board)):
        print("[" + str(board[i]) + "]", end="")
        if i == 2 or i == 5 or i == 8:
            print(end="\n")


# pass in board
# return updated board
# must validate move (in range, unoccupied square)
def getMove(board, player):
    validMove = False
    while not validMove:
        move = input("{0}, what is your move: ".format(player))
        position = int(move) - 1  # cast input as an integer, and puts player move in correct index
        # in range
        if position < 0 or position > 8:
            print("That is an illegal move.")
        # unoccupied square
        if board[position] == "X" or board[position] == "O":
            print("That is an illegal move.")
        else:
            # if valid move, put player on board
            board[position] = player
            return board


def checkWin(board, player):
    if (board[0] == player and board[1] == player and board[2] == player) or \
            (board[3] == player and board[4] == player and board[5] == player) or \
            (board[6] == player and board[7] == player and board[8] == player) or \
            (board[0] == player and board[3] == player and board[6] == player) or \
            (board[1] == player and board[4] == player and board[7] == player) or \
            (board[2] == player and board[5] == player and board[8] == player) or \
            (board[0] == player and board[4] == player and board[8] == player) or \
            (board[2] == player and board[4] == player and board[6] == player):
        return True
    else:
        return False


def checkDraw(board, player):
    count = 0
    for i in range(len(board)):
        if board[i] == player:
            # if board[i] == "X" or board[i) == "O"
            count += 1
        if count == len(board):
            return True


def main():
    # Repeat play loop
    playGame = True
    while playGame:
        # output instructions
        displayInstructions()
        # initialize board
        board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        print(len(board))
        # initialize first player to X
        player = "X"
        # play until win or draw
        while not checkWin(board, player) or checkDraw(board, player):
            showBoard(board)
            getMove(board, player)
            checkWin(board, player)
            checkDraw(board, player)
            # if the game is in play (not a win or draw)
            if not checkWin(board, player) or checkDraw(board, player):
                # swap player
                if player == "X":
                    player = "O"
                else:
                    player = "X"
        # if win
        if checkWin(board, player):
            showBoard(board)
            print("{0} wins.".format(player))
            playGame = False
        # if draw
        elif checkDraw(board, player):
            showBoard(board)
            print("It's a draw")
            playGame = False
        # Ask if want to play another game
        playAgain = input("Would you like to play again? (y/n): ").lower()
        if playAgain == "y":
            main()
        else:
            print("Goodbye.")


if __name__ == "__main__":
    main()
1
What specific problems are you facing when you try to implement the chekDraw function? - izhang05
My suggestion is to keep track of how many X/Os on the board, and if no one won and there are 9 pieces then it's a draw - afghanimah
I would reccomend initializing the board to a list of ~None~. Then when you check the board you can just say~for I in board: if i is None: return False~ then when you check valid moves you can make sure the spot is not already used! - TheLazyScripter
Thank you for the suggestions! I will try them out. - user12810341

1 Answers

0
votes

instead of these long series of and/or, you should build a list of board positions that form segments (lines) and use it as indirection to get all patterns on the board:

For example:

segments = [ (0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6) ]

boardMarks = [ c if c in "XO" else "." for c in board ]
patterns   = [ "".join(sorted(boardMarks[i] for i in s)) for s in segments ]

playerWins = (player*3) in patterns
xWins      = "XXX" in patterns
oWins      = "OOO" in patterns
draw       = not xWins and not oWins and "." not in boardMarks

or, if you want to be more predictive and call out a draw early when there are no more moves that can win:

draw = not any(canWin in patterns for canWin in ("...","..X","..O",".XX",".OO"))

Because the patterns are sorted, there are only 5 combinations that represent a winnable line

If you want to make the computer play, you can use this 'autoPlay' function to select a position based on a mini-max rating system:

skill = 4 # 1 to 4 (novice to master)
def rating(position,player,board,level=skill+5):
    if board[position] in "XO" or not level: return 0
    newBoard = board[:position]+[player]+board[position+1:]
    isWin = player*3 in ( "".join(newBoard[i] for i in s) for s in segments )
    if isWin: return 3**level * 2
    nextRatings = [rating(p,"XO"[player=="X"],newBoard,level-1) for p in range(9)]
    return 3**level - max(nextRatings,key=abs)

from random import sample
def autoPlay(board,player):
    return max(sample(range(9),9),key=lambda p:rating(p,player,board))

Example use:

position = autoPlay(board,player)
print("computer plays ",player," at position ",position+1)
board[position] = player