DEV Community

Cover image for Tic Tac Toe with Python!
pleasantencounter
pleasantencounter

Posted on • Edited on

1

Tic Tac Toe with Python!

Project Info

This is my first post on this platform, and I'm excited to share my simple program with this awesome community. The last couple of days I've been working on a Tic Tac Toe game, which I attempted to build a few months ago when I was fresh to python. Needless to say I failed.

I've been working with python for about 6 months, and it's been a blast. Feel free to review the code below and provide any feedback.

Tic Tac Toe Full Code

count = 0
player = 'X'
score = False
dictBoard = {'1':' ' , '2': ' ' , '3': ' ' ,
            '4': ' ' , '5': ' ' , '6': ' ' ,
            '7': ' ' , '8': ' ' , '9': ' ' }
boardList= []
xSet = set()
oSet = set()
newDict = {}

def displayBoard(board):
    print(board['1'],board['2'],board['3'],sep="|")
    print('-+-+-')
    print(board['4'],board['5'],board['6'],sep="|")
    print('-+-+-')
    print(board['7'],board['8'],board['9'],sep="|")

def changeplayer():
    global player
    global count
    if  player == 'X':
        player ='O'
    else:
        player ='X'
    count +=1

def checkScore(board):
    global newDict
    for key,value in board.items():
        if board[key] != " ":
            newDict={value:key}
        for user, position in newDict.items():
            if user == 'X':
                xSet.add(position)
                scoreLogic(xSet)
            elif user == 'O':
                oSet.add(position)
                scoreLogic(oSet)

def resetGame(var, board):
    global score
    global xSet
    global oSet
    global count
    var.lower()
    if var == 'y':
        #clears board
        for key in board:
            board[key] = ' '
        #prints board then resets board variables
        displayBoard(dictBoard)
        score = False
        xSet = set()
        oSet = set()
        count = 0
    else:
        exit()

def scoreLogic(playerSet):
    global score
    if all(num in playerSet for num in ['1','2','3']):
        score = True
    elif all(num in playerSet for num in ['4','5','6']): 
        score = True
    elif all(num in playerSet for num in ['7','8','9']):
        score = True
    elif all(num in playerSet for num in ['1','4','7']):
        score = True
    elif all(num in playerSet for num in ['2','5','8']):
        score = True
    elif all(num in playerSet for num in ['3','6','9']):
        score = True
    elif all(num in playerSet for num in ['1','5','9']):
        score = True
    elif all(num in playerSet for num in ['3','5','7']):
        score = True
    else:
        score = False

def mainGame ():
    while count < 9:
        position = input("Player enter position: ")
        if dictBoard[position] == ' ':
            dictBoard[position]=player
            displayBoard(dictBoard)
            checkScore(dictBoard)   
        else:
            print("Choose a different position")
            continue

        if score == True:
            print("Winner Winner Chicken Dinner!")
            resume = str(input("You would you like to continue, press Y: "))
            resetGame(resume,dictBoard)

        changeplayer()

if __name__ == "__main__":
    mainGame()

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please show some love ❤️ or share a kind word in the comments if you found this useful!

Got it!