今天我時間有點緊張,因此不說廢話了,直接進入正題。前做連接:python
上次咱們的Game
類是這樣的:json
import game_obj as o class Game: def __init__(self): o.sunlight = 50 o.board = [0] * 10 self.sunlight = o.sunlight self.board = o.board import json with open("level.json") as fr: self.steps = json.load(fr) def step(self): print("Sunlight: %d." % self.sunlight) print("Current state:") for obj in self.board: if isinstance(obj, o.GameObject): obj.step() print(obj, end=' ')
這個類離全自動還差這些元素:segmentfault
step()
的方法。下面就先解決前兩個!app
以前,咱們已經有了配置文件。咱們如今要作的就是每步都看看這一步有沒有在配置文件中出現。命令行
import game_obj as o class Game: def __init__(self): o.sunlight = 50 o.board = [0] * 10 self.sunlight = o.sunlight self.board = o.board self.step_num = 0 import json with open("level.json") as fr: self.steps = json.load(fr) def step(self): self.step_num += 1 print("Sunlight: %d." % self.sunlight) print("Current state:") for obj in self.board: if isinstance(obj, o.GameObject): obj.step() print(obj, end=' ') if str(self.step_num) in self.steps.keys(): action = self.steps[str(self.step_num)] if action == "zombie": o.Zombie(9) elif action == "exit zombie": o.Zombie(9, die_to_exit=True)
好!如今,遊戲能夠自動產生殭屍了。而後呢?code
真正的植物大戰殭屍遊戲能夠讓玩家用鼠標控制遊戲。因爲這是命令行遊戲,因此咱們得用命令控制。我忽然發現,竟然還得編寫處理命令的方法!遊戲
def process_command(self, commands): for command in commands: command_list = command.split() if command_list[0] == 'plant' and len(command_list) == 3: plant_type = command_list[1] try: pos = int(command_list[2]) except ValueError: print("Invalid command.") else: if plant_type == 's': o.Sunflower(pos) elif plant_type == 'p': o.Peashooter(pos) else: print("Invalid command.")
好,用用它吧(固然,是在step()
裏面)!get
def step(self): pass # 同前 first_command = input("next step: ") if first_command: commands = [first_command] next_command = 'some content' while next_command: next_command = input(" -: ") commands.append(next_command) else: commands = [] self.process_command(commands)
後來我又知道,能夠把不依賴實例的方法聲明爲@staticmethod
,並把self
參數去掉,因而把process_command
改成:input
@staticmethod def process_command(commands): pass # 同前
好了!至此,咱們的三個需求只剩一個了,而這一個將會在第三步的後半步解決!歡迎繼續關注!it