0.01的代码,遇到敌人就会失败,该添加战斗功能。
我们可以将现在的代码封装在小的函数中,更容易管理代码。
函数式编程中,可以通过重复使用一组简单的函数来构建复杂的逻辑。
将之前的代码封装到六个独立的函数中:a显示主题 b显示任务 c占据者类型 d处理用户选择 e揭示房屋占据情况 f输入房屋
这种封装到函数的操作叫做:重构
如果程序出现错误,可以试着在中断处插入一行print("*****************")来观察输出
import random
import textwrap # 用于提供格式打印功能
import sys
def print_dotted_line(width=72): # 打印分隔行
print('-' * width)
def show_theme_message(width):
"""显示主题"""
print_dotted_line()
print_bold("兽人之怒 v0.0.5:")
msg = (
"在人类和他们的敌人战争中,兽人是第一个到来的敌人,一支强大的兽人军队"
"正在向人类的聚集地进发。他们几乎摧毁了行进道路上的一切。人类不同种族"
"首领联手击败敌人,来共同为伟大时代而战斗。人们都被召集起来参加军队。"
"Foo先生,一个勇敢的骑士,向东部进发。两天两夜,穿过茂密的丛林,在路"
"上他发现了一个孤立的定居点。因为疲劳,加上希望补充食物,他决定绕道"
"而行,他进入村庄时,看到五个木屋,周围没有任何敌人,犹豫之后,他决定"
"进入其中一件木屋。。")
print(textwrap.fill(msg, width=width))
def show_game_mission():
"""打印游戏任务"""
print_bold("任务:")
print("\t选择一个准备进入的木屋:...")
print_bold("提示:")
print("注意敌人可能潜伏在屋子中!")
print_dotted_line()
def reveal_occupants(idx, huts):
"""打印屋中情况"""
msg = ""
print("正在打开屋子...")
for i in range(len(huts)):
occupant_info = "<%d:%s>" % (i + 1, huts[i])
if i + 1 == idx:
occupant_info = "\033[1m" + occupant_info + "\033[0m"
msg += occupant_info + " "
print("\t" + msg)
print_dotted_line()
def occupy_huts():
"""随机分配屋中元素"""
huts = []
occupants = ['敌人', '朋友', '空无一人']
while len(huts) < 5:
computer_choice = random.choice(occupants)
huts.append(computer_choice)
return huts
def process_user_choice():
"""处理用户选择"""
msg = "\033[1m" + "选择要进入的屋子 (1-5): " + "\033[0m"
user_choice = input("\n" + msg)
idx = int(user_choice)
return idx
def reset_health_meter(health_meter):
"""玩家和敌人的初始血量"""
health_meter['玩家'] = 40
health_meter['敌人'] = 30
def print_bold(msg, end='\n'):
"""用blod字体打印信息"""
print("\033[1m" + msg + "\033[0m", end=end)
def show_health(health_meter, bold=False):
"""显示玩家和敌人的血量"""
msg = "健康值: 骑士Foo: %d, 敌人: %d" \
% (health_meter['玩家'], health_meter['敌人'])
if bold:
print_bold(msg)
else:
print(msg)
def attack(health_meter):
"""攻击的主逻辑"""
hit_list = 4 * ['玩家'] + 6 * ['敌人'] #4成几率命中玩家,6成几率命中敌人
injured_unit = random.choice(hit_list)
hit_points = health_meter[injured_unit] #被伤害的单位当前血量
injury = random.randint(10, 15) #随机选择被伤害值,10-15之间
health_meter[injured_unit] = max(hit_points - injury, 0) #被伤害后的剩余血量,如果为负则为0
print("攻击! ", end='')
show_health(health_meter) #显示玩家和敌人的血量
def play_game(health_meter):
huts = occupy_huts() #随机分配屋子中元素
idx = process_user_choice() #玩家选择的屋子编号
reveal_occupants(idx, huts) #显示屋中元素,高亮显示玩家选择
if huts[idx - 1] != '敌人': #如果选择的元素不是"敌人"
print_bold("恭喜! 你赢了!!!")
else:
print_bold('发现敌人! ', end='') #如果是敌人
show_health(health_meter, bold=True) #显示各方血量
continue_attack = True
# 继续攻击
while continue_attack:
continue_attack = input(".......继续攻击? (y/n): ")
if continue_attack == 'n':
print_bold("以现在的状态逃跑...")
show_health(health_meter, bold=True)
print_bold("游戏结束!")
break
attack(health_meter)
# 检查是否有被击败
if health_meter['敌人'] <= 0:
print_bold("干得好! 敌人被击败! 你赢了!!!")
break
if health_meter['玩家'] <= 0:
print_bold("你输了 :( 下次好运!")
break
def run_application():
"""程序最上层控制."""
keep_playing = 'y'
health_meter = {}
reset_health_meter(health_meter)
show_game_mission()
while keep_playing == 'y':
reset_health_meter(health_meter) #重置血量
play_game(health_meter) #调用play_game函数运行游戏
keep_playing = input("\n继续玩吗? Yes(y)/No(n): ")
if __name__ == '__main__':
run_application()
浙公网安备 33010602011771号