Home > front end >  Was making an AI tic tac toe bot, but return is giving output as none when there is a value there
Was making an AI tic tac toe bot, but return is giving output as none when there is a value there

Time:11-03

I am kind of new to python and its also my first time asking here so sorry in advance for any mistakes

I was working on a AI tic tac toe bot and while testing it I found that many a times the output was coming as none instead of the output that's mentioned in the return

TL;DR: return is giving none instead of output

(https://pastebin.com/kR2Mk2GA)

CodePudding user response:

I'm guessing it's the function cal that returns a None. It is most likely because of your nested elif/if lines 35 to 178. Let's look at the last one for example:

elif squ[6] == squ[2] == "o": 
    # if this is True

    if squ[4] != "x":
        # But this is false
        return "4"

    # You end up not returning, which is equal to a None

What should happend when squ[6] == squ[2] == "o" is True but squ[4] != "x" is False ?


Side note: Try to limit code repetition, it will help a great deal with debugging. There are "a lot" of other things you can do to make your code better, a good way to find them is to read other people's code.

Have fun learning python !

CodePudding user response:

When you use a string of elif statements instead of new if statements your code doesn't continue execution after it reaches the inside of elif.

The problem is, when your AI opponent tries to place an X where you already have a O it sees that it cannot, but the code isn't continuing after it finds that information out(because you're using elif), returning nothing. This is causing your function to return nothing.

Example:

test = "foo"
frank = "bar"

if (test == "foo"):
    print("we made it here!")
elif (frank == "bar" ):
    print("this never gets executed because we found our first if statement!")
    
    
if (test == "foo"):
    print("we made it here!")
if (frank == "bar"):
    print("We also made it here, because we used if instead of elif!")

Instead of using a bunch of elif you're going to want to replace them to regular "if" statements inside your cal() method(function.)

if squ[8] == squ[7] == "x":
    if squ[6] != "o":
        return "6"
if squ[8] == squ[6] == "x":
    if squ[7] != "o":
        return "7"
if squ[6] == squ[7] == "x":
    if squ[8] != "o":
        return "8"
if squ[5] == squ[4] == "x":
    if squ[3] != "o":
        return "3"
  • Related