我正在制作一个简单的基于文本的游戏,它使用while
循环进行战斗。它询问玩家他们想做什么,并提供使用武器或库存(魔药等)的选项。如果他们选择库存以查看他们拥有的东西,我怎样才能让他们选择回去选择武器和攻击呢?我尝试创建一个名为back
的函数,其唯一代码是pass
,如果用户输入back
,它会将它们发送到菜单的开头。但它会无休止地循环敌人的攻击,而不是让用户做任何事情。有任何想法吗?这是我的战斗代码:
我希望能够将它们发回到print "what will you do?"
行
def combat():
hero_hp = 1000000
enemy_hp = randint(5, 10)
enemy_name_test = randint(1,5)
enemy_weapon_test = randint(1,5)
enemy_name = list_of_enemys[enemy_name_test]
enemy_weapon = list_of_weapons[enemy_weapon_test]
while hero_hp > 0 and enemy_hp > 0:
print "The %s swings at you with a %s" % (enemy_name, enemy_weapon)
damage = randint(0, 10)
if damage == 0 :
print "the %s misses" %enemy_name
else :
hero_hp -= damage
print "The %s hits you with a %s for %d hit points you have %d hit points left" % (enemy_name, enemy_weapon, damage, hero_hp)
hero_hp -= damage
if hero_hp <= 0 :
print "you have been slain!"
close()
else :
print "What will you do?"
print inventory
player_choice = raw_input("> ")
if player_choice == '1' :
print hero_weapons
player_choice2 = raw_input("> ")
weapon = hero_weapons[player_choice2]
damage = randint(0, 10)
enemy_hp -= damage
print "You attack with %s for %d hit points" % (weapon, damage)
print "%s has %d hit points left" % (enemy_name, enemy_hp)
if enemy_hp <= 0 :
print "You have slain the %s" % enemy_name
else :
pass
else :
print hero_equipment
player_choice2 = raw_input("> ")
heal = randint(1, 10)
hero_equipment.pop(player_choice2)
print "you drink a potion and heal %s hit points" % heal
答案 0 :(得分:0)
我希望这个答案不会超出你的想法,但是你的程序会变得很复杂,很快就会把它变成一个非工作的混乱。
我建议您研究有限状态机,这是一种很好的收集方式
您的代码已经描述了一个FSM,它只是通过if语句和选择变量的组合来实现的。这是一个与您尝试用代码描述的状态表接近的状态表
|choice
state |attack potion inventory back
--------------+--------------------------------------------------------
combat_begin |combat_begin combat_begin show_inventory
show_inventory| combat_begin combat_begin
如果玩家已经开始战斗,她可以进行攻击,然后进入战斗开始。她可以使用一种药水,也可以让她回到战斗中(并且具有药水所具有的任何效果)。她可以要求查看她的库存,使她处于一个新的状态(show_inventory)。在战斗开始时她不能做的一件事就是“回”,因为那个牢房是空的。
如果玩家处于show_inventory状态,她可以“退回”或使用药水,两者都会再次开始战斗。她在这里不能做的就是攻击或展示库存。
显然,我已经让这个例子变得非常简单,希望能让你知道这需要去哪里。
答案 1 :(得分:0)
创建一个speperate函数,其中包含您想要循环的函数,然后无论何时循环,都要调用该函数。
例如:
def example(example_item):
if example_a == example_b:
example(example_item) #calling the function again
else:
return(false)
当然这不是你会使用的,但它只是一个例子。
确保每次都有一些变化,或者它将是一个无限循环。例如,您可以将1
添加到example_a
,这最终会在某个时刻停止循环。