Make a simple tic-tac-hole game with Python

Source: Internet
Author: User
In this tutorial, I'll show you how to use Python for a tic-tac-hole game. This will include functions, lists, if statements, while loops, for loops, error handling, and so on.

First, we will create two functions, and the first function will print out the background template for the Tic-Tac-string game:

Def print_board (): For    I in range (0,3):        for J in Range (0,3):            print map[2-i][j],            if J! = 2:                print "|", C5/>print ""

Here we use two for loops to iterate over a map list variable named. This variable is a two-dimensional list that will hold information for each location.

Since I will follow the keypad number to the control position (as you will see later), so the first value we set it to (2-i) , and then we want to use "|" to split our position, so in each position after printing, we give him a print "|" , we are here print map[2-i][j], Commas are used to ensure that they are printed on the same line.

Now, this function can print the background of a game, it looks like this drop:

  |   |     |   |     |   |
X | X |   O | X | O   | O | X
X | X | X x | X | X x | X | X

Next, we create a check_done() function that checks to see if the game is over after each round, and if the game is over, returns true and prints a message.

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]! = "":        pri NT turn, "won!!!"        return True if "map[0" and "not in map[1] and" "Not in    map[2]:        print" Draw "        return true
  
   return False
  

First, we will check the horizontal and vertical direction, is not three is the same, and is not empty (so he does not think that three consecutive empty lines are eligible), and secondly, we check the diagonal in the same way.

If one line matches the 8 lines, then the game ends and prints "Won!!!" and return True , at the same time pay attention to turn this variable, its role is to judge the current chess is that side, the final display of the message will be "x win!!" "or" O win!! ”。

The function then determines that if no position is empty, it means that no one can win the game (as previously judged), then a draw is printed and returned True .

If there are no such cases, then the game is not over, return False .

OK, now that we have two functions, let's start with our real program, first to create three variables:

turn = "X" map = [["", "", ""], ["," "," "], [", "", ""       ]]done = False

I have already told you that these three variables are ripe, if you forget, then look at the following:

    • Turn: Who's gone?


    • Map: The background of the game


    • Done: This game has a wooden end

Next, write this:

While do! = true:    print_board ()    print turn, "' s turn"    print    moved = False while moved!    = true:

There is a while loop, and until done is true, we print out who is going.

Then create a variable named to check that the player is not moving, and moved if not, go to the next loop.

Next, we print how the player should go:

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

Next:

Try:    pos = Input ("SELECT:")    if POS <=9 and POS >=1:

We want the player to enter a number, and then we check whether it is between 1~9, and we have to add an error handling, such as player input "Hello", the program can't just quit.

Now, we need to check if this step of his walk can go:

y = pos/3x = pos%3if x! = 0:    x-=1else:    x = 2    Y-=1

Hah, open your eyes, first we get a value of x and Y, and then use them to check if the position he wants is empty, and then I'll explain to you x and y they're swollen work:

    • Position 1:y = 1/3 = 0, X = 1%3 = 1; X-= 1 = 0


    • Position 2:y = 2/3 = 0, X = 2%3 = 2; X-= 1 = 1


    • Position 3:y = 3/3 = 1, X = 3%3 = 0; X = 2, Y-= 1 = 0


    • ......

The following self-calculation ah, I directly on the conclusion (by, Hexo Default template does not show the table Ah, I am in the MOU above the editing more beautiful than the following!) ):

y\x x=0 x=1 x=2
y=2 7 8 9
Y=1 4 5 6
Y=0 1 2 3

Aha, this position is the same as what we typed!

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

Now we have done most of the work, but there are several lines of code:

Map[y][x] = turnmoved = Truedone = Check_done () if done = = False:    if turn = = "X":        turn = "O"    else:        turn = " X "except:    print" need to add a numeric value "

Well, we're going to copy the moved variable to true and check if the end is over, and the wood has the end of the words change character to go away.

OK, almost over, if you just want CTRL + C and CTRL + V, below is the whole code, I hope you learned something, (^_^)/~~ bye.

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] = = ma            P[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]! = "": PR        int turn, "won!!!"    return true if "map[0" and "not in map[1] and" "Not in Map[2]: print" Draw "return True return Falseturn = "X" map = [["", "", ""], ["," "," "], [", "", ""]]done = falsewhile done! = True:p Rint_board () Print turn, "' s turn" print moved = False while moved! = true:print "Please select Positi On ' typing in a ' number between 1 and 9, see below for which number this is which position ... "print" 7|8| 9 "PrinT "4|5|6" print "1|2|3" Print Try:pos = Input ("SELECT:") if POS <=9 and PO                s >=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 do = = False:                            if turn = = "X": Turn = "O" Else: turn = "X" Except:print "You need to add a numeric value"

Source: Vswe

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.