Python 我如何循环这个?
因此,我正在制作一个简单的游戏,其中用户从一个边境国家攻击一个国家,但我遇到了一个问题,我想不出一个简单的方法来扩展这段代码,因为我计划在游戏中添加更多的国家。最终产品将类似于风险,但如果一切按计划进行,将更加复杂。这段代码工作得很好,但我希望它更易于扩展。把这看作是一份草稿Python 我如何循环这个?,python,loops,canopy,Python,Loops,Canopy,因此,我正在制作一个简单的游戏,其中用户从一个边境国家攻击一个国家,但我遇到了一个问题,我想不出一个简单的方法来扩展这段代码,因为我计划在游戏中添加更多的国家。最终产品将类似于风险,但如果一切按计划进行,将更加复杂。这段代码工作得很好,但我希望它更易于扩展。把这看作是一份草稿 countries=['USA','MEXICO','CANADA'] #ignore MILITARYGROWTHRATE, that will be put to use later in production, I
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...")
几乎可以肯定的是,您希望用一个数据结构(例如使用国家名称作为键的字典)替换每个国家的特定变量。因此,您不必参考美国地区数据,而应该查找地区数据[USA]。这可以扩展到任意数量的国家,因为您可以简单地向字典添加新值 您可以使用以下方法对其进行初始化:
REGION_DATA = { "USA": {'Bordering':['MEXICO','CANADA'],'MILITARYGROWTHRATE':1.03},
"MEXICO": {'Bordering':['USA'],'MILITARYGROWTHRATE':1.01},
"CANADA": {'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 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!")
这个问题似乎离题了,因为它属于Code Review StackExchange?您可以阅读OOP。老实说,在阅读您的评论之前,我不知道Code Review StackExchange。我会检查一下,如果这个问题看起来更合适的话,我会提出这个问题。感谢您的快速回复!这太完美了!我刚开始编码,所以我希望有一个解释得很好的解决方案,这是现场。谢谢