第11篇!第11篇!第11篇!!!说实话,我真没想过文章会更新到10以上。可是,来都来了,咱们的编程仍是要继续的嘛!今天的主题:配置文件!首先,上篇连接:从0开始用python写一个命令行小游戏(十)python
首先,我要强调一点:全部须要变量匹配的地方(相似别的语言中的switch
),均可以用配置文件(主要是字典)。好比,个人游戏里面种植植物时匹配植物名称。既然这个配置文件须要与植物的类交互,因此要使用Python
格式,而非JSON
或别的语言。试试看:编程
# config.py import game_obj as o config = { "plant_name": { 's': o.Sunflower, 'p': o.Peashooter, } }
而后把game.Game.process_command()
的try-except-else
中的else
改成:segmentfault
from config import config if plant_type in config["plant_name"].keys(): config["plant_name"][plant_type](x, y) # 获取类型并调用构造方法
怎么样,是否是优雅不少呢?但别忘了,咱们还有一个地方有急需switch
语句:僵尸配置。dom
将config.py
改成:命令行
import game_obj as o config = { "plant_name": {} # 同前 "zombie_name": { "zombie": o.Zombie, "kicker": o.KickerZombie, } }
而后将game.Game.step()
改成:code
def step(self, commands): # 其他同前 if str(self.step_num) in self.steps.keys(): action = self.steps[str(self.step_num)] from config import config from random import randint action_list = action.split() if action_list[-1] in config["zombie_name"].keys(): config["zombie_name"][action_list[-1]](9, randint(0, 4), action_list[0] == 'exit')
好了,今天就这样吧。游戏
下次···对了,多关卡!敬请继续关注!get