2016-03-28 18 views
0

所以我是新手編程,並從一個建議開始學習python,我一直在學習Python python的艱辛方式和代碼學院。Python:在py2exe轉換後保持遊戲運行

我已經從代碼學院製作了豬拉丁遊戲,並稍微調整了它,所以它保持循環,但是一旦我將它與py2exe的幫助下轉換爲在Windows中運行exe文件,它不再有效,我只是想知道是否有人可以指示我如何稍微改變腳本以適應工作的正確方向。

print "Let's do some Pig Latin!" 
pyg = 'ay' 

original = raw_input('Enter a word:') 

word = original.lower() 
first = word[0] 
new_word = word + first + pyg 


if len(original) > 0 and original.isalpha(): 
    print new_word [1:] 
    again = raw_input('Would you like to play again? Y/N \n').upper() 
else: 
    print 'You were supposed to enter a word!,Try again' 
    execfile ('pig.py') 

if again == 'Y': 
    execfile ('pig.py') 
else: 
    print 'Goodbye!' 

見它適用於只是重新運行具有的execfile腳本整個事實,但顯然這是行不通的exe文件,我看了一些其他的問題和答案,但因爲我已經有劇本一種工作讓我感到困惑,我需要幫助理解我將如何重構腳本。

感謝您提前提供任何幫助的人。

回答

0

您應該使用while循環,而不是重新執行該文件的:

should_run = True 
print "Let's do some Pig Latin!" 
while should_run: 
    pyg = 'ay' 

    original = raw_input('Enter a word:') 

    word = original.lower() 
    first = word[0] 
    new_word = word + first + pyg 


    if len(original) > 0 and original.isalpha(): 
     print new_word [1:] 
     again = raw_input('Would you like to play again? [Y/N] \n').upper() 
     while again not in "NY": 
      again = raw_input("Invalid input. Play again? [Y/N] ").upper() 

     should_run = "NY".index(again) # If again is Y, should_run is 1 (True). Otherwise, it is 0 (False) 
    else: 
     print 'You were supposed to enter a word!,Try again' 
+0

這個工作!謝謝你的幫助 只要我明白並從中學習,我就會看到兩個新功能,我之前沒有使用過'Not in'和'.index()' 發生了什麼?這是否反饋給while函數以使「?」中的任何內容都存在,如果不是,它會運行這個while? 因此,在理論上我沒有能夠輸入「NY1234XLZ」,並且好像用戶輸入了腳本中的任何一個腳本,但是如果它在這個範圍之外,它會執行一段時間。 與.index()我不太清楚我理解那個那裏發生了什麼。 再次謝謝。 – Kingbuttmunch

+0

你對'不在'是正確的。 Python幾乎讀到它是如何用英語閱讀的。如果'again'既不是'N'也不是'Y',while循環會做另一次迭代。對於'.index()',它將返回首次出現的字符串的索引。如果'再次'是'Y',它會返回'1',因爲'NY'[1]'是'Y'。 'N'將會是'0'。布爾(「真」和「假」)實際上只是整數。 Zero的布爾值爲「False」,任何其他數字的布爾值爲「True」,所以如果'again'爲'Y','should_run'爲'1'或'True'。如果'again'是'N','should_run'將是'0'或'False'。 – zondo