How to write a function to the game where you can run from the fight and so it would return your position to the state before the battle, because with my current code it returns you to the beginning of the game.
This is my code
def run():
runnum = random.randitn(1, 10)
if runnum <= 4:
print("Success!")
option = input(" ")
start1()
else runnum > 7:
print("You can't run!")
option = input(" ")
fight()
CodePudding user response:
If you want to be able to come back to a previous state (before the fight), either store the previous state, or use the Command
pattern which allows for easy "undo", or do something else that may require re-architecturing your game.
It would be simpler to help you if we had a Minimal Reproducible Example of your problem.
CodePudding user response:
It is good to start a problem like this with the data structures.
You might want a player, rooms and mobs. YAML is handy for this kind of data modeling.
MODEL = """
rooms:
0:
desc: You are in the lobby on Shang Tsung's Island. It is a rather grey room.
name: The lobby
1:
desc: An aged Shang Tsung sits on his throne and watches the fights below. Monk
students also watch and applaud after every round is finished.
name: The courtyard
2:
desc: A prominent lava river flows in the background. On the west side of the
stageis a bridge that goes over it, while the east side leads to a split road.
A rock outcropping marks each side of the stage. Spikes and their victims, dot
the landscape.
name: Krossroads
3:
desc: An sandy oval arena. From the stands giant drummers beat their drums as the
fighters beat each other up. It is said that in the event of a tie, Konga,
the biggest drummer of them all, will challenge both of the warriors.
name: Drum Arena
player:
location: 0
health: 24
mobs:
0:
name: Kobra
location: 1
desc: Kobra is a tall man. The newest recruit of the Black Dragon has
shoulder length blond hair and he wears a white karate gi with black
and gold trim. He wears no shirt under his gi. He has taped wrists
and gloves, and he wears dark baggy pants with yellow trim over bare feet.
health: 14
strength: 6
1:
name: Kira
location: 3
desc: Kira is a rational level-headed anarchist, opposite in character to Kobra.
She has unlikely red hair in a pair of even more unlikely pony tails and
wears a black leather jerkin and leggings dyed in the blood of her
many victims. In each hand she wields a serrated dagger.
health: 20
strength: 8
"""
The game is then structured around this data model. At heart it a while loop that continues until the player runs out of health. At the start of the loop prompt the user for a command.
def run():
....
while player['health'] > 0:
cmd = prompt("cmd: ")
if cmd == ...
More concretely, handle the command "quit" or "q" to allow the player to exit the game:
import yaml
from rich import print
from rich.prompt import Prompt
from rich.panel import Panel
import random
def run():
model = yaml.load(MODEL, Loader=yaml.Loader)
rooms = model['rooms']
player = model['player']
while player['health'] > 0:
loc = rooms[player['location']]
prompt = f"[orange1 on grey23][{loc['name']}][/]"
cmd = Prompt.ask(prompt).lower()
if cmd in ["q", "quit"]:
print("Thank you for playing")
return
Add commands to look, to move north and south.
if cmd in ["l", "look"]:
desc = [loc['desc']]
print(Panel("\n".join(desc)))
continue
if cmd in ["n", "north"]:
player['location'] = 1
continue
elif cmd in ["s", "south"]:
player['location'] -= 1
continue
A complete example that incorporates mobs and a combat system.
def find_mob(model):
mobs = model['mobs']
player = model['player']
for mob in mobs.values():
if mob['location'] == player['location']:
return mob
def run():
print(Panel("Welcome to MORTAL TEXT BASED KOMBAT\n"
"Commands are north, south, look, punch and kick.\n"
"Good luck!"))
model = yaml.load(MODEL, Loader=yaml.Loader)
rooms = model['rooms']
player = model['player']
loc = rooms[player['location']]
while player['health'] > 0:
new_loc = rooms[player['location']]
if loc != new_loc:
print(f"[deep_sky_blue3 on thistle1] You enter {new_loc['name']}[/]")
loc = new_loc
mob = find_mob(model)
if mob:
prompt = f"[red3 on light_salmon1][{loc['name']} | You ({player['health']}) vs {mob['name']} ({mob['health']})] [/]"
else:
prompt = f"[orange1 on grey23][{loc['name']}][/]"
cmd = Prompt.ask(prompt).lower()
if cmd in ["n", "north"]:
if player['location'] < max(rooms.keys()):
player['location'] = 1
else:
print("Sorry, you can't go north :worried: ")
continue
elif cmd in ["s", "south"]:
if player['location'] > 0:
player['location'] -= 1
else:
print("Sorry, you can't go south :worried: ")
continue
elif cmd in ["l", "look"]:
desc = [loc['desc']]
if mob:
desc.append(f"[red3 on grey93]{mob['name']} is here![/]")
desc.append(f"[blue on white]{mob['desc']}[/]")
print(Panel("\n".join(desc)))
continue
if mob:
hit, damage = -1, 0
if cmd in ["punch", "p"]:
cmd = "punch"
hit, damage = random.randint(4,20), random.randint(1,6)
elif cmd in ["kick", "k"]:
cmd = "kick"
hit, damage = random.randint(1,20), random.randint(2,8)
if hit > 9:
print(f"Your {cmd} hits and does {damage} damage!")
mob["health"] -= damage
if mob['health'] <= 0:
print(f"You killed {mob['name']}!")
mob['location'] = -1
continue
elif hit > 0:
print(f"Your {cmd} misses.")
if random.randint(1,20) > 10:
damage = random.randint(1,mob['strength'])
print(f"{mob['name']} hits you. You take {damage} damage.")
player['health'] -= damage
if player['health'] <= 0:
print("[red on black]You died[/] :skull:")