4
\$\begingroup\$

I made my version of a tic-tac-toe game for fun, but as being new to coding, I would assume that there are far better ways to make this. I just want to simplify my code down to make it easier to manage. I would say the main problem is the code is repetitive. I've tried to use for loops to make the code more concise, but I couldn't get that to work.

import random
import time
import sys

#Sets all of the square variables to empty
one = " "
two = " "
three = " "
four = " "
five = " "
six = " "
seven = " "
eight = " "
nine = " "

#Prints the tic tac toe board
def printboard():
    print("["+one+"]["+two+"]["+three+"]\n["+four+"]["+five+"]["+six+"]\n["+seven+"]["+eight+"]["+nine+"]")

#Your turn. Takes the input and makes sure that the square it is in is empty
def yourvalid():
    while True:
        you = input("Your turn! (1-9)")
        you = you.lower()
        if "1" == you:
            if one == " ":
                return you
            else:
                print("Not Valid. Try again.")
        elif "2" == you:
            if two == " ":
               return you
            else:
                print("Not Valid. Try again.")
        elif "3" == you:
            if three == " ":
                return you
            else:
                print("Not Valid. Try again.")
        elif "4" == you:
            if four == " ":
                return you
            else:
                print("Not Valid. Try again.")
        elif "5" == you:
            if five == " ":
                return you
            else:
                print("Not Valid. Try again.")
        elif "6" == you:
            if six == " ":
                return you
            else:
                print("Not Valid. Try again.")
        elif "7" == you:
            if seven == " ":
                return you
            else:
                print("Not Valid. Try again.")
        elif "8" == you:
            if eight == " ":
                return you
            else:
                print("Not Valid. Try again.")
        elif "9" == you:
            if nine == " ":
                return you
            else:
               print("Not Valid. Try again.")
        else:
            print("Not Valid. Try again.")

#tests if anyone has won the game
def testwon():
    if one == two == three == "x" or four == five == six == "x" or seven == eight == nine == "x" or one == four == seven == "x" or two == five == eight == "x" or three == six == nine == "x" or one == five == nine == "x" or three == five == seven == "x":
        win = "x"
        return win
    elif one == two == three == "o" or four == five == six == "o" or seven == eight == nine == "o" or one == four == seven == "o" or two == five == eight == "o" or three == six == nine == "o" or one == five == nine == "o" or three == five == seven == "o":
        win = "o"
        return win

#The computer's turn, sees if there is a way to win, and if not random selection
def easy():
    if two + three == "oo" and one == " " or four + seven == "oo" and one == " " or five + nine == "oo" and one == " ":
        op = "1"
        return op
    elif one + three == "oo" and two == " " or five + eight == "oo" and two == " ":
        op = "2"
        return op
    elif one + two == "oo" and three == " " or seven + five == "oo" and three == " " or nine + six == "oo" and three == " ":
        op = "3"
        return op
    elif one + seven == "oo" and four == " " or five + six == "oo" and four == " ":
        op = "4"
        return op
    elif one + nine == "oo" and five == " " or two + eight == "oo" and five == " " or three + seven == "oo" and five == " " or four + six == "oo" and five == " ":
        op = "5"
        return op
    elif three + nine == "oo" and six == " " or four + five == "oo" and six == " ":
        op = "6"
        return op
    elif one + four == "oo" and seven == " " or five + three == "oo" and seven == " " or eight + nine == "oo" and seven == " ":
        op = "7"
        return op
    elif two + five == "oo" and eight == " " or seven + nine == "oo" and eight == " ":
        op = "8"
        return op
    elif seven + eight == "oo" and nine == " " or one + five == "oo" and nine == " " or three + six == "oo" and nine == " ":
        op = "9"
        return op
    else:
        random = "0"
        return random

#a different computer. first sees if there is a way to win, then sees if you can win, and then random selection.
def medium():
    if two + three == "oo" and one == " " or four + seven == "oo" and one == " " or five + nine == "oo" and one == " ":
        op = "1"
        return op
    elif one + three == "oo" and two == " " or five + eight == "oo" and two == " ":
        op = "2"
        return op
    elif one + two == "oo" and three == " " or seven + five == "oo" and three == " " or nine + six == "oo" and three == " ":
        op = "3"
        return op
    elif one + seven == "oo" and four == " " or five + six == "oo" and four == " ":
        op = "4"
        return op
    elif one + nine == "oo" and five == " " or two + eight == "oo" and five == " " or three + seven == "oo" and five == " " or four + six == "oo" and five == " ":
        op = "5"
        return op
    elif three + nine == "oo" and six == " " or four + five == "oo" and six == " ":
        op = "6"
        return op
    elif one + four == "oo" and seven == " " or five + three == "oo" and seven == " " or eight + nine == "oo" and seven == " ":
        op = "7"
        return op
    elif two + five == "oo" and eight == " " or seven + nine == "oo" and eight == " ":
        op = "8"
        return op
    elif seven + eight == "oo" and nine == " " or one + five == "oo" and nine == " " or three + six == "oo" and nine == " ":
        op = "9"
        return op
    if two + three == "xx" and one == " " or four + seven == "xx" and one == " " or five + nine == "xx" and one == " ":
        op = "1"
        return op
    elif one + three == "xx" and two == " " or five + eight == "xx" and two == " ":
        op = "2"
        return op
    elif one + two == "xx" and three == " " or seven + five == "xx" and three == " " or nine + six == "xx" and three == " ":
        op = "3"
        return op
    elif one + seven == "xx" and four == " " or five + six == "xx" and four == " ":
        op = "4"
        return op
    elif one + nine == "xx" and five == " " or two + eight == "xx" and five == " " or three + seven == "xx" and five == " " or four + six == "xx" and five == " ":
        op = "5"
        return op
    elif three + nine == "xx" and six == " " or four + five == "xx" and six == " ":
        op = "6"
        return op
    elif one + four == "xx" and seven == " " or five + three == "xx" and seven == " " or eight + nine == "xx" and seven == " ":
        op = "7"
        return op
    elif two + five == "xx" and eight == " " or seven + nine == "xx" and eight == " ":
        op = "8"
        return op
    elif seven + eight == "xx" and nine == " " or one + five == "xx" and nine == " " or three + six == "xx" and nine == " ":
        op = "9"
        return op
    else:
        random = "0"
        return random

#Makes sure the random selection is a valid space
def randomvalid():
    while True:
        ops = random.randrange(1,9)
        if 1 == ops:
            if one == " ":
                return ops
        elif 2 == ops:
            if two == " ":
               return ops
        elif 3 == ops:
            if three == " ":
                return ops
        elif 4 == ops:
            if four == " ":
                return ops
        elif 5 == ops:
            if five == " ":
                return ops
        elif 6 == ops:
            if six == " ":
                return ops
        elif 7 == ops:
            if seven == " ":
                return ops
        elif 8 == ops:
            if eight == " ":
                return ops
        elif 9 == ops:
            if nine == " ":
                return ops

#winning sequence
def winner():
    if testwon() == "x":
        printboard()
        print("X won!")
        sys.exit()
    elif testwon() == "o":
        printboard()
        print("O won!")
        sys.exit()

#Beginning instuctions and difficulty selection
print("[1][2][3]\n[4][5][6]\n[7][8][9]")
print("These are the numbers you enter for each box.")
while True:
    dif = input("Which difficulity do you want? (Easy, Medium)")
    dif = dif.lower()
    if dif == "easy" or dif == "medium":
        print("You have set the difficulty to " + dif.title() + ".")
        break
    else:
        print("Not a valid answer.")

#your turn
printboard()
validated = yourvalid()
if validated == "1":
    one = "x"
elif validated == "2":
    two = "x"
elif validated == "3":
    three = "x"
elif validated == "4":
    four = "x"
elif validated == "5":
    five = "x"
elif validated == "6":
    six = "x"
elif validated == "7":
    seven = "x"
elif validated == "8":
    eight = "x"
elif validated == "9":
    nine = "x"

#tests for a winner    
winner()

#computer's turn
printboard()
print("Computer's Turn!")
time.sleep(2)
if dif == "easy":
    opponent = easy()
    if opponent == "1":
        one = "o"
    elif opponent == "2":
        two = "o"
    elif opponent == "3":
        three = "o"
    elif opponent == "4":
        four = "o"
    elif opponent == "5":
        five = "o"
    elif opponent == "6":
        six = "o"
    elif opponent == "7":
        seven = "o"
    elif opponent == "8":
        eight = "o"
    elif opponent == "9":
        nine = "o"
    elif opponent == "0":
        rand = randomvalid()
        if rand == 1:
            one = "o"
        elif rand == 2:
            two = "o"
        elif rand == 3:
            three = "o"
        elif rand == 4:
            four = "o"
        elif rand == 5:
            five = "o"
        elif rand == 6:
            six = "o"
        elif rand == 7:
            seven = "o"
        elif rand == 8:
            eight = "o"
        elif rand == 9:
            nine = "o"
elif dif == "medium":
    opponent = medium()
    if opponent == "1":
        one = "o"
    elif opponent == "2":
        two = "o"
    elif opponent == "3":
        three = "o"
    elif opponent == "4":
        four = "o"
    elif opponent == "5":
        five = "o"
    elif opponent == "6":
        six = "o"
    elif opponent == "7":
        seven = "o"
    elif opponent == "8":
        eight = "o"
    elif opponent == "9":
        nine = "o"
    elif opponent == "0":
        rand = randomvalid()
        if rand == 1:
            one = "o"
        elif rand == 2:
            two = "o"
        elif rand == 3:
            three = "o"
        elif rand == 4:
            four = "o"
        elif rand == 5:
            five = "o"
        elif rand == 6:
            six = "o"
        elif rand == 7:
            seven = "o"
        elif rand == 8:
            eight = "o"
        elif rand == 9:
            nine = "o"

winner()

printboard()
validated = yourvalid()
if validated == "1":
    one = "x"
elif validated == "2":
    two = "x"
elif validated == "3":
    three = "x"
elif validated == "4":
    four = "x"
elif validated == "5":
    five = "x"
elif validated == "6":
    six = "x"
elif validated == "7":
    seven = "x"
elif validated == "8":
    eight = "x"
elif validated == "9":
    nine = "x"
winner()
printboard()
print("Computer's Turn!")
time.sleep(2)
if dif == "easy":
    opponent = easy()
    if opponent == "1":
        one = "o"
    elif opponent == "2":
        two = "o"
    elif opponent == "3":
        three = "o"
    elif opponent == "4":
        four = "o"
    elif opponent == "5":
        five = "o"
    elif opponent == "6":
        six = "o"
    elif opponent == "7":
        seven = "o"
    elif opponent == "8":
        eight = "o"
    elif opponent == "9":
        nine = "o"
    elif opponent == "0":
        rand = randomvalid()
        if rand == 1:
            one = "o"
        elif rand == 2:
            two = "o"
        elif rand == 3:
            three = "o"
        elif rand == 4:
            four = "o"
        elif rand == 5:
            five = "o"
        elif rand == 6:
            six = "o"
        elif rand == 7:
            seven = "o"
        elif rand == 8:
            eight = "o"
        elif rand == 9:
            nine = "o"
elif dif == "medium":
    opponent = medium()
    if opponent == "1":
        one = "o"
    elif opponent == "2":
        two = "o"
    elif opponent == "3":
        three = "o"
    elif opponent == "4":
        four = "o"
    elif opponent == "5":
        five = "o"
    elif opponent == "6":
        six = "o"
    elif opponent == "7":
        seven = "o"
    elif opponent == "8":
        eight = "o"
    elif opponent == "9":
        nine = "o"
    elif opponent == "0":
        rand = randomvalid()
        if rand == 1:
            one = "o"
        elif rand == 2:
            two = "o"
        elif rand == 3:
            three = "o"
        elif rand == 4:
            four = "o"
        elif rand == 5:
            five = "o"
        elif rand == 6:
            six = "o"
        elif rand == 7:
            seven = "o"
        elif rand == 8:
            eight = "o"
        elif rand == 9:
            nine = "o"
winner()

printboard()
validated = yourvalid()
if validated == "1":
    one = "x"
elif validated == "2":
    two = "x"
elif validated == "3":
    three = "x"
elif validated == "4":
    four = "x"
elif validated == "5":
    five = "x"
elif validated == "6":
    six = "x"
elif validated == "7":
    seven = "x"
elif validated == "8":
    eight = "x"
elif validated == "9":
    nine = "x"
winner()
printboard()
print("Computer's Turn!")
time.sleep(2)
if dif == "easy":
    opponent = easy()
    if opponent == "1":
        one = "o"
    elif opponent == "2":
        two = "o"
    elif opponent == "3":
        three = "o"
    elif opponent == "4":
        four = "o"
    elif opponent == "5":
        five = "o"
    elif opponent == "6":
        six = "o"
    elif opponent == "7":
        seven = "o"
    elif opponent == "8":
        eight = "o"
    elif opponent == "9":
        nine = "o"
    elif opponent == "0":
        rand = randomvalid()
        if rand == 1:
            one = "o"
        elif rand == 2:
            two = "o"
        elif rand == 3:
            three = "o"
        elif rand == 4:
            four = "o"
        elif rand == 5:
            five = "o"
        elif rand == 6:
            six = "o"
        elif rand == 7:
            seven = "o"
        elif rand == 8:
            eight = "o"
        elif rand == 9:
            nine = "o"
elif dif == "medium":
    opponent = medium()
    if opponent == "1":
        one = "o"
    elif opponent == "2":
        two = "o"
    elif opponent == "3":
        three = "o"
    elif opponent == "4":
        four = "o"
    elif opponent == "5":
        five = "o"
    elif opponent == "6":
        six = "o"
    elif opponent == "7":
        seven = "o"
    elif opponent == "8":
        eight = "o"
    elif opponent == "9":
        nine = "o"
    elif opponent == "0":
        rand = randomvalid()
        if rand == 1:
            one = "o"
        elif rand == 2:
            two = "o"
        elif rand == 3:
            three = "o"
        elif rand == 4:
            four = "o"
        elif rand == 5:
            five = "o"
        elif rand == 6:
            six = "o"
        elif rand == 7:
            seven = "o"
        elif rand == 8:
            eight = "o"
        elif rand == 9:
            nine = "o"
winner()

printboard()
validated = yourvalid()
if validated == "1":
    one = "x"
elif validated == "2":
    two = "x"
elif validated == "3":
    three = "x"
elif validated == "4":
    four = "x"
elif validated == "5":
    five = "x"
elif validated == "6":
    six = "x"
elif validated == "7":
    seven = "x"
elif validated == "8":
    eight = "x"
elif validated == "9":
    nine = "x"
winner()
printboard()
print("Computer's Turn!")
time.sleep(2)
if dif == "easy":
    opponent = easy()
    if opponent == "1":
        one = "o"
    elif opponent == "2":
        two = "o"
    elif opponent == "3":
        three = "o"
    elif opponent == "4":
        four = "o"
    elif opponent == "5":
        five = "o"
    elif opponent == "6":
        six = "o"
    elif opponent == "7":
        seven = "o"
    elif opponent == "8":
        eight = "o"
    elif opponent == "9":
        nine = "o"
    elif opponent == "0":
        rand = randomvalid()
        if rand == 1:
            one = "o"
        elif rand == 2:
            two = "o"
        elif rand == 3:
            three = "o"
        elif rand == 4:
            four = "o"
        elif rand == 5:
            five = "o"
        elif rand == 6:
            six = "o"
        elif rand == 7:
            seven = "o"
        elif rand == 8:
            eight = "o"
        elif rand == 9:
            nine = "o"
elif dif == "medium":
    opponent = medium()
    if opponent == "1":
        one = "o"
    elif opponent == "2":
        two = "o"
    elif opponent == "3":
        three = "o"
    elif opponent == "4":
        four = "o"
    elif opponent == "5":
        five = "o"
    elif opponent == "6":
        six = "o"
    elif opponent == "7":
        seven = "o"
    elif opponent == "8":
        eight = "o"
    elif opponent == "9":
        nine = "o"
    elif opponent == "0":
        rand = randomvalid()
        if rand == 1:
            one = "o"
        elif rand == 2:
            two = "o"
        elif rand == 3:
            three = "o"
        elif rand == 4:
            four = "o"
        elif rand == 5:
            five = "o"
        elif rand == 6:
            six = "o"
        elif rand == 7:
            seven = "o"
        elif rand == 8:
            eight = "o"
        elif rand == 9:
            nine = "o"
winner()

printboard()
validated = yourvalid()
if validated == "1":
    one = "x"
elif validated == "2":
    two = "x"
elif validated == "3":
    three = "x"
elif validated == "4":
    four = "x"
elif validated == "5":
    five = "x"
elif validated == "6":
    six = "x"
elif validated == "7":
    seven = "x"
elif validated == "8":
    eight = "x"
elif validated == "9":
    nine = "x"
winner()
printboard()
print("It's a tie!")

Also I'm not that good with functions, so patching up mistakes there would be helpful. Just having overall better code.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Your code is waaaaaaaaaaaaaaaaay too long. Have a look at the 70 other questions on this site that asked about tic-tac-toe in Python and especially their accepted answers to see how many lines of code you really need. \$\endgroup\$ Nov 3, 2017 at 21:25
  • 2
    \$\begingroup\$ @RolandIllig To be fair, only 9 of those questions involve an AI player. \$\endgroup\$ Nov 3, 2017 at 22:55
  • 1
    \$\begingroup\$ Why would you tell OP their code is too long? They came here to find ways to improve it. \$\endgroup\$
    – Daniel
    Nov 4, 2017 at 11:57

2 Answers 2

5
\$\begingroup\$

Before anything else, I'm going to point out to you that you have a function called testwon. It almost works.

The problem is that it will return "x" or "o", but it won't return anything for "nope, no winner yet."

That's sort of like returning None. But you really should make it explicit.

At any rate, you need to create a while loop - not a for loop - to play the game:

while testwon() not in "xo":
    printboard()
    # player turn
    # winner()
    # computer turn
    # winner()

This is because a for loop would run a fixed number of times, but it's possible to win in 5 moves (xoxox) or it might take 9 moves (xoxoxoxox). Since you don't know how many, you want to "keep going until something changes." That's a while loop.

In addition to that change, I'd like you to find places where code is copied, and convert those into a function. For example, all your checks of if validated == "1", etc.

The principle is called "DRY" for Don't Repeat Yourself. It applies in a lot of ways, but this is the most basic: if you write code two times, make it a function (or a macro) and maintain it in one place.

If you make those two changes, I think your code will be a lot smaller, and easier to understand, and easier to review. I'd encourage you to submit a new review with that code.

\$\endgroup\$
2
\$\begingroup\$

Instead of defining 9 individual variables (one, two, …), you should learn about lists.

board = [" " for x in range(9)]

This creates one variable (called board), but that variable can store 9 things at once. Now replace one with board[0], then replace two with board[1], and so on. Your initialization code then looks like:

board[0] = " "
board[1] = " "
board[2] = " "
board[3] = " "
board[4] = " "
board[5] = " "
board[6] = " "
board[7] = " "
board[8] = " "

This already looks more uniform than your individual variables. But the best thing is that you can write this code much shorter:

for i in range(9):
    board[i] = " "

That's all. The second line is run multiple times, once for each number between 0 (inclusive) and 9 (exclusive). In effect, this code does the same as the 9-liner above.

Continuing with this idea, you can make your code much shorter.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.