2016-04-25 7 views
-2

while(True)関数がどのようにコードに当てはまるかを調べるのに苦労します。それは、コンピュータまたはユーザーが(最初にラウンドとしてユーザ入力)ポイントの所望の量に到達するまで、私はゲームループにしようとしていますとして使用する権利のことである場合も全くわからないWhile(True)ループを理解していない - Python 2.7

import random 


def main(): 

print 
print "----------------------------------" 
print "Welcome to Rock, Paper, Sciccors! " 
print "----------------------------------" 


rounds = input("How many points to win?: ") 

user_choice = input("Choose Rock = 1 , Paper = 2 or Sciccors = 3: ") 

user_score = 0 

computer_score = 0 



if user_choice == 1: 

    print "You chose Rock" 

elif user_choice == 2: 

    print "You chose Paper" 

elif user_choice == 3: 

    print "You chose Sciccors" 

else: 

    print " Wrong! Choose 1, 2 or 3!" 



computer_choice = random.randrange(1, 4) 


if computer_choice == 1: 

    print "Computer chose Rock" 

elif computer_choice == 2: 

    print "Computer chose Paper" 

elif computer_choice == 3: 

    print "Computer chose Sciccors" 


def checkResults(computer_choice, user_choice): 

    checkResults = computer_choice - user_choice 


    if computer_choice - user_choice == 0: 

     print("Draw!") 

     user_score += 1 

     computer_score += 1 

    elif computer_choice - user_choice == 1 or computer_choice - user_choice  == -2: 

     print("Computer wins") 

     computer_score += 1 

    elif computer_choice - user_choice == -1 or computer_choice - user_choice == 2: 

     print("You win!") 

     user_score += 1 


print (" Computer {} , You {}" .format(computer_score, user_score)) 

while(True): 

if computer_score == rounds or user_score == rounds: 

    main() 
else: 
    break 
+0

構文エラーなしで実行できるコードで回答を更新できますか?空の行を削除することをお勧めします。 – totoro

答えて

1

あなたは

while computer_score == rounds or user_score == rounds: 

    ' Your code returning computer_score and user_score 

基本的while Trueだけbreak文またはキーボード割り込み経由を使用して終了することができます無限ループです:このビット短くすることができます。

0

while True:は、コマンドbreakでのみ停止できる無限ループです。あなたの例では、main()メソッド(前に定義した通り、def main():と言う)を無限に実行するループを作成しました。ループが終了する唯一の時間は、プロセスを終了する(つまり、Windowsのタスクマネージャを使用する)場合、またはcomputer_scoreuser_scoreの両方がroundsと等しくならない場合です(elseステートメントは2行目から最後の行までを意味します)。これが起こると、プログラムはbreakを呼び出し、強制的にループを強制終了し、ファイルの最後まで移動します(プログラムを終了します)。

while True ... breakループを使用することは、「エレガントな」とは見なされないため、プログラマが戸惑うことがあることに注意してください。行うには完全に罰金のコードですが、最後の数行を再書き込みするための別の方法は次のとおりです:

while computer_score==rounds or user_score==rounds: 
    main() 

これはcomputer_scoreuser_scoreまでwhileループを実行することで、同じ結果を達成両者が等しくないroundsを行います。その時点で、whileループは完全に終了し、ファイルの最後まで到達することでプログラムを終了します。

関連する問題