2014-06-07 55 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