2016-11-05 8 views
0

私はPythonを書く初心者です。私はユーザに動的な選択肢を作成しようとしています。彼らが望むオプションを選択し、それに基づいて機能を実行します。条件に基づいて変更されるオプションのリストを表示し、ユーザにそれらのオプションの1つを選択させてください

私の「ゲーム」は、5ガロンの樽に4ガロンを入れなければならないダイ・ハードから場面を再現しています。

ユーザーは、何も入っていない2本のボトルと水を利用して始めます。彼らが始めているので、彼らは2つのだけのオプションが必要です。

[1] Fill bottle A 
[2] Fill bottle B 
Select Option: 

コードが正しかった、とオプション1を選択したと仮定し、満たされたボトルAを、彼らが持っている次のオプションは次のようになります。

[1] pour bottle A into bottle B 
[2] Fill bottle B 
[3] Empty bottle A 
Select Option: 

ここに私の(おそらく恐ろしい)のコードは、これまでのところです:私は把握に苦労しています何

class Bottles(object): 
    amount = 0 
    def __init__(self,name,capacity,amount): 
     self.name = name 
     self.capacity = capacity 
     self.amount = amount 

    def AddWater(self,increase): 
     if (self.amount + increase) > self.capacity: 
      self.amount = self.capacity 
      print("Overflow! {0}'s at max capacity ({1} gallons)").format(self.name,self.capacity) 
     else: 
      self.amount = self.amount + increase 

    def RemWater(self,decrease): 
     if (self.amount - decrease) < 0: 
      self.amount = 0 
      print("Empty! {0} is now empty!").format(self.name) 
     else: 
      self.amount = self.amount - decrease 

def ShowOptions(): 
    available_options = [] 
    option_value = 1 

    print("Bottle A Amount: {0}").format(bottle_a.amount) 
    print("Bottle B Amount: {0}").format(bottle_b.amount) 

    print("Your options are as follows:") 
    if bottle_a.amount != bottle_a.capacity: 
     print("[{0}] Fill bottle A").format(option_value) 
     available_options.append(str(option_value)) 
     option_value += 1 

    if bottle_b.amount != bottle_b.capacity: 
     print("[{0}] Fill bottle B").format(option_value) 
     available_options.append(str(option_value)) 
     option_value += 1 

    if bottle_a.amount != bottle_a.capacity and bottle_b.amount > 0: 
     print("[{0}] Pour water in Bottle B into Bottle A").format(option_value) 
     option_value += 1 

    if bottle_b.amount != bottle_b.capacity and bottle_a.amount != 0: 
     print("[{0}] Pour water in Bottle A into Bottle B").format(option_value) 
     option_value += 1 

    if bottle_a.amount == 4 or bottle_b.amount == 4: 
     print("{0}] Defuse bomb.").format(option_value) 
     option_value += 1 

bottle_a = Bottles("Bottle A",5,3) # 5 gallon bottle 
bottle_b = Bottles("Bottle B",3,0) # 3 gallon bottle 

ShowOptions() 

は、その選択をお願いして、余分なOPTの全体の束を追加することなく、その機能を実行するために、両方の方法です毎回イオンチェック。

+0

図をあなたは、余分なチェックを回避し、その後構築し、それを使用する必要があるデータの種類:

はここでゲームが上記のアプローチで見ることができる方法の例です。 – cco

答えて

0

最初のitemが表示されるテキストで、2番目のitemがoptionが選択された場合に実行する関数であるペアのリストを作成できます。次に、オプションを一度だけ決定する機能をコーディングし、選択されたオプションを実行することは簡単です。

class Bottle(object): 
    def __init__(self,name,capacity,amount): 
     self.name = name 
     self.capacity = capacity 
     self.amount = amount 

    def fill(self): 
     self.amount = self.capacity 

    def empty(self): 
     self.amount = 0 

    def fill_from(self, bottle): 
     amount = min(self.capacity - self.amount, bottle.amount) 
     self.amount += amount 
     bottle.amount -= amount 

# Add all the possible options for given bottle to the list 
def add_bottle_options(options, bottle, other): 
    # Fill 
    if bottle.amount != bottle.capacity: 
     options.append(('Fill {}'.format(bottle.name), lambda: bottle.fill())) 

    # Empty 
    if bottle.amount: 
     options.append(('Empty {}'.format(bottle.name), lambda: bottle.empty())) 

    # Pour to 
    if bottle.amount != bottle.capacity and other.amount: 
     text = 'Pour water in {} into {}'.format(other.name, bottle.name) 
     options.append((text, lambda: bottle.fill_from(other))) 


bottle_a = Bottle("Bottle A", 5, 0) # 5 gallon bottle 
bottle_b = Bottle("Bottle B", 3, 0) # 3 gallon bottle 
ticking = True 

def defuse(): 
    global ticking 
    ticking = False 

while ticking: 
    print('Bottle A Amount: {}, capacity: {}'.format(bottle_a.amount, 
                bottle_a.capacity)) 
    print('Bottle B Amount: {}, capacity: {}'.format(bottle_b.amount, 
                bottle_b.capacity)) 

    print("Your options are as follows:") 

    # List of option text, function to execute tuples 
    available_options = [] 
    add_bottle_options(available_options, bottle_a, bottle_b) 
    add_bottle_options(available_options, bottle_b, bottle_a) 

    if bottle_a.amount == 4 or bottle_b.amount == 4: 
     available_options.append(('Defuse bomb', defuse)) 

    # Enumerate will return (number, item) tuples where the number starts 
    # from second parameter. Since items are (name, function) 
    # tuples themselves enumerate returns (number, (name, function)) 
    # tuples which we need to unpack so that we can use number and name 
    # for printing. (s, _) does nested unpacking so that name goes to 
    # variable s and function to _ which is a common name for throwaway data. 
    for i, (s, _) in enumerate(available_options, 1): 
     print('[{}] {}'.format(i, s)) 

    try: 
     # Ask user choice, convert it to int, subtract 1 since displayed 
     # options use 1-based indexing and execute the selected option 
     choice = input('Select option: ') 
     available_options[int(choice) - 1][1]() 
    except: 
     print('Invalid option') 

print('Congrats, you defused bomb') 
+0

まあ、それは素晴らしいです!それを読んで*理にかなっていますが、私はすべてをあまり理解していません。私はcodeacademyのレッスンの約87%で、ラムダではまだ作業していないので、それはおそらく私の欠けているキーです。このラインを私に少し説明できますか?私は理解していません 'のためのi、(s、_)の列挙(available_options、1): print(' [{}] {} 'フォーマット(i、s)) ' –

+0

私ができる最高の、それが助けて欲しい。いずれにしても、組み込み関数の詳細については、['enumerate'](https://docs.python.org/3.5/library/functions.html#enumerate)をチェックしてください。 [ラムダ式](https://docs.python.org/3.5/tutorial/controlflow.html#lambda-expressions)は匿名関数です。 – niemmi

関連する問題