我该如何循环呢?

时间:2014-06-07 06:23:53

标签: python loops canopy

所以我正在制作一个简单的游戏,其中用户攻击来自边境国家的国家,但我遇到了一个问题,我想不出一个简单的方法来扩展这个代码,因为我正在计划在游戏中添加更多国家。最终产品将类似于Risk,但如果一切按计划进行,则会更复杂。这段代码工作正常,但我希望扩展更容易。把它想象成草稿。

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...")

1 个答案:

答案 0 :(得分: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!")
相关问题