0

while ループと if を使用してサイコロ ゲームを作成しようとしています。私はこれを成功させましたが、数字4、6、または12が入力されていない場合、無効な選択を示し、diceChoiceを再度尋ねるようにゲームをプログラムする方法を理解しようとしています. 誰でも助けることができますか?

これまでのところ...

rollAgain = "Yes" or "yes" or "y"

while rollAgain == "Yes" or "yes" or "y":
    diceChoice = input ("Which dice would you like to roll; 4 sided, 6, sided or 12 sided?")
    if diceChoice == "4":
        import random 
        print("You rolled a ", random.randint(1,4)) 
    if diceChoice == "6":
        import random
        print("You rolled a ", random.randint(1,6))
    if diceChoice == "12":
        import random
        print("You rolled a ", random.randint(1,12))

    rollAgain = input ("Roll Again?") 
print ("Thank you for playing")
4

4 に答える 4

3

Whileループを修正し、すべての繰り返しを片付けました。import ステートメントを先頭に移動しました。rollAgain と diceChoice により多くのオプションを許可するように構造化されています。

import random

rollAgain = "Yes"

while rollAgain in ["Yes" , "yes", "y"]:
    diceChoice = input ("Which dice would you like to roll; 4 sided, 6, sided or 12 sided?")
    if diceChoice in ["4","6","12"]:
        print("You rolled a ",random.randint(1,int(diceChoice)))
    else:
        print "Please input 4,6, or 12."
    rollAgain = input ("Roll Again?") 

print ("Thank you for playing")

この種の割り当てを行う:

rollAgain = "Yes" or "yes" or "y"

不要 - 最初の値のみが入力されます。この変数のいずれかを選択します。その目的のために必要なのは 1 つだけです。

この種の割り当ては、ここでも機能しません。

while rollAgain == "Yes" or "yes" or "y":

これも最初の値のみをチェックします。他のポスターが行ったように分割するか、上記のコードのリストのようにすべてを組み込む別のデータ構造を使用する必要があります。

于 2013-08-01T17:02:27.783 に答える
1

上部にランダムに一度だけインポートする必要があります

import random  #put this as the first line

rollAgain 宣言は、1 つの値にのみ設定する必要があります

rollAgain = "yes"  # the or statements were not necessary

後続の条件で行うのを忘れました。これrollAgain ==はより簡単な方法です

while rollAgain.lower().startswith("y"):  #makes sure it starts with y or Y

無効な入力ステートメントを実行するにはelif:、 andelse:ステートメントを使用して単純にすることができます

if diceChoice == "4":
    print("You rolled a ", random.randint(1,4)) 
elif diceChoice == "6":
    print("You rolled a ", random.randint(1,6))
elif diceChoice == "12":
    print("You rolled a ", random.randint(1,12))
else:
    print("Invalid Input, please enter either 4, 6, or 12")

あなたは基本的にこれを言っていたので、あなたの古いwhileループは決して終了しませんでした

while rollAgain == "Yes" or True or True  #because non-empty strings are treated as True

ステートメントについて尋ねたので編集inします。ここに簡単な例を示します

>>>5 in [1,2,3,4]
False
>>>5 in [1,2,3,4,5]
True

このステートメントは、変数がリスト内にあるかどうかを確認する他の言語のinステートメントに似ていますcontains()

ただし、返されたリストに5ないため、リストにあるので返されます[1,2,3,4]False
5[1,2,3,4,5]True

特に、変数が一連のオプション内にあることを確認したい場合は、コード内のいくつかの場所でこれを使用できます。シンプルにするためにお勧めしませんでした。

于 2013-08-01T17:01:51.973 に答える
0
diceChoice = None
while diceChoice not in ["4","12","6"]:
    diceChoice = input("enter choice of dice(4,6,12)")
print "You picked %d"%diceChoice
于 2013-08-01T17:04:03.983 に答える