顯示具有 Python 標籤的文章。 顯示所有文章
顯示具有 Python 標籤的文章。 顯示所有文章

2015年10月7日 星期三

[程式/Python] 俄羅斯方塊 Tetris

之前在Codecademy看完了python的課程後,想看看自己理解了多少,於是找了MIT的Python Course的功課和Project來做,這幾天沒發文就是去寫程式了,目前己完成所有Project。

其中一個我覺得很有趣的是自製 俄羅斯方塊 遊戲,我把它打包成執行檔了,載點如下:
>>俄羅斯方塊 下載<<

下載 俄羅斯方塊.rar 後,解壓縮並運行tetris.exe進行遊戲,其中會出現一個黑色畫面不用理會,玩完後關了它就好。

控制:
←↓→:移動方塊
↑:轉動方塊
空白鍵:直接落下

當遊戲進行到後期,畫面更新速度會加快,然後就會不定期出現一些Bug來阻礙大家遊玩∠( ᐛ 」∠)_,有發現的話請幫忙回報,我能處理的都會處理。(不過很多不是我的code有問題,似乎是Graphics Module的問題,這個我沒法處理)

完成這些Project的難點是Template都是用Python2寫的,我要把它改寫成Python3的格式,畢竟我也是一個月前第一次接觸Python,2和3的分別寫在不太熟識,結果很多時間花在翻譯code。

另外我也有完成 康威生命遊戲 ,不過這個好像沒那麼有趣所以不貼了。

遊戲畫面:

2015年9月20日 星期日

[程式/Python] 凱撒密碼 加密器 Caesar Cipher

凱撒密碼是移位密碼的一種,將英文字的各字母順移指定次數,例如ABE各順移兩次的話就會變成CDG。

以下是Python的code,這次沒有註解,因為寫的時候有點想睡,想寫快點,而且函數名稱都很明顯了,有看不懂再問吧:

 
def checkint(c):
    while True:
        try:
            c = int(c)
            return c
        except:    
            print ("Invaild value!")
            c = input("Enter shift value again:")

def checkempty(s):
    while s=="":
        print ("No sentence.")
        s = input("Enter sentence to encrypt again:")
    return s

def shiftletter(word, c):
    new_word = []
    for letter in word:
        temp=ord(letter)
        if temp in range(65, 91):
            temp+=c
            temp = (temp-65)%26+65
        elif temp in range(97, 123):
            temp+=c
            temp = (temp-97)%26+97
        new_word.append(chr(temp))
    return "".join(new_word)

def encode(Input, c):
    word_list = Input.split()
    new_word_list = []
    for word in word_list:
        new_word_list.append(shiftletter(word, c))
    return " ".join(new_word_list)

#My "Restart" option
def exit(ans):
    while True:
        ans = str(ans).lower()    
        if ans == "y":
            print ("See You!")
            input ("Press enter to continue")
            raise SystemExit()
        elif ans == "n":
            return "n"
        else:
            print ()
            print ("Invalid Input")
            ans = input("Exit? (y/n)")
#End of "Restart"

def main():
    Input = checkempty(input("Enter sentence to encrypt:"))
    c = checkint(input("Enter shift value:"))

    #for test
    #Input = "Mayday! Mayday!"
    #c = input("Enter shift value:")
    #end for test
    
    print ("The encoded phrase is:", encode(Input, c))


print ("Welcome to Caesar cipher!")
print ()
re = "n"
while re=="n":
    main()
    print ()
    re = exit(input("Exit? (y/n)"))
    print ()
    print ()



效果:


首先顯示歡迎字句,然後問要加密的句子,如果沒有輸入句子就會要你重新輸入。然後到輸入順移次數,如果輸入非整數就會顯示輸入無效,直至輸入為整數。之後就會輸出加密後的句子,數字和符號不會改變。最後問你是否離開,答y就會結束,答n的話就會再來一次。

2015年9月19日 星期六

[程式/Python] 猜字遊戲 Hangman

┳┻|_∧
┻┳|ω・) ♪
┳┻|⊂ノ

我用Python寫的第一個遊戲終於出來了,是猜字遊戲:

>>Hangman下載<<

下載Hangman EXE.rar後,解壓縮並運行hangman.exe進行遊戲,畫面大小請自己調整,我還不會調整∠( ᐛ 」∠)_


遊戲如下:


開始遊戲後會看到載入字庫的畫面,字庫word.txt的字可以自行增加,不過55900字已經夠玩了吧。下面會看到吊刑台,沒甚麼作用,只是用來顯示你有多快輸。
Word會顯示你猜對了的字母在該字的哪個位置,Guess是你猜過的字母,Misses是猜錯了的字母,Guess a letter要求玩家輸入一個字母。


猜錯的話就會開始出現吊頸男,上頭的guesses left會減少,減到0還沒猜到就結束,玩家輸,在0之前猜完就贏。


猜對了字母的話guesses left不會減少,可一直猜下去。


輸的畫面,輸了後會公佈答案,贏了也會就是了。



遊戲完結後會問你是否離開,只能答y或n,輸入其他會顯示輸入無效,答y的話遊戲會自動結束,答n的話會直接開始新遊戲。

code就不貼了,有人要我再貼吧。

2015年9月17日 星期四

[程式] Codecademy Python課程File Input/Output 5/9 Reflesh錯誤及解決方法

Codecademy Python 課程跑到File In/Out 5/9時,即使你的code打對了,它還是會出現以下錯誤:
Traceback (most recent call last):
  File "python", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'text.txt'

並要求你Reflesh頁面。

解決方法(意外地簡單):
先在畫面左邊選擇6/9的課程,然後重新回到5/9的課程,重新提交你的code。

2015年9月8日 星期二

[程式/Python] 小遊戲 - BattleShip Code分享

剛剛在Codecademy完成了BattleShip的練習,原本打算改成2P,不過我先把它改成Python34的格式再加入重新開始和結束的選項。老實說,這遊戲真的不太好玩,編碼如下:
from random import randint

#function for print out the board
def print_board(board):
    for row in board:
        print (" ".join(row))

#variable for restart
re=1

while (re==1):
    #generate a game board
    board = []
    for row in range(5):
        board.append(["O"]*5)

    ship_row = randint(0,len(board)-1)
    ship_col = randint(0,len(board[0])-1)

    print ("Battle Ship!")
    print_board(board)

    #for debug, del it after finish
    print ("(", ship_row, ",", ship_col, ")")

    #give 4 turns to guess
    for turn in range(4):
        print ()
        print ("Turn ",turn+1)
        guess_row = int(input("Guess Row:"))
        guess_col = int(input("Guess Col:"))

        #different result according to the guess 
        if guess_row == ship_row and guess_col == ship_col:
            board[guess_row][guess_col] = "W"
            print ()
            print ("Congratulations! You sunk my battleship!")
            print_board(board)
            break
        else:
            print ()
            if guess_row not in range(5) or guess_col not in range(5):
                print ("Oops, that's not even in the ocean.")
            elif board[guess_row][guess_col] == "X":
                print ("You guessed that one already.")
            else:
                board[guess_row][guess_col] = "X"
                print ("You missed my battleship!")
            print_board(board)
            if turn == 3:
                print ("Gome Over")
    print ()

    #variable for asking restart
    res=1
    while(res==1):
        response = input("Restart(Y/N)? ")
        print ()
        response = response.upper()
        if response == "Y":
            res=0
        elif response == "N":
            res=0
            re=0
        else:
            print ("Invalid Input")
            print ()

    print ()
    print ()
    print ()

raise SystemExit("See You!")



當中加入了while loop和raise SystemExit()來作重新開始和結束遊戲的選擇。

2015年8月26日 星期三

[程式/Python] 在Codecademy寫的第一個Python程序 : Pig Latin

最近試著在Codecademy學寫Python,這是我寫的第一個程序:


把英文單字的字頭放到最尾,然後在後面加上ay的暗語。

不過寫這個的時候還沒學到for loop怎麼寫,上網查了一下寫法再試一下,那個range(a,b)原來只到 i = b-1,(a,b)不由a到b,總覺得很不舒服。

後記:
原來到這邊不需要寫這個程式,之後的課程會一步步教,而且有教"string".[a:b],可以不用for來寫:3