Skip to content Skip to sidebar Skip to footer

Tic-tac-toe Game - Errors And Ai

import random def game(): def display_instructions(): ''' Will print out instructions for how to play tic-tac-toe''' print('Hello, and welcome to TIC-TAC-TOE! Here's how yo

Solution 1:

You could use this compact Computer player function as your AI:

from random import sample
axes = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)] 

defisWin(board):
    returnany(board[a]+board[b]+board[c] in ["XXX","OOO"] for a,b,c in axes)

#level 3**3=Naive, 3**4=beginner, 3**5=intermediate, 3**6=good, 3**7=expertdefrating(position,play,board,level=3**6):    
    if board[position] != " "or level < 3: return0
    newBoard = board[:position]+[play]+board[position+1:]
    if isWin(newBoard): return level*2
    nextRatings = [rating(p,"XO"[play=="X"],newBoard,level/3) for p inrange(9)]
    return level-max(nextRatings,key=abs)

To make the computer play (with some randomness), use this line where computer is the letter that the computer plays ("X" or "O") and board is a list of board positions (indexed from 0 to 8) containing "X", "O" or a space character:

position = max(sample(range(9),9),key=lambda p:rating(p,computer,board))

Here is some sample code using the computer playing function:

whileTrue:
    board = [" "]*9
    player,computer = sample("XOXO",2)
    player = computer
    print(player,computer)
    whileTrue:
        for r inrange(0,9,3):
            print("("+") (".join(board[r:r+3])+")",list(range(r+1,r+4)))
        available = [str(p+1) for p inrange(9) if board[p] == " "]
        if isWin(board) ornot available : break
        player = "XO"[player=="X"]
        if player == computer:
            position = max(sample(range(9),9),key=lambda p:rating(p,computer,board))
            print(f"Computer plays {player} at {position+1}")
        else:
            whileTrue:
                position = input(f"Position to play for {player}: ")
                if position notin available: print("Invalid position")
                else : position = int(position)-1; break
        board[position] = player
    print( f"{player}'s WIN !!!\n"if isWin(board) else"DRAW.\n")

Post a Comment for "Tic-tac-toe Game - Errors And Ai"