Tic-Toc-Toe Game (Phyton 3.X.X)

This is the place to post any code that you want to share with the community. Only completed scripts should be posted here.

Tic-Toc-Toe Game (Phyton 3.X.X)

Postby Tricky » Mon Aug 19, 2013 11:55 am

I have stated trying phyton for a littel while now. about 2 weeks.i wanted to challange my self, so why not do the same thing i did in visual basic and C++, C# and batch. Create a Tic-Toc-Toe game!

i want to hear what you think about it, and if this is good or bad. pls aswell give a rating of 0-5 so i know more of how good i did. anyway here it is:
Code: Select all
import time
from sys import exit
#_--------------------------------------------------------------------------------------------
Player = "X"
numX = 1
numO = 1
#_--------------------------------------------------------------------------------------------
A1 = "#       #"
A2 = "#       #"
A3 = "#       #"
A4 = "#       #"
A5 = "#       #"
A6 = "#       #"
A7 = "#       #"
A8 = "#       #"
A9 = "#       #"
B1 = "#       #"
B2 = "#       #"
B3 = "#       #"
B4 = "#       #"
B5 = "#       #"
B6 = "#       #"
B7 = "#       #"
B8 = "#       #"
B9 = "#       #"
C1 = "#       #"
C2 = "#       #"
C3 = "#       #"
C4 = "#       #"
C5 = "#       #"
C6 = "#       #"
C7 = "#       #"
C8 = "#       #"
C9 = "#       #"
PXL1 = "# #   # #"
PXL2 = "#  # #  #"
PXL3 = "# #   # #"
POL1 = "#  # #  #"
POL2 = "# #   # #"
POL3 = "#  # #  #"
BLA1 = "#       #"
BLA2 = "#       #"
BLA3 = "#       #"
#_--------------------------------------------------------------------------------------------
def printgamepanel():
    checkO()
    checkX()
    print("")
    print("")
    print("")
    print("")
    print("")
    print("")
    print("")
    print("")
    print("")
    print("")
    print("")
    print("")
    print("")
    print("")
    print("")
    print("")
    print("")
    print("#############################")
    print("#"+A1+A2+A3+"#")
    print("#"+A4+A5+A6+"#")
    print("#"+A7+A8+A9+"#")
    print("#############################")
    print("#"+B1+B2+B3+"#")
    print("#"+B4+B5+B6+"#")
    print("#"+B7+B8+B9+"#")
    print("#############################")
    print("#"+C1+C2+C3+"#")
    print("#"+C4+C5+C6+"#")
    print("#"+C7+C8+C9+"#")
    print("#############################")
#_--------------------------------------------------------------------------------------------
def RePlayerXMove():
    printgamepanel()
    PlayerXMove()
def RePlayerOMove():
    printgamepanel()
    PlayerOMove()
def PlayerXMove():
    global A1
    global A2
    global A3
    global A4
    global A5
    global A6
    global A7
    global A8
    global A9
    global B1
    global B2
    global B3
    global B4
    global B5
    global B6
    global B7
    global B8
    global B9
    global C1
    global C2
    global C3
    global C4
    global C5
    global C6
    global C7
    global C8
    global C9
    global numX
    while True:
        try:
            move_string = input("Player X move:")
            move = int(move_string)
            if move > 9:
                print("Enter a number between 1 and 9!")
                RePlayerXMove()
            if move < 1:
                print("Enter a number between 1 and 9!")
                RePlayerXMove()
            if move == 1:
                if A1 == "#       #":
                    if numX <= 3:
                        A1=PXL1
                        A4=PXL2
                        A7=PXL3
                        numX += 1
                    elif numX > 3:
                        print("You dont have any free X's!")
                        RePlayerXMove()
                elif A1 == "#  # #  #":
                    print("You can't select a feild that the other player have")
                    RePlayerXMove()
                elif A1 == "# #   # #":
                    A1 = "#       #"
                    A4 = "#       #"
                    A7 = "#       #"
                    numX -= 1
                    RePlayerXMove()
            if move == 2:
                if A2 == "#       #":
                    if numX <= 3:
                        A2=PXL1
                        A5=PXL2
                        A8=PXL3
                        numX += 1
                    elif numX > 3:
                        print("You dont have any free X's!")
                        RePlayerXMove()
                elif A2 == "#  # #  #":
                    print("You can't select a feild that the other player have")
                    RePlayerXMove()
                elif A2 == "# #   # #":
                    A2 = "#       #"
                    A5 = "#       #"
                    A8 = "#       #"
                    numX -= 1
                    RePlayerXMove()
            if move == 3:
                if A3 == "#       #":
                    if numX <= 3:
                        A3=PXL1
                        A6=PXL2
                        A9=PXL3
                        numX += 1
                    elif numX > 3:
                        print("You dont have any free X's!")
                        RePlayerXMove()
                elif A3 == "#  # #  #":
                    print("You can't select a feild that the other player have")
                    RePlayerXMove()
                elif A3 == "# #   # #":
                    A3 = "#       #"
                    A6 = "#       #"
                    A9 = "#       #"
                    numX -= 1
                    RePlayerXMove()
            if move == 4:
                if B1 == "#       #":
                    if numX <= 3:
                        B1=PXL1
                        B4=PXL2
                        B7=PXL3
                        numX += 1
                    elif numX > 3:
                        print("You dont have any free X's!")
                        RePlayerXMove()
                elif B1 == "#  # #  #":
                    print("You can't select a feild that the other player have")
                    RePlayerXMove()
                elif B1 == "# #   # #":
                    B1 = "#       #"
                    B4 = "#       #"
                    B7 = "#       #"
                    numX -= 1
                    RePlayerXMove()
            if move == 5:
                if B2 == "#       #":
                    if numX <= 3:
                        B2=PXL1
                        B5=PXL2
                        B8=PXL3
                        numX += 1
                    elif numX > 3:
                        print("You dont have any free X's!")
                        RePlayerXMove()
                elif B2 == "#  # #  #":
                    print("You can't select a feild that the other player have")
                    RePlayerXMove()
                elif B2 == "# #   # #":
                    B2 = "#       #"
                    B5 = "#       #"
                    B8 = "#       #"
                    numX -= 1
                    RePlayerXMove()
            if move == 6:
                if B3 == "#       #":
                    if numX <= 3:
                        B3=PXL1
                        B6=PXL2
                        B9=PXL3
                        numX += 1
                    elif numX > 3:
                        print("You dont have any free X's!")
                        RePlayerXMove()
                elif B3 == "#  # #  #":
                    print("You can't select a feild that the other player have")
                    RePlayerXMove()
                elif B3 == "# #   # #":
                    B3 = "#       #"
                    B6 = "#       #"
                    B9 = "#       #"
                    numX -= 1
                    RePlayerXMove()
            if move == 7:
                if C1 == "#       #":
                    if numX <= 3:
                        C1=PXL1
                        C4=PXL2
                        C7=PXL3
                        numX += 1
                    elif numX > 3:
                        print("You dont have any free X's!")
                        RePlayerXMove()
                elif C1 == "#  # #  #":
                    print("You can't select a feild that the other player have")
                    RePlayerXMove()
                elif C1 == "# #   # #":
                    C1 = "#       #"
                    C4 = "#       #"
                    C7 = "#       #"
                    numX -= 1
                    RePlayerXMove()
            if move == 8:
                if C2 == "#       #":
                    if numX <= 3:
                        C2=PXL1
                        C5=PXL2
                        C8=PXL3
                        numX += 1
                    elif numX > 3:
                        print("You dont have any free X's!")
                        RePlayerXMove()
                elif C2 == "#  # #  #":
                    print("You can't select a feild that the other player have")
                    RePlayerXMove()
                elif C2 == "# #   # #":
                    C2 = "#       #"
                    C5 = "#       #"
                    C8 = "#       #"
                    numX -= 1
                    RePlayerXMove()
            if move == 9:
                if C3 == "#       #":
                    if numX <= 3:
                        C3=PXL1
                        C6=PXL2
                        C9=PXL3
                        numX += 1
                    elif numX > 3:
                        print("You dont have any free X's!")
                        RePlayerXMove()
                elif C3 == "#  # #  #":
                    print("You can't select a feild that the other player have")
                    RePlayerXMove()
                elif C3 == "# #   # #":
                    C3 = "#       #"
                    C6 = "#       #"
                    C9 = "#       #"
                    numX -= 1
                    RePlayerXMove()
            #time.sleep(1)
            printgamepanel()
            print("X moved to "+str(move))
            time.sleep(1)
            Turn()
        except:
            print('please enter a number')
            continue
#_--------------------------------------------------------------------------------------------
def PlayerOMove():
    global A1
    global A2
    global A3
    global A4
    global A5
    global A6
    global A7
    global A8
    global A9
    global B1
    global B2
    global B3
    global B4
    global B5
    global B6
    global B7
    global B8
    global B9
    global C1
    global C2
    global C3
    global C4
    global C5
    global C6
    global C7
    global C8
    global C9
    global numO
    while True:
        try:
            move_string = input("Player O move:")
            move = int(move_string)
            if move > 9:
                print("Enter a number between 1 and 9!")
                PlayerOMove()
            if move < 1:
                print("Enter a number between 1 and 9!")
                PlayerOMove()
            if move == 1:
                if A1 == "#       #":
                    if numO <= 3:
                        A1=POL1
                        A4=POL2
                        A7=POL3
                        numO += 1
                    elif numO > 3:
                        print("You dont have any free O's!")
                        RePlayerOMove()
                elif A1 == "# #   # #":
                    print("You can't select a feild that the other player have")
                    RePlayerOMove()
                elif A1 == "#  # #  #":
                    A1 = "#       #"
                    A4 = "#       #"
                    A7 = "#       #"
                    numO -= 1
                    RePlayerOMove()
            if move == 2:
                if A2 == "#       #":
                    if numO <= 3:
                        A2=POL1
                        A5=POL2
                        A8=POL3
                        numO += 1
                    elif numO > 3:
                        print("You dont have any free O's!")
                        RePlayerOMove()
                elif A2 == "# #   # #":
                    print("You can't select a feild that the other player have")
                    RePlayerOMove()
                elif A2 == "#  # #  #":
                    A2 = "#       #"
                    A5 = "#       #"
                    A8 = "#       #"
                    numO -= 1
                    RePlayerOMove()
            if move == 3:
                if A3 == "#       #":
                    if numO <= 3:
                        A3=POL1
                        A6=POL2
                        A9=POL3
                        numO += 1
                    elif numO > 3:
                        print("You dont have any free O's!")
                        RePlayerOMove()
                elif A3 == "# #   # #":
                    print("You can't select a feild that the other player have")
                    RePlayerOMove()
                elif A3 == "#  # #  #":
                    A3 = "#       #"
                    A6 = "#       #"
                    A9 = "#       #"
                    numO -= 1
                    RePlayerOMove()
            if move == 4:
                if B1 == "#       #":
                    if numO <= 3:
                        B1=POL1
                        B4=POL2
                        B7=POL3
                        numO += 1
                    elif numO > 3:
                        print("You dont have any free O's!")
                        RePlayerOMove()
                elif B1 == "# #   # #":
                    print("You can't select a feild that the other player have")
                    RePlayerOMove()
                elif B1 == "#  # #  #":
                    B1 = "#       #"
                    B4 = "#       #"
                    B7 = "#       #"
                    numO -= 1
                    RePlayerOMove()
            if move == 5:
                if B2 == "#       #":
                    if numO <= 3:
                        B2=POL1
                        B5=POL2
                        B8=POL3
                        numO += 1
                    elif numO > 3:
                        print("You dont have any free O's!")
                        RePlayerOMove()
                elif B2 == "# #   # #":
                    print("You can't select a feild that the other player have")
                    RePlayerOMove()
                elif B2 == "#  # #  #":
                    B2 = "#       #"
                    B5 = "#       #"
                    B8 = "#       #"
                    numO -= 1
                    RePlayerOMove()
            if move == 6:
                if B3 == "#       #":
                    if numO <= 3:
                        B3=POL1
                        B6=POL2
                        B9=POL3
                        numO += 1
                    elif numO > 3:
                        print("You dont have any free O's!")
                        RePlayerOMove()
                elif B3 == "# #   # #":
                    print("You can't select a feild that the other player have")
                    RePlayerOMove()
                elif B3 == "#  # #  #":
                    B3 = "#       #"
                    B6 = "#       #"
                    B9 = "#       #"
                    numO -= 1
                    RePlayerOMove()
            if move == 7:
                if C1 == "#       #":
                    if numO <= 3:
                        C1=POL1
                        C4=POL2
                        C7=POL3
                        numO += 1
                    elif numO > 3:
                        print("You dont have any free O's!")
                        RePlayerOMove()
                elif C1 == "# #   # #":
                    print("You can't select a feild that the other player have")
                    RePlayerOMove()
                elif C1 == "#  # #  #":
                    C1 = "#       #"
                    C4 = "#       #"
                    C7 = "#       #"
                    numO -= 1
                    RePlayerOMove()
            if move == 8:
                if C2 == "#       #":
                    if numO <= 3:
                        C2=POL1
                        C5=POL2
                        C8=POL3
                        numO += 1
                    elif numO > 3:
                        print("You dont have any free O's!")
                        RePlayerOMove()
                elif C2 == "# #   # #":
                    print("You can't select a feild that the other player have")
                    RePlayerOMove()
                elif C2 == "#  # #  #":
                    C2 = "#       #"
                    C5 = "#       #"
                    C8 = "#       #"
                    numO -= 1
                    RePlayerOMove()
            if move == 9:
                if C3 == "#       #":
                    if numO <= 3:
                        C3=POL1
                        C6=POL2
                        C9=POL3
                        numO += 1
                    elif numO > 3:
                        print("You dont have any free O's!")
                        RePlayerOMove()
                elif C3 == "#  # #  #":
                    print("You can't select a feild that the other player have")
                    RePlayerOMove()
                elif C3 == "# #   # #":
                    C3 = "#       #"
                    C6 = "#       #"
                    C9 = "#       #"
                    numO -= 1
                    RePlayerOMove()
            #time.sleep(1)
            printgamepanel()
            print("O moved to "+str(move))
            time.sleep(1)
            Turn()
        except:
            print('please enter a number')
            continue
#----------------------------------------------------------------------------------------------------------------------
def Turn():
    global Player
    if Player == "X":
        Player="O"
        PlayerOMove()
    if Player=="O":
        Player="X"
        PlayerXMove()
def checkO():
    if A1 == "#  # #  #" and A2 == "#  # #  #" and A3 == "#  # #  #":
        print("Player O Won!")
        time.sleep(5)
        exit(0)
    if B1 == "#  # #  #" and B2 == "#  # #  #" and B3 == "#  # #  #":
        print("Player O Won!")
        time.sleep(5)
        exit(0)
    if C1 == "#  # #  #" and C2 == "#  # #  #" and C3 == "#  # #  #":
        print("Player O Won!")
        time.sleep(5)
        exit(0)
    if A1 == "#  # #  #" and B1 == "#  # #  #" and C1 == "#  # #  #":
        print("Player O Won!")
        time.sleep(5)
        exit(0)
    if A2 == "#  # #  #" and B2 == "#  # #  #" and C2 == "#  # #  #":
        print("Player O Won!")
        time.sleep(5)
        exit(0)
    if A3 == "#  # #  #" and B3 == "#  # #  #" and C3 == "#  # #  #":
        print("Player O Won!")
        time.sleep(5)
        exit(0)
    if A1 == "#  # #  #" and B2 == "#  # #  #" and C3 == "#  # #  #":
        print("Player O Won!")
        time.sleep(5)
        exit(0)
    if A3 == "#  # #  #" and B2 == "#  # #  #" and C1 == "#  # #  #":
        print("Player O Won!")
        time.sleep(5)
        exit(0)
def checkX():
    if A1 == "# #   # #" and A2 == "# #   # #" and A3 == "# #   # #":
        print("Player X Won!")
        time.sleep(5)
        exit(0)
    if B1 == "# #   # #" and B2 == "# #   # #" and B3 == "# #   # #":
        print("Player X Won!")
        time.sleep(5)
        exit(0)
    if C1 == "# #   # #" and C2 == "# #   # #" and C3 == "# #   # #":
        print("Player X Won!")
        time.sleep(5)
        exit(0)
    if A1 == "# #   # #" and B1 == "# #   # #" and C1 == "# #   # #":
        print("Player X Won!")
        time.sleep(5)
        exit(0)
    if A2 == "# #   # #" and B2 == "# #   # #" and C2 == "# #   # #":
        print("Player X Won!")
        time.sleep(5)
        exit(0)
    if A3 == "# #   # #" and B3 == "# #   # #" and C3 == "# #   # #":
        print("Player X Won!")
        time.sleep(5)
        exit(0)
    if A1 == "# #   # #" and B2 == "# #   # #" and C3 == "# #   # #":
        print("Player X Won!")
        time.sleep(5)
        exit(0)
    if A3 == "# #   # #" and B2 == "# #   # #" and C1 == "# #   # #":
        print("Player X Won!")
        time.sleep(5)
        exit(0)
#----------------------------------------------------------------------------------------------------------------------
printgamepanel()
PlayerXMove()
#----------------------------------------------------------------------------------------------------------------------



I used alot of if statements and strings i know xD
Tricky
 
Posts: 2
Joined: Mon Aug 19, 2013 11:44 am

Re: Tic-Toc-Toe Game (Phyton 3.X.X)

Postby Mekire » Mon Aug 19, 2013 4:02 pm

So you have only studied python for 2 weeks so I will try not to be too harsh here, but... you need to reexamine your entire approach. Anytime you think you need a numbered variable name, what you actually need is a list (or other container object). Global variables are not acceptable. You have raw exceptions which catch exceptions that are supposed to end the game (like keyboard interrupt). Also a lot of this is very repetitious making your program a lot longer than it needs to be.

This is not guaranteed error free and could still do with some cleaning but take a look. I limited myself to just functions as I don't think you have learned classes at this point.
Code: Select all
X_CELL = ["#########  ",
          "# #   # #  ",
          "#   #   #  ",
          "# #   # #  "]


O_CELL = ["#########  ",
          "#  # #  #  ",
          "# #   # #  ",
          "#  # #  #  "]


BLANK_CELL = ["#########  ",
              "#       #  ",
              "#       #  ",
              "#       #  "]


OPTION_DICT = {"X" : X_CELL,
               "O" : O_CELL,
               " " : BLANK_CELL}


def main():
    play_again = True
    while play_again:
        game()
        play_again = ask_play_again()
    print("\nThank you for playing")


def game():
    state = [[" " for i in range(3)] for j in range(3)]
    print_board(state)
    winner = False
    x_turn = True
    while not winner:
        choice = get_choice(state)
        state = add_choice(state,choice,x_turn)
        print_board(state)
        winner = check_win(state)
        x_turn = not x_turn
    print("{} wins!".format(winner))


def ask_play_again():
    while True:
        query = input("\nWould you like to play again (Y/N)? >>> ").lower()
        if query in ("y","yes"):
            return True
        elif query in ("n","no"):
            return False


def get_choice(state):
    good = False
    while not good:
        choice = validate_input()
        good = check_if_choice_empty(state,choice)
    return choice


def check_if_choice_empty(state,choice):
    good = state[choice[0]][choice[1]] == " "
    if not good:
        print("Cell already taken.")
    return good


def validate_input():
    choice = None
    while choice not in [str(i) for i in range(1,10)]:
        if choice != None:
            print("Invalid selection.")
        choice = input("Please choose your cell (1-9) >>> ")
    choice = int(choice)-1
    return divmod(choice,3)


def add_choice(state,choice,x_turn):
    state[choice[0]][choice[1]] = "X" if x_turn else "O"
    return state


def print_board(state):
    print("\n"*13)
    for row in state:
        for i in range(4):
            print("".join(OPTION_DICT[col][i] for col in row))
    print("#########  "*3)


def check_win(state):
    for check in ("X","O"):
        for row in state:
            if all(col==check for col in row):
                return check
        for col in zip(*state):
            if all(row==check for row in col):
                return check
        if all(state[i][i]==check for i in range(3)):
            return check
        elif all(state[i][j]==check for i,j in [(2,0),(1,1),(0,2)]):
            return check


if __name__ == "__main__":
    main()

-Mek
User avatar
Mekire
 
Posts: 988
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Tic-Toc-Toe Game (Phyton 3.X.X)

Postby Somelauw » Mon Aug 19, 2013 7:26 pm

There are too many global variables. Global variables should be avoided as much as possible.
playerXMove and playerOMove are almost exact duplicates. Merge them to a function playerMove(type).
The same goed for checkX and checkY. Instead you should make a function check(type) and call it like check('x') or check('o').

Your board representation isn't really easy to work with.
An example of a better board representation would be:
Code: Select all
board = [['X', 'O', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]


Avoid recursion in most cases. Your playerXmove calls rePlayerXMove which on its turn calls playerXmove. This could create a recursion overflow in some cases. But, focus on the other points first.
Join the #python-forum IRC channel on irc.freenode.net!
Somelauw
 
Posts: 72
Joined: Tue Feb 12, 2013 8:30 pm

Re: Tic-Toc-Toe Game (Phyton 3.X.X)

Postby Tricky » Mon Aug 19, 2013 7:57 pm

Thanks for all this help, looking forward to improving my code. as i have never worked in a language simular to phyton i need to learn the functions and how statements at build, plus i didnt know that you could make multi-line strings, so i did my best and made one line strings and it became a huge mess. I know i still have alot to learn and alot about taking alot of my code off and learn to use "classes" and learn more use of funktions. This was aswell the first "real" project i did. else i just played around with setting up strings to form a sentence, this took me about 3 days to make (2-4 hours a day) so i dont think it is that bad though

Code: Select all
A="Hello"
B=", World!"
print(A+B)
Tricky
 
Posts: 2
Joined: Mon Aug 19, 2013 11:44 am


Return to Completed Scripts

Who is online

Users browsing this forum: No registered users and 2 guests

cron