python 写命令行游戏_从0开始用python写一个命令行小游戏(五)

今天我时间有点紧张,所以不说废话了,直接进入正题。前作链接:

从0开始用python写一个命令行小游戏(一)

从0开始用python写一个命令行小游戏(二)

从0开始用python写一个命令行小游戏(三)

从0开始用python写一个命令行小游戏(四)

用户界面:第2.5步(第三步的前半步)

上次我们的Game类是这样的:

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=' ')

这个类离全自动还差这些元素:

自动出现的僵尸;

用户可控的植物;

自动重复执行step()的方法。

下面就先解决前两个!

自动出现的僵尸

之前,我们已经有了配置文件。我们现在要做的就是每步都看看这一步有没有在配置文件中出现。

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)

好!现在,游戏可以自动产生僵尸了。然后呢?

用户可控的植物

真正的植物大战僵尸游戏可以让玩家用鼠标控制游戏。由于这是命令行游戏,所以我们得用命令控制。我突然发现,居然还得编写处理命令的方法!

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()里面)!

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改为:

@staticmethod

def process_command(commands):

pass # 同前

好了!至此,我们的三个需求只剩一个了,而这一个将会在第三步的后半步解决!欢迎继续关注!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值