Answers for "python tic tact toe"

5

how to code a tic tac toe game with ai python

#Tic Tac Toe game in python by techwithtim

board = [' ' for x in range(10)]

def insertLetter(letter, pos):
    board[pos] = letter

def spaceIsFree(pos):
    return board[pos] == ' '

def printBoard(board):
    print('   |   |')
    print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
    print('   |   |')
    print('-----------')
    print('   |   |')
    print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
    print('   |   |')
    print('-----------')
    print('   |   |')
    print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
    print('   |   |')
    
def isWinner(bo, le):
    return (bo[7] == le and bo[8] == le and bo[9] == le) or (bo[4] == le and bo[5] == le and bo[6] == le) or(bo[1] == le and bo[2] == le and bo[3] == le) or(bo[1] == le and bo[4] == le and bo[7] == le) or(bo[2] == le and bo[5] == le and bo[8] == le) or(bo[3] == le and bo[6] == le and bo[9] == le) or(bo[1] == le and bo[5] == le and bo[9] == le) or(bo[3] == le and bo[5] == le and bo[7] == le)

def playerMove():
    run = True
    while run:
        move = input('Please select a position to place an 'X' (1-9): ')
        try:
            move = int(move)
            if move > 0 and move < 10:
                if spaceIsFree(move):
                    run = False
                    insertLetter('X', move)
                else:
                    print('Sorry, this space is occupied!')
            else:
                print('Please type a number within the range!')
        except:
            print('Please type a number!')
            

def compMove():
    possibleMoves = [x for x, letter in enumerate(board) if letter == ' ' and x != 0]
    move = 0

    for let in ['O', 'X']:
        for i in possibleMoves:
            boardCopy = board[:]
            boardCopy[i] = let
            if isWinner(boardCopy, let):
                move = i
                return move

    cornersOpen = []
    for i in possibleMoves:
        if i in [1,3,7,9]:
            cornersOpen.append(i)
            
    if len(cornersOpen) > 0:
        move = selectRandom(cornersOpen)
        return move

    if 5 in possibleMoves:
        move = 5
        return move

    edgesOpen = []
    for i in possibleMoves:
        if i in [2,4,6,8]:
            edgesOpen.append(i)
            
    if len(edgesOpen) > 0:
        move = selectRandom(edgesOpen)
        
    return move

def selectRandom(li):
    import random
    ln = len(li)
    r = random.randrange(0,ln)
    return li[r]
    

def isBoardFull(board):
    if board.count(' ') > 1:
        return False
    else:
        return True

def main():
    print('Welcome to Tic Tac Toe!')
    printBoard(board)

    while not(isBoardFull(board)):
        if not(isWinner(board, 'O')):
            playerMove()
            printBoard(board)
        else:
            print('Sorry, O's won this time!')
            break

        if not(isWinner(board, 'X')):
            move = compMove()
            if move == 0:
                print('Tie Game!')
            else:
                insertLetter('O', move)
                print('Computer placed an 'O' in position', move , ':')
                printBoard(board)
        else:
            print('X's won this time! Good Job!')
            break

    if isBoardFull(board):
        print('Tie Game!')

while True:
    answer = input('Do you want to play again? (Y/N)')
    if answer.lower() == 'y' or answer.lower == 'yes':
        board = [' ' for x in range(10)]
        print('-----------------------------------')
        main()
    else:
        break
Posted by: Guest on June-12-2020
0

tic tac toe python

class Grid:

    def __init__(self):
        self.__grid = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
        self.__score = 0
        self.turn = 1

    def check_location(self, x_index, y_index):
        if self.__grid[int(x_index) - 1][int(y_index) - 1] == 1 or
           self.__grid[int(x_index) - 1][int(y_index) - 1] == 2:
            return False
        else:
            return True

    def display(self):
        lineVal: int = 0
        print("0 1 2 3")
        for i in self.__grid:
            lineVal += 1
            print(str(lineVal), end=" ")
            for k in i:
                print(str(k), end=" ")

            print()

    def place_counter(self, x_index, y_index):
        if self.turn == 1:
            self.__grid[int(x_index) - 1][int(y_index) - 1] = 1
            self.turn = -1
        else:
            self.__grid[int(x_index) - 1][int(y_index) - 1] = 2
            self.turn = 1

    def reset_grid(self):
        for i in range(len(self.__grid)):
            for k in range((len(self.__grid[i]))):
                self.__grid[i][k] = 0

    def victory_check(self):
        for l in range(1, 2):

            for i in range(len(self.__grid)):
                if self.__grid[i][0] == l and self.__grid[i][1] == l and self.__grid[i][2] == l:
                    return True
                if self.__grid[0][i] == l and self.__grid[1][i] == l and self.__grid[2][i] == l:
                    return True
                if self.__grid[0][0] == l and self.__grid[1][1] == l and self.__grid[2][2] == l:
                    return True
                if self.__grid[0][2] == l and self.__grid[1][1] == l and self.__grid[2][0] == l:
                    return True


def collect_place():
    return input("Please enter a location: ")


placingGrid = Grid()
while True:
    placingGrid.display()
    x_pos = collect_place()
    y_pos = collect_place()
    if placingGrid.check_location(x_pos, y_pos):
        placingGrid.place_counter(x_pos, y_pos)
    else:
        print("Invalid location")

    if placingGrid.victory_check():
        print("Well done")
        placingGrid.reset_grid()
Posted by: Guest on July-12-2021

Python Answers by Framework

Browse Popular Code Answers by Language