今天我时间有点紧张,因此不说废话了,直接进入正题。前做连接: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