2014-06-07 86 views
-4

因此,我正在製作一個簡單的遊戲,其中用戶從邊界國家攻擊一個國家,但我遇到了一個問題,因爲我無法想出一個簡單的方法來擴展此代碼,因爲我正在計劃在遊戲中增加更多的國家。最終產品將與風險類似,但如果一切按計劃進行,則會更加複雜。此代碼正常工作,但我期望更容易擴展。把這看作是一個粗略的草案。我該如何循環?

countries=['USA','MEXICO','CANADA'] 

#ignore MILITARYGROWTHRATE, that will be put to use later in production, I just added it in early 

USA_REGION_DATA={'Bordering':['MEXICO','CANADA'],'MILITARYGROWTHRATE':1.03} 
MEXICO_REGION_DATA={'Bordering':['USA'],'MILITARYGROWTHRATE':1.01} 
CANADA_REGION_DATA={'Bordering':['USA'],'MILITARYGROWTHRATE':1.01} 

def attack(origin,target): 
    '''Origin is where you are attacking from, 
    target is who you are attacking''' 
    x=origin.upper() 
    y=target.upper() 
    if x not in countries: 
     print("You must attack from somewhere!") 
    elif x=='USA': 
     if y not in USA_REGION_DATA['Bordering']: 
      print("Not a valid target") 
     else: 
      print("Attack is underway!") 
    elif x=='MEXICO': 
     if y not in MEXICO_REGION_DATA['Bordering']: 
      print("Not a valid target") 
     else: 
      print("Attack is underway!") 
    elif x=='Canada': 
     if y not in CANADA_REGION_DATA['Bordering']: 
      print("Not a valid target") 
     else: 
      print("Attack is underway!") 

print("Are you attacking from the USA, Mexico, or Canada?") 
origin=raw_input() 
if origin.upper()=='USA': 
    print("Are you attacking Mexico or Canada?") 
    target=raw_input() 
    print("Are you sure you want to attack "+target+"? (Yes or No)") 
    answer=raw_input() 
    if answer.upper()=='YES': 
     attack(origin,target) 
    else: 
     print("You'll never get anything done by sitting around...") 
else: 
    print("Are you sure you want to attack the USA?(Yes or No)") 
    if raw_input().upper()=='YES': 
     target='USA' 
     attack(origin,target) 
    else: 
     print("You'll never get anything done by sitting around...") 
+6

這個問題看似已關閉 - 因爲它屬於Code Review StackExchange? – Dair

+0

你可以閱讀關於OOP。 – Christian

+0

我不知道Code Review StackExchange,直到我閱讀你的評論,說實話。如果看起來更合適,我會檢查一下並提出問題。感謝您的快速響應! – Jackson

回答

3

你幾乎肯定要更換你的具體變量與數據結構(如字典)每個國家使用該國的名字作爲重點。所以,而不是指USA_REGION_DATA,你會查找REGION_DATA["USA"]。這可以擴展到任何國家,因爲您可以簡單地向字典添加新的值。

REGION_DATA = { "USA": {'Bordering':['MEXICO','CANADA'],'MILITARYGROWTHRATE':1.03}, 
       "MEXICO": {'Bordering':['USA'],'MILITARYGROWTHRATE':1.01}, 
       "CANADA": {'Bordering':['USA'],'MILITARYGROWTHRATE':1.01} 
       } 

attack功能(和其他人)將是通用的,與個別國家沒有特殊的外殼:

你可以像初始化

def attack(origin,target): 
    '''Origin is where you are attacking from, 
    target is who you are attacking''' 
    x=origin.upper() 
    y=target.upper() 
    if x not in REGION_DATA: 
     print("You must attack from somewhere!") 
    elif y not in REGION_DATA[x]['Bordering']: # extra indexing by x here 
     print("Not a valid target") 
    else: 
     print("Attack is underway!") 
+0

這是完美的!我剛開始編寫代碼,所以我希望得到一個很好解釋的解決方案,這點很重要。謝謝! – Jackson