用 Python 做個簡單的井字遊戲

Byron發表於2013-07-29

  在這個教程中,我將展示如何利用Python來做一個井字遊戲。這將包括函式、列表、if語句、while迴圈、for迴圈以及錯誤處理等等。

  首先,我們將建立兩個函式,第一個函式將會列印出井字遊戲的背景模板:

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 ""

  在這裡,我們使用了兩個for迴圈,要遍歷一個名為map的列表變數。這個變數是一個二維列表,將儲存每個位置的資訊。

  由於我會按照小鍵盤的數字來進行對照位置(稍後你會看到),所以第一個值我們把它設為(2-i),然後我們想用"|"來進行分割我們的位置,所以在每個位置列印完之後,我們給他列印一個"|",我們在這裡print map[2-i][j],使用了逗號,以保證他們在同一行被列印出來。

  現在,這個函式可以列印一個遊戲的背景啦,它看起來是這個樣子滴:

  |   |   
  |   |   
  |   |
X | X |   
O | X | O 
  | O | X
X | X | X 
X | X | X 
X | X | X

  接下來,我們建立一個check_done()函式,它會在每輪結束之後檢查遊戲是否結束了,如果遊戲結束,那麼返回True並列印一條訊息。

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

  首先,我們會檢查水平和垂直方向,是不是有三格是相同、並且不為空(所以他不會認為連續三個空行是符合條件的),其次,我們以相同的方式來檢查對角線。

  這8行如果有一行符合條件,那麼遊戲結束並且列印出“Won!!!”並返回True,同時注意turn這個變數,它的作用是判斷現在下棋的是那一方,最終展現出來的訊息將會是“X贏了!!”或“O贏了!!”。

  接下來這個函式會判斷假如沒有一個位置是空的,那麼就意味著沒有人能夠贏得比賽(前面判斷過了),那麼就列印出平局,並且返回True

  如果沒有上述兩種情況,那麼遊戲還沒結束,返回False

  OK,現在我們有了兩個函式,接下來開始我們真正的程式,首先來建立三個變數:

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

  我已經告訴過你這三個變數是熟麼意思了,假如你忘了的話,那麼看看下面:

  • turn:該誰走了
  • map:遊戲的背景地圖
  • done:這個遊戲到底有木有結束

  接下來,這樣寫:

while done != True:
    print_board()

    print turn, "'s turn"
    print

    moved = False
    while moved != True:

  裡面有一個while迴圈,直到done為True為止,我們列印出該輪到誰走了。

  然後建立一個名為moved的變數,檢查玩家是不是移動了,如果沒有移動,則進入下一個迴圈。

  接下來,我們列印玩家該怎樣去下:

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:

  我們希望玩家輸入一個數字,然後我們檢查是不是在1~9之間,同時,我們還得增加一個錯誤處理,比如玩家輸入”Hello”,程式不能就這麼退出了。

  現在,我們需要檢查他走的這一步能不能走:

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

  hah,睜大眼睛啦,首先我們得到一個X和Y的值,然後使用他們來檢查,他要下的那個位置是不是空的,接下來我會向你解釋X和Y他們是腫麼工作的:

  • 位置1:Y = 1/3 = 0, X = 1%3 = 1; x -= 1 = 0
  • 位置2:Y = 2/3 = 0, X = 2%3 = 2; X -= 1 = 1
  • 位置3:Y = 3/3 = 1, X = 3%3 = 0; X = 2, Y -= 1 = 0
  • ……

  下面的自己算啊,我直接上結論(靠,Hexo預設的模板不顯示錶格啊,我在mou上面編輯的時候比下面的漂亮多了!):

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

  aha,這個位置和我們鍵入的是一樣的!

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

  現在我們完成大部分工作了,但是還有幾行程式碼:

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"

  嗯,我們給moved變數複製為True,並檢查是否結束了,木有結束的話變換角色換下一個人走。

  OK,差不多結束了,假如你只是想Ctrl+C 和 Ctrl+V的話,下面是全部的程式碼,希望你學到了點什麼,( ^_^ )/~~拜拜。

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"

  原文出處: Vswe

相關文章