Answers for "tic tac toe with classes python"

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
2

tic tac toe in python

import time
import sys

TITLES = "    A   B   Cn"
INIT_BOARD = "| / | / | / |n"
A, B, C = 4, 8, 12
# creates the game board
board = [f"{x} {INIT_BOARD}" for x in range(3)]
user_turn = ""
taken = True
winner = False
turn_number = 0
# keeps the score and determines what symbols will be used
SYMBOLS = ["x", "o"]
winner_save = [list(x * 3) for x in SYMBOLS]
score = {symbol: 0 for symbol in SYMBOLS}

# does all the logic to the game
class logic:
    def __init__(self, ctx, turn, win_template):
        self.ctx = ctx
        self.turn = turn
        self.template = win_template

    # check if 3 of the same symbols are in a line
    def winner_check(self):
        # initializes the list containing the rows. rows 0, 1, and 2 are created
        win_check = [
            [board[c][x] for x in range(4, len(board[c])) if x % 4 == 0]
            for c in range(3)
        ]
        # adds the values for every possible row to the list
        for x in range(3):
            win_check.append([win_check[c][x] for c in range(3)])
        win_check.append([win_check[x][x] for x in range(3)])
        win_check.append([win_check[x][c] for x, c in zip(range(3)[::-1], range(3))])
        # determines if someone has won
        for x in win_check:
            if x in self.template:
                print(f"{self.turn} wins!")
                keep = True
                break
            keep = False
        return keep

    # updates the spot value of the given input. ex: input = A1, spot A1 will be occupied by the player
    def take_spot(self):
        append_board = board[int(user[1])]
        append_board = "".join(
            [
                append_board[x] if x != eval(user[0]) else self.turn
                for x in range(len(append_board))
            ]
        )
        return append_board

    # checks to see if a spot on the board is already occupied
    def spot_taken(self):
        board_ctx = board[int(self.ctx[1])][eval(self.ctx[0])]
        check_spot = True if board_ctx in ["o", "x"] else False
        if check_spot == True:
            print("spot already taken :/ try again")
        return check_spot


# takes the location input and checks if it exists
def input_check():
    slow_print("location- n")
    ctx = input().upper()
    all_input = [x + str(c) for x in ["A", "B", "C"] for c in range(3)]
    if ctx in all_input:
        pass
    else:
        while ctx not in all_input:
            slow_print("invalid location, try againn")
            slow_print("location- n")
            ctx = input().upper()
    return list(ctx)


# takes an input and prints it smoothly to the console
def slow_print(inpt):
    for x in inpt:
        sys.stdout.write(x)
        time.sleep(0.01)


slow_print(TITLES + "".join(board))

# determines what symbol will go first
while True:
    slow_print(f"{SYMBOLS[0]}'s or {SYMBOLS[1]}'s?- n")
    user_turn = input()
    if user_turn in [SYMBOLS[0], SYMBOLS[1]]:
        slow_print(f"{user_turn}'s first!n")
        break
    else:
        slow_print("incorrent input try again!")

# brings all the functions and logic together
while True:
    outcome = "None"
    while winner == False:
        # keeps track of the amount of turns to determine if the outcome is a tie
        turn_number += 1
        if turn_number == 10:
            slow_print("Tie!n")
            outcome = None
            break
        # takes spot input and brings the spot_taken logic together to determines==
        # whether a spot is already occupied
        while taken == True:
            user = input_check()
            init = logic(user, user_turn, winner_save)
            taken = init.spot_taken()
        ctx_board = init.take_spot()
        board[int(user[1])] = ctx_board
        slow_print(TITLES + "".join(board))
        user_turn = SYMBOLS[0] if user_turn != SYMBOLS[0] else SYMBOLS[1]
        taken = True
        winner = init.winner_check()
    # makes sure the point is given to the winner by inverting the current user_turn
    if outcome == None:
        pass
    else:
        score[SYMBOLS[0] if user_turn == SYMBOLS[1] else SYMBOLS[1]] += 1
    slow_print(
        f"Scores: {SYMBOLS[0]}-{score[SYMBOLS[0]]}, {SYMBOLS[1]}-{score[SYMBOLS[1]]}n"
    )
    slow_print("Would you like to play another (Y/N)?- n")
    repeat = input().upper()
    if repeat == "Y":
        winner = False
        board = [f"{x} {INIT_BOARD}" for x in range(3)]
        turn_number = 0
        continue
    else:
        break
Posted by: Guest on March-18-2021

Python Answers by Framework

Browse Popular Code Answers by Language