+ Reply to Thread
Results 1 to 7 of 7

Thread: Tic-Tac-Toe in Python

  1. #1
    Join Date
    Apr 2009
    Location
    Uppsala, Sweden
    Posts
    9,547
    Blog Entries
    5
    Rep Power
    98

    Tic-Tac-Toe in Python

    I will in this tutorial show how to make a Tic-Tac-Toe game in Python. It will include functions, lists, if statements, while loops, for loops, error handling etc.



    We'll begin with creating two functions, the first one will print out the Tic-Tac-Toe board:



    Code:
    def print_board():
        for i in range(0,3):
            for j in range(0,3):
                print map[2-i][j],
                if j != 2:
                    print "|",
            print ""

    Here we uses two for loops to go through a list variable called map. This variable is a two dimensional list which will hold the info about what's in each position.

    Since I (as you will see later) uses the position from the numpad the lowest numbers will come last (at the bottom) we have to inverse the first value (2-i). Then we want to print a "|" as s separator between the squares we do so if j != 2 so we don't get a separator at the end of each line. Then when the line is finished we prints "" just so we continue on a new line since we used the comma ("print map[2-i][j],") to stay on the same line.

    So now this function could print a board looking something like these examples:

    Code:
      |   |   
      |   |   
      |   |
    Code:
    X | X |   
    O | X | O 
      | O | X
    Code:
    X | X | X 
    X | X | X 
    X | X | X


    Then we have the check_done() function which we will use after each turn to see if the game is over, if so we returns True and prints out a message.



    Code:
    def check_done():
        for i in range(0,3):
            if map[i][0] == map[i][1] == map[i][2] != " " \
            or map[0][i] == map[1][i] == map[2][i] != " ":
                print turn, "won!!!"
                return True
            
        if map[0][0] == map[1][1] == map[2][2] != " " \
        or map[0][2] == map[1][1] == map[2][0] != " ":
            print turn, "won!!!"
            return True
    
        if " " not in map[0] and " " not in map[1] and " " not in map[2]:
            print "Draw"
            return True
            
    
        return False

    First we check if all 3 squares in all horizontal and vertical lines are the same and not " ". This is so it won't think an completely empty line is a line with 3 in a row. Then it checks the two diagonally lines in the same way. If at least one of these 8 lines are a winning line we will print out turn, "won!!!" and also return the value True. the turn variable will hold which player who's in turn so the message will be either "X won!!!" or "O won!!!".

    Then we check if none of the squares still has the value " ". If it's so it means all squares are filled and that nobody have won(since we already have tested if anyone won) so therefor the program prints out "Draw" and then returns True since the game is over.

    If none of this happens the function should return False since the game is not over yet.





    Now we're done with the two functions and may therefor start with the "real" program. Firstly we have to create 3 variables:


    Code:
    turn = "X"
    map = [[" "," "," "],
           [" "," "," "],
           [" "," "," "]]
    done = False
    I have already told you what these 3 does, but If you have forgot:
    • turn is whose turn it is.
    • map is the board
    • done is if we're done or not
    .





    And now, write this:


    Code:
    while done != True:
        print_board()
        
        print turn, "'s turn"
        print
    
        moved = False
        while moved != True:
    So here we have a while loop which will continue to loop until done is equal to True. As long as done = False the program will loop one more time when the users have made a move. The we prints out whose turn it is and then creates a variable called moved. The next loop is used to see if the player did a move or not, if it didn't come back here to prompt the user to try again.




    Then we just prints how the players should do to play:

    Code:
            print "Please select position by typing in a number between 1 and 9, see below for which number that is which position..."
            print "7|8|9"
            print "4|5|6"
            print "1|2|3"
            print




    Then...

    Code:
            try:
                pos = input("Select: ")
                if pos <=9 and pos >=1:
    We want the user to select the number and then we check if it's between 1 and 9. But we also adds an error handling so the program won't quit just because an error occurs when the user types a non-number (Like "Hello").






    Now we need to check if this move is possible:



    Code:
                    Y = pos/3
                    X = pos%3
                    if X != 0:
                        X -=1
                    else:
                         X = 2
                         Y -=1
                        
                    if map[Y][X] == " ":

    First we gets a X value and a Y value and then use them to check if the square the user wants to use is empty, I will now show you how the calculation of X and Y works.




    So with the calculations of X and Y we get the position of the square like this:



    ...which is exactly the same as the instruction we typed earlier:


    Code:
            print "7|8|9"
            print "4|5|6"
            print "1|2|3"



    Now we have done most of it but we have some lines left:


    Code:
                        map[Y][X] = turn
                        moved = True
                        done = check_done()
    
                        if done == False:
                            if turn == "X":
                                turn = "O"
                            else:
                                turn = "X"
                    
                
            except:
                print "You need to add a numeric value"
    So we store the current users "name" at the right position (with the X and Y values), set move to True, check if we're done and stores that in done. If the game isn't over, change who's next to move and then we have two lines to print an error message if the try block failed in some way.




    That was pretty much it, here comes the whole code if you just want to copy-paste it all, hope you learned something. Bye




    Code:
    def print_board():
        for i in range(0,3):
            for j in range(0,3):
                print map[2-i][j],
                if j != 2:
                    print "|",
            print ""
    
    
    def check_done():
        for i in range(0,3):
            if map[i][0] == map[i][1] == map[i][2] != " " \
            or map[0][i] == map[1][i] == map[2][i] != " ":
                print turn, "won!!!"
                return True
            
        if map[0][0] == map[1][1] == map[2][2] != " " \
        or map[0][2] == map[1][1] == map[2][0] != " ":
            print turn, "won!!!"
            return True
    
        if " " not in map[0] and " " not in map[1] and " " not in map[2]:
            print "Draw"
            return True
            
    
        return False
    
    
    
    
    
    turn = "X"
    map = [[" "," "," "],
           [" "," "," "],
           [" "," "," "]]
    done = False
    
    
    while done != True:
        print_board()
        
        print turn, "'s turn"
        print
    
        moved = False
        while moved != True:
            print "Please select position by typing in a number between 1 and 9, see below for which number that is which position..."
            print "7|8|9"
            print "4|5|6"
            print "1|2|3"
            print
    
            try:
                pos = input("Select: ")
                if pos <=9 and pos >=1:
                    Y = pos/3
                    X = pos%3
                    if X != 0:
                        X -=1
                    else:
                         X = 2
                         Y -=1
                        
                    if map[Y][X] == " ":
                        map[Y][X] = turn
                        moved = True
                        done = check_done()
    
                        if done == False:
                            if turn == "X":
                                turn = "O"
                            else:
                                turn = "X"
                    
                
            except:
                print "You need to add a numeric value"
    Last edited by Vswe; 10-05-2009 at 02:45 PM.

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Location
    Advertising world
    Posts
    Many

     
  3. #2
    Jordan Guest

    Re: Tic-Tac-Toe in Python

    Wow, neat! I didn't know you were learning Python as well.
    +rep

  4. #3
    Join Date
    Apr 2009
    Location
    Uppsala, Sweden
    Posts
    9,547
    Blog Entries
    5
    Rep Power
    98

    Re: Tic-Tac-Toe in Python

    I learned it yesterday. Did you know I only need one day to learn a programming language?

  5. #4
    Join Date
    Jul 2008
    Location
    Somewhere that is shorter to write than "In the gloomy shadows of my personal namespace"
    Posts
    10,725
    Blog Entries
    2
    Rep Power
    90

    Re: Tic-Tac-Toe in Python

    I hereby challenge you to learn C++ in one day

    +rep, that's a nice tutorial
    Hey! Check out my new Toyota keyboaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

  6. #5
    Join Date
    Aug 2009
    Location
    ~/
    Posts
    918
    Rep Power
    19

    Re: Tic-Tac-Toe in Python

    Tried it out, Very Nice +rep

    I've been slowly learning Python
    since I started here on the forum.

    You're very sharp Vswe , I'm much slower on
    the uptake , hope you can help me out when I need it.

  7. #6
    Join Date
    Apr 2009
    Location
    Uppsala, Sweden
    Posts
    9,547
    Blog Entries
    5
    Rep Power
    98

    Re: Tic-Tac-Toe in Python

    Sure I will help you if you need help, debtboy. Thanks all of you for the +rep

  8. #7
    Join Date
    Jul 2006
    Posts
    16,491
    Blog Entries
    75
    Rep Power
    143

    Re: Tic-Tac-Toe in Python

    Nicely done. +rep

    I agree that some languages take longer to learn than others, though.
    Programming is a branch of mathematics.
    My CodeCall Blog | My Personal Blog

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Advanced Python, part 1: Extending Python with C
    By spyder in forum Python Tutorials
    Replies: 0
    Last Post: 07-31-2010, 09:36 AM
  2. Replies: 11
    Last Post: 07-31-2010, 12:52 AM
  3. Power Of Python - What Has Been Written In Python?
    By Raja Sekharan in forum Python
    Replies: 7
    Last Post: 02-02-2009, 11:55 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts