Discuss Scratch

ScratchCatHELLO
Scratcher
1000+ posts

PyRPG (Python Text Adventure)

imfh wrote:

You might want to make it so there are multiple words you can use for the same action. For example, I kept trying to use “examine item” rather than “look at item” since that is what I usually use in other text games.

noted. is there a place i can find common command names?

imfh wrote:

Also, a matter of preference, but you could use command.startswith(“blah”) rather than command == “blah”.

I've actually stopped slicing strings. now I'm using this method:
command = input().split
to make commands a bit easier to parse and make the code easier to understand. I'm not sure if this is the right method, but it works pretty well.

imfh wrote:

It is also handy to have abbreviations for commands, particularly with movement. With Zork, for example, you can just type ‘w’ to go west, which becomes really helpful when the map gets larger. Another common abbreviation is an L for look.

I have abbreviations for movement commands (in the latest version), but I'll definitely think about adding abbreviations to commands like “look” or maybe “help”.

imfh wrote:

With the map, don't be afraid to make it un-grid-like. What I mean is, when the player travels west along a path, you could make it curve so they have to travel south to return. You can also make one way paths. Stuff like this can make the map more maze like and fun to explore.

I'll definitely try to do this, if I remember it (although I'm not really sure where I want to go with the map)
the system I currently have should allow for this just fine, because it's not actually confined to a grid and I can technically include any direction I want to

imfh wrote:

When you are making the map, I've sometimes found it easier to draw it on paper first. You can draw a box for each location and connect the boxes using lines. A line on the west side means you go west to travel that path. You can also draw arrows and stuff to indicate one way; you get the idea. Example map from Zork

once I start designing the map, I'll do this. thanks!

imfh wrote:

You might want to consider adding more detail into your “normal” room descriptions so you don't have to type look every time. I usually like to have the descriptions say things like “You are on a north-south path” to make basic directions obvious.

That's probably a good idea. I remember zork having some of those, so it would make sense to have them here too.

imfh wrote:

If the player isn't necessarily typing look every time, you can also hide some hidden secrets, such as “You notice a small break in the brush to the west.”

this gives me some ideas…

thanks for the feedback!












enter command
West of House
This is an open field west of a white house, with a boarded front door.
There is a small mailbox here.
A rubber mat saying 'Welcome to Zork!' lies by the door.

>examine mailbox
I see nothing special about the mailbox.

>
















Python 3 Text Adventure
cool new browser game - cursed laughing-crying emoji - Illuminati - you know waterbenders, but do you know stock-imagebenders? - snek - vibin' - Bump song (vevo) - Speed bump - yee - fred - m i c k e y



ScratchCatHELLO
I have 4300+ posts, I've been on scratch for 3 years, I'm a Forum Helper™ and I have a Scratch Wiki account!
I like: Python, CSS, Javascript, Rust

zahmbie1
Scratcher
1000+ posts

PyRPG (Python Text Adventure)

NorthenSuperCoders
Scratcher
100+ posts

PyRPG (Python Text Adventure)

Hey, If you haveing problems for Python IDE so Download and Install Anaconda Application and Snake, yes its application. search on google first Anaconda its an example of Adobe Air and Snake is an example of scratch 2 which doesn't runs without adobe air.

NorthenSuperCoders
A self-programmer - also writes books, him self.
===================================================
ScratchCatHELLO
Scratcher
1000+ posts

PyRPG (Python Text Adventure)

NorthenSuperCoders wrote:

Hey, If you haveing problems for Python IDE so Download and Install Anaconda Application and Snake, yes its application. search on google first Anaconda its an example of Adobe Air and Snake is an example of scratch 2 which doesn't runs without adobe air.

uh… what












enter command
West of House
This is an open field west of a white house, with a boarded front door.
There is a small mailbox here.
A rubber mat saying 'Welcome to Zork!' lies by the door.

>examine mailbox
I see nothing special about the mailbox.

>
















Python 3 Text Adventure
cool new browser game - cursed laughing-crying emoji - Illuminati - you know waterbenders, but do you know stock-imagebenders? - snek - vibin' - Bump song (vevo) - Speed bump - yee - fred - m i c k e y



ScratchCatHELLO
I have 4300+ posts, I've been on scratch for 3 years, I'm a Forum Helper™ and I have a Scratch Wiki account!
I like: Python, CSS, Javascript, Rust

zahmbie1
Scratcher
1000+ posts

PyRPG (Python Text Adventure)

NorthenSuperCoders wrote:

Hey, If you haveing problems for Python IDE so Download and Install Anaconda Application and Snake, yes its application. search on google first Anaconda its an example of Adobe Air and Snake is an example of scratch 2 which doesn't runs without adobe air.
what
*rereads ten times*
i still don’t get it
ScratchCatHELLO
Scratcher
1000+ posts

PyRPG (Python Text Adventure)

zahmbie1 wrote:

NorthenSuperCoders wrote:

Hey, If you haveing problems for Python IDE so Download and Install Anaconda Application and Snake, yes its application. search on google first Anaconda its an example of Adobe Air and Snake is an example of scratch 2 which doesn't runs without adobe air.
what
*rereads ten times*
i still don’t get it

things I learned:
- Anaconda
- You need to install Anaconda, it doesn't come automatically
- Use Anaconda if python IDE isn't working (but I don't use a python IDE)
- Also install Snake™, which is an application
- Search “first anaconda”. there'll be an example of Adobe Air (for some reason)
- Snake is an example of scratch 2
- Scratch 2 doesn't runs without adobe air

Last edited by ScratchCatHELLO (June 28, 2021 18:06:53)













enter command
West of House
This is an open field west of a white house, with a boarded front door.
There is a small mailbox here.
A rubber mat saying 'Welcome to Zork!' lies by the door.

>examine mailbox
I see nothing special about the mailbox.

>
















Python 3 Text Adventure
cool new browser game - cursed laughing-crying emoji - Illuminati - you know waterbenders, but do you know stock-imagebenders? - snek - vibin' - Bump song (vevo) - Speed bump - yee - fred - m i c k e y



ScratchCatHELLO
I have 4300+ posts, I've been on scratch for 3 years, I'm a Forum Helper™ and I have a Scratch Wiki account!
I like: Python, CSS, Javascript, Rust

NorthenSuperCoders
Scratcher
100+ posts

PyRPG (Python Text Adventure)

ScratchCatHELLO wrote:

zahmbie1 wrote:

NorthenSuperCoders wrote:

Hey, If you haveing problems for Python IDE so Download and Install Anaconda Application and Snake, yes its application. search on google first Anaconda its an example of Adobe Air and Snake is an example of scratch 2 which doesn't runs without adobe air.
what
*rereads ten times*
i still don’t get it

things I learned:
- Anaconda
- You need to install Anaconda, it doesn't come automatically
- Use Anaconda if python IDE isn't working (but I don't use a python IDE)
- Also install Snake™, which is an application
- Search “first anaconda”. there'll be an example of Adobe Air (for some reason)
- Snake is an example of scratch 2
- Scratch 2 doesn't runs without adobe air
Yeah!

NorthenSuperCoders
A self-programmer - also writes books, him self.
===================================================
NorthenSuperCoders
Scratcher
100+ posts

PyRPG (Python Text Adventure)

Anaconda and my connection is low so search for Snake Python IDE on Google

NorthenSuperCoders
A self-programmer - also writes books, him self.
===================================================
ScratchCatHELLO
Scratcher
1000+ posts

PyRPG (Python Text Adventure)

NorthenSuperCoders wrote:

Yeah!

I know about anaconda and adobe air, but what do Snake (1976), Scratch 2.0, and Adobe Air have to do with anaconda?
ack ninja'd but I can't find a Snake IDE

zahmbie1 wrote:

when bump

sorry, I was working on a different project that generates a (semi-believable) story, but after spending a day or two programming a map gen prototype, I realized it's probably too ambitious. I think I'll go back to working on this again.

Last edited by ScratchCatHELLO (June 28, 2021 18:18:10)













enter command
West of House
This is an open field west of a white house, with a boarded front door.
There is a small mailbox here.
A rubber mat saying 'Welcome to Zork!' lies by the door.

>examine mailbox
I see nothing special about the mailbox.

>
















Python 3 Text Adventure
cool new browser game - cursed laughing-crying emoji - Illuminati - you know waterbenders, but do you know stock-imagebenders? - snek - vibin' - Bump song (vevo) - Speed bump - yee - fred - m i c k e y



ScratchCatHELLO
I have 4300+ posts, I've been on scratch for 3 years, I'm a Forum Helper™ and I have a Scratch Wiki account!
I like: Python, CSS, Javascript, Rust

ScratchCatHELLO
Scratcher
1000+ posts

PyRPG (Python Text Adventure)

acording to wc, the average “word” in my code is 10-ish letters long
probably because of stuff like this:
item.special[commandname.strip()][1](*item.special[commandname.strip()][2:len(item.special[commandname.strip()])+2])












enter command
West of House
This is an open field west of a white house, with a boarded front door.
There is a small mailbox here.
A rubber mat saying 'Welcome to Zork!' lies by the door.

>examine mailbox
I see nothing special about the mailbox.

>
















Python 3 Text Adventure
cool new browser game - cursed laughing-crying emoji - Illuminati - you know waterbenders, but do you know stock-imagebenders? - snek - vibin' - Bump song (vevo) - Speed bump - yee - fred - m i c k e y



ScratchCatHELLO
I have 4300+ posts, I've been on scratch for 3 years, I'm a Forum Helper™ and I have a Scratch Wiki account!
I like: Python, CSS, Javascript, Rust

ScratchCatHELLO
Scratcher
1000+ posts

PyRPG (Python Text Adventure)

PyRPG v0.4 (BETA) - The Acheivements Update
added achievements, and some under-the-hood stuff

#iteration 3
import os
import random
from difflib import SequenceMatcher
import random
from rich import print as rprint
from rich import align
version = "0.4 (BETA)"
#blue   = inventory
#purple = item uses
#red    = error/invalid command
#orange = combat?
#green  = outside-game messages (changelog, clearing, quit prompt)
class Room:
    """
    Represents a room.
    Attributes
    ----------
    name : str
        the room name (used in dev mode)
    passive : str
        the description that displays after each turn
    detail : str
        the description that displays when you type "look"
    directions : dict
        a dict of directions a player in the room can move
        {
            "s": ["roomname"],
            "n": ["otherroomname", "warningmsg" conditionfunction, arg1, arg2]
        }
        conditionfunction - function that returns True or False. If the function returns True, the path is passable. If the function returns False, the path is impassable.
        warningmsg - the warning for when the path is impassable
        arg - the arguments for the condition function
    items : dict
        a list of item objects
    ents : dict
        a list of entity objects
    Methods
    -------
    ritem(itemname):
        removes an item by name
    rent(entname):
        removes an entity by name
    str(room):
        converts a room into a string listing attributes
    """
    def __init__(room, name, descriptions, directions, items, ents):
        room.name = name
        room.passive = descriptions[0]
        room.detail = descriptions[1]
        room.directions = directions
        room.items = items
        room.ents = ents
    def __str__(room):
        tmpstr = f"{room.name} "
        for item in room.items:
            tmpstr += f"D There is a {item.name}.\n"
        for ent in room.ents:
            tmpstr += f"D A {ent.name} is standing here.\n"
        return tmpstr
    def ritem(room, itemname):
        room.items.pop(itemname)
    def rent(room, entname):
        room.items.pop(entname)
class Item:
    """
    Represents an item.
    Attributes
    ----------
    name : str
        the item name
    short : str
        short description of the item
    long : str
        detailed description of the item
    stats : dict
        a list of stats
        structure is as follows:
        {
            "dmg": 10, #damage of the item
            "critdmg": 15, #damage of the item when it hits something critically
            "sellprice": 30, #sell value
            "buyprice": 35, #buy value
            "atkeffect": randomdmg #executes a function when you use the item to attack
        }
    special : dict (optional)
        a list of actions that can be performed using an item
        toaster:
        {
            "toast bread": ["toast your bread", toast, "bread"],
            "toast bagel": ["toast your bagel", "toast, "bagel"]
        }
        use toaster to toast bread - executes toast("bread")
        use toaster to toast bagel - executes toast("bagel")
        use toaster instructions - prints the following:
            toast bread - toast your bread
            toast bagel - toast your bagel
        syntax:
        {
            "subcommand": ["description", function, "arg1", "arg2", "arg3"]
        }
    weapon : bool (optional)
        False -> not a weapon
        True -> a weapon
        defaults to False
    """
    def __init__(item, name, descriptions, stats, special={}, weapon=False):
        item.name = name
        item.d = descriptions
        item.short = descriptions[0] #brief
        item.long = descriptions[1] #detail
        item.stats = stats
        item.special = special
        item.weapon = weapon
class Ent:
    """
    Represents an entity.
    Attributes
    ----------
    name : str
        the entity name
    inv : dict
        the inventory of the entity. consists of a dict of Item objects
    stats : dict
        the stats of the entity
        structure is as follows:
        {
            "hp": 10, #current health
            "maxhp": 10, #full health
            "dmg": 5, #its damage in combat
            "acc": 2, #entity will hit (1/acc)*100 percent of the time
            "crit": 5, #entity will crit (1/crit)*100 percent of the time
            "critdmg": 7, #damage of a critical hit
        }
    hostilemode : int
        whether an entity will attack unprovoked
        2: the entity will attack when the player enters the room it's in
        1: the entity won't fight unprovoked
        0: the entity won't fight
    """
    def __init__(ent, name, inv, stats, hostilemode=1):
        ent.name = name
        ent.inv = inv
        ent.stats = stats
        ent.hostilemode = hostilemode
    def giveitem(ent, player, itemname):
        player["inv"][itemname] = ent.inv[itemname]
        ent.inv[itemname].pop()
    def damage(ent, amount):
        if ent.stats["hp"] - amount < 0:
            ent.stats["hp"] = 0
        else:
            ent.stats["hp"] -= amount
    def heal(ent, amount):
        if ent.stats["hp"] + amount > ent.stats["maxhp"]:
            ent.stats["hp"] = ent.stats["maxhp"]
        else:
            ent.stats["hp"] += amount
    def attack(ent):
        stats = ent.stats
        hitper = (1/stats["acc"])*100
        critper = (1/stats["crit"])*100
        if bool(random.choices([1, 0], weights=[hitper, 100-hitper])[0]):
            if bool(random.choices([1, 0], weights=[critper, 100-critper])[0]):
                rprint(f"!![bold red]The {ent.name} critically hit you, doing {stats['critdmg']} damage!")
                return stats["critdmg"]
            else:
                rprint(f"! [bold]The {ent.name} hit you, doing {stats['dmg']} damage!")
                return stats["dmg"]
        else:
            rprint(f"  [italic]The {ent.name} missed!")
            return 0
title = """      :::::::::  :::   ::: :::::::::  :::::::::   ::::::::
     :+:    :+: :+:   :+: :+:    :+: :+:    :+: :+:    :+:
    +:+    +:+  +:+ +:+  +:+    +:+ +:+    +:+ +:+
   +#++:++#+    +#++:   +#++:++#:  +#++:++#+  :#:
  +#+           +#+    +#+    +#+ +#+        +#+   +#+#
 #+#           #+#    #+#    #+# #+#        #+#    #+#
###           ###    ###    ### ###         ########       """
versions = {
    "0.1 (BETA)": "[b green]0.1[/]\n - first version of game\n - added look, help, movement commands, grab/drop, inventory, inspect, clear, quit\n - added first map (two rooms with an item in one)\n",
    "0.2 (BETA)": "[green][b]0.2[/]\n[i dim]The Feedback and Consistency Update[/][/green]\n - added changelog\n - fixed typos\n - consistent capitalization\n - 'inventory' now tells you when your inventory is empty\n - 'grab' and 'drop' now warn you when the item isn't in the room or your inventory, respectively.\n",
    "0.3 (BETA)": "[green][b]0.3[/]\n[i dim]The Items Update[/][/green]\n[b] - added 'use' (this sounds small, but it's actually pretty big)[/]\n - box can now be opened using the 'use' command",
    "0.4 (BETA)": "[green][b]0.4[/]\n[i dim]The Achievements Update[/][/green]\n - added some helper functions\n - sword can now destroy things\n[b] - added achievements[/]\n[b] - added 'achievements' command[/]\n - added built-in method to make conditional paths to other rooms"
}
commands = {
    "help": ["print list of commands and descriptions.", "[b]=HELP=[/]\nPrints a list of command and simple descriptions.\n[b]USAGE[/]\nhelp - print list of commands and descriptions\n    command (opt) - print detailed description of the specified command."],
    "help <command>": ["print detailed explanation of <command>."],
    "quit": ["quit game.", "[b]=QUIT=[/]\nExits the game.\n[b]USAGE[/]\nquit - end game\nq - end game"],
    "look": ["look around at the current room.", "[b]=LOOK=[/]\nPrints a detailed description of the current room.\n[b]USAGE[/]\nlook - see description of current room"],
    "north": ["go north.", "[b]=NORTH=[/]\nMoves the player north.\n[b]USAGE[/]\nnorth - move player north\nn - move player north"],
    "west": ["go west.", "[b]=WEST=[/]\nMoves the player west.\n[b]USAGE[/]\nwest - move player west\nw - move player west"],
    "east": ["go east.", "[b]=EAST=[/]\nMoves the player east.\n[b]USAGE[/]\neast - move player east\ne - move player east"],
    "south": ["go south.", "[b]=WEST=[/]\nMoves the player south.\n[b]USAGE[/]\nwest - move player south\ns - move player south"],
    "grab": ["grab item from room.", "[b]=GRAB=[/]\nGrab an item out of the room and place it in your inventory.\n[b]USAGE[/]\ngrab - grab an item\n    item - name of item to grab."],
    "drop": ["drop item into room.", "[b]=DROP=[/]\nDrop an item from your inventory and place it in the room.\n[b]USAGE[/]\ndrop - drop an item\n    item - name of item to drop."],
    "inventory": ["list items in inventory.", "[b]=INVENTORY=[/]\nPrint a list of items in your inventory.\n[b]USAGE[/]\ninventory/i - read inventory"],
    "inspect": ["show detailed description of an item.", "[b]=INSPECT=[/]\nShow a detailed description of an item in your inventory.\n[b]USAGE[/]\ninspect - show long item description"],
    "clear": ["clear cmd prompt/terminal.", "[b]=CLEAR=[/]\nClear screen (for when the terminal has a lot of text in it).\n[b]USAGE[/]\nclear - clear cmd/terminal"],
    "changelog": ["show changelog for the current rpg version.", "[b]=CHANGELOG=[/]\nShow version changelog.\n[b]USAGE[/]\nchangelog - show changelog for the current version\n    version (opt) - print changelog for specific version"],
    "changelog <version>": ["show changelog for a specific rpg version."],
    "use": ["use an item to do something.", "[b]=USE=[/]\nPerform an action using an item in your inventory\n[b]USAGE[/]\nuse - perform an action using an item\n    item - the item to use\n        to - use an item to do something\n            action - what to use the item for\n        instructions - get a list of things the item can do"],
    "achievements": ["list achievements.", "[b]=ACHIEVEMENTS=[/]\nDisplay achievements or show description of an achievement\nachievements - list achievements\n    symbol (opt) - display an achievement with the specified symbol"],
    "achievements <symbol>": ["display a specific achievement."]
}
#find the item of a list that is closest to a string
def findsimilar(thing, inlist):
    similar = {}
    for item in inlist:
        similar[item] = SequenceMatcher(None, item, thing).ratio()
    return list(reversed(sorted(similar.items(),key=lambda x:x[1])))[0][0]
player = {}
def initplayer(name, startroom):
    global player
    global achievements
    player = {
        "name": name,
        "loc": startroom,
        "hp": 30,
        "maxhp": 30,
        "inventory": {},
        "achievements": {"!": ["Adventurer", "On a quest to... uh... idk it's the beta do whatever", "Start the game", "!", "bright_black"]}
    }
def open(contname, intname, name, descriptions, stats, special, weapon, destroy, destroymsg, stopdoubleopen, commandname):
    """
    Command for opening a generic container as an option for the use command
    Arguments
    ---------
    contname (str) - container name
    intname (str) - internal name for the new item
    descriptions, stats, special, weapon (varies) - see item definition. these apply to the new item.
    destroy (bool) - destroy container after it's opened?
    destroymsg (str) - message displayed when container is destroyed do to opening.
    """
    item = Item(name, descriptions, stats, special, weapon)
    player["inventory"][intname] = item
    rprint(f"You open the {contname}. There's a {name} inside!")
    rprint(f"[blue]You now have a [b]{name}[/]!")
    intcontname = list(player["inventory"].keys())[[player["inventory"][iname].name for iname in player["inventory"]].index(contname)]
    #prevent player from opening the container twice
    if stopdoubleopen:
        player["inventory"][intcontname].special.pop(commandname)
    if contname == "box":
        achieve("A strange package", "Who was this for?", "Open the box.", "?", "orange4")
    if destroy:
        player["inventory"].pop(intcontname)
        print(destroymsg)
        print(f"[blue]You no longer have the {contname}!")
def achieve(title, splashtext, description, symbol, color):
    if not title in list(player["achievements"].keys()):
        width = len(max(["Achievement Get!", (title+"    "), splashtext, description], key = len)) + 2
        space = [" "*width, " "*(width-(len(title)+3+len(symbol))), " "*(width-len(splashtext)), " "*(width-len(description)), " "*(width-16)]
        rprint(f"[white on {color}]{space[0]}[/]\n[black on bright_yellow]Achievement Get!{space[4]}[/][white on yellow]\n[b]{title.upper()}[/b] ([{color} on yellow]{symbol}[/]){space[1]}\n[i]{splashtext}{space[2]}[/]\n[not b]{description}[/]{space[3]}\n[white on {color}]{space[0]}")
        player["achievements"][symbol] = [title, splashtext, description, symbol, color]
#achieve("Hello, world", "foo... bar...", "00101101", "@", "green")
def destroy(intname, name, msg):
    if intname in player["inventory"]:
        player["inventory"].pop(intname)
        rprint(f"[blue]The {name} has been destroyed!")
        if msg:
            rprint(msg)
    else:
        rprint(f"[red]You don't have a {name} to destroy!")
def sdestroy(swordname):
    rprint("[purple b]Destroy what?")
    name = input()
    itemnames = [player["inventory"][iname].name for iname in player["inventory"]]
    if name in itemnames:
        intname = list(player["inventory"].keys())[itemnames.index(name)]
        msg = ""
        if intname == "bx":
            msg = "A tree falls on the path between the crossroads and the forest, blocking it!"
        elif intname == swordname:
            msg = "...wait, what?!"
            achieve("how?!", "I used the sword to destroy the sword", "destroy a sword with the same sword", "?!", "red")
        destroy(intname, name, msg)
    else:
        rprint(f"[red]You don't have a {name} to destroy!")
def checkitem(itemname):
    return True if itemname in list(player["inventory"].keys()) else False
def noeffect():
    pass
box = Item("box", ["An odd box", "There are no markings on the cardboard box. It looks like it's been sitting in the forest for a while."], {"sellprice": 100, "buyprice": 150}, {"open": ["open the box", open, "box", "swrd", "sword", ["An elven sword", "There are a variety of runes inscribed in the sword. The edges of the blade seem to glow slightly. How cliche."], {"sellprice": 90, "buyprice": 100}, {"destroy": ["break a thing", sdestroy, "swrd"]}, False, False, "", True, "open"]})
startroom = Room("Crossroads", ["A crossroads between a mountain, a forest, a town, and a plains. You can move [red]north[/red], south, [red]east or west[/red] from here.", "To the west is a mountain that looms in the distance.\nTo the north is a town named <TODO: name town>.\nTo the east is a bridge over a river, leading to a path that trails off into the distance.\nTo the south is the dark forest you came out of."], {"s": ["ft1"]}, {}, {})
foresttrail1 = Room("Forest Trail", ["A dark north/[red]south[/] forest trail", "This place gives you the chills.\nTo the north is a crossroads between two trails.\nTo the south is a rocky clearing."], {"n": ["sr", "There's a tree blocking the path!", checkitem, "bx"]}, {"bx": box}, {})
allrooms = {
    "sr": startroom,
    "ft1": foresttrail1,
}
rprint(align.Align(f"[b green]{title}[/]", "center").center(f"[bold green]{title}[/]"))
rprint(align.Align(f"[b]V{version}[/]", "center").center(f"[b]V{version}[/]"))
name = input("What is your adventurer's name? ")
initplayer(name, startroom)
while True:
    room = player["loc"]
    rprint(room.passive)
    command = input(f"\n{player['name']}> ").split()
    if command:
        #list commands
        if command == ["help"]:
            for command in commands:
                rprint(f"{command} - {commands[command][0]}")
            print()
        #detailed help for specific command
        elif command[0] == "help" and len(command) >= 2:
            rprint(f"{commands[command[1]][1]}\n")
        #look around
        elif command == ["look"]:
            rprint(room.detail)
            for item in room.items:
                rprint(f"There is a {room.items[item].name} here.")
            rprint()
        #movement
        elif command[0][0] in list(room.directions.keys()) and command[0] in ["north", "west", "east", "south", "up", "down", "n", "w", "e", "s", "u", "d"]:
            move = room.directions[command[0][0]]
            if len(move) == 1 or move[2](*move[3:len(move)]):
                player["loc"] = allrooms[room.directions[command[0][0]][0]]
            else:
                rprint(f"[red]{move[1]}")
        #if the player tries to move in a direction that they can't
        elif command[0] in ["north", "west", "east", "south", "up", "down", "n", "w", "e", "s", "u", "d"]:
            if len(command[0]) == 1:
                tmpconvert = {"n": "north", "w": "west", "e": "east", "s": "south", "u": "up", "d": "down"}
                rprint(f"[red]You cannot go {tmpconvert[command[0]]}.")
            else:
                rprint(f"[red]You cannot go {command[0]}.")
        #grab items
        elif command[0] == "grab" and len(command) >= 2:
            items = {room.items[item].name:room.items[item] for item in room.items}
            name = " ".join(command[1:])
            if name in items:
                item = items[name]
                internalname = list(room.items.keys())[list(items.values()).index(item)]
                player["inventory"][internalname] = item
                room.items.pop(internalname)
                rprint(f"[blue]{name} grabbed!")
            else:
                if not len(items) == 0:
                    rprint(f"[red]There is no {name} here! There [i]is[/] a {findsimilar(name, items)} here. Did you mean that?")
                else:
                    rprint(f"[red]There are no items here!")
            #let this code stand as a memorial of what not to do
            #item = [room.items[item] for item in room.items][[room.items[item].name for item in room.items].index(command[1].lower())]
            #itemname = list(room.items.keys())[list(room.items.values()).index(item)]
            #player["inventory"][itemname] = item
            #room.items[itemname].pop()
        #unspecified item
        elif command == ["grab"]:
            rprint("[red]Grab what?")
        #drop items
        elif command[0] == "drop" and len(command) >= 2:
            items = {player["inventory"][item].name:player["inventory"][item] for item in player["inventory"]}
            name = " ".join(command[1:])
            if name in items:
                item = items[name]
                internalname = list(player["inventory"].keys())[list(items.values()).index(item)]
                room.items[internalname] = item
                player["inventory"].pop(internalname)
                rprint(f"[blue]{name} dropped!")
            else:
                if not len(items) == 0:
                    rprint(f"[red]There is no {name} in your inventory! There [i]is[/] a {findsimilar(name, items)} in your inventory. Did you mean that?")
                else:
                    rprint(f"[red]You don't have any items to drop!")
        #unspecified item
        elif command == ["drop"]:
            rprint("[red]Drop what?")
        #see detailed description of item in inventory
        elif command[0] == "inspect" and len(command) == 2:
            items = {player["inventory"][item].name:player["inventory"][item] for item in player["inventory"]}
            name = " ".join(command[1:])
            if name in items:
                rprint(f"[b blue]{items[name].name.upper()}[/]\n[pale_turquoise1]{items[name].long}[/]")
        #unspecified item
        elif command == ["inspect"]:
            rprint("[red]Inspect what?")
        #see inventory
        elif command == ["inventory"] or command == ["i"]:
            for i in player["inventory"]:
                item = player["inventory"][i]
                rprint(f"[b blue]{item.name}[/] [b]-[/] [i blue]{item.short}[/]")
            if len(player["inventory"]) == 0:
                rprint("[red]Your inventory is empty!")
        #use an item to perform an action
        elif command[0] == "use" and len(command) >= 2:
            itemname = ""
            inst = ""
            items = {player["inventory"][item].name:player["inventory"][item] for item in player["inventory"]}
            current = 0
            #find item name
            for word in command[1:len(command)]:
                current += 1
                if word in ["to", "instructions"]:
                    inst = word
                    break
                else:
                    itemname += f" {word}"
            #if the player included a "to" or "instructions"
            if inst:
                #if the player has the item
                if itemname.strip() in items:
                    item = items[itemname.strip()]
                    if inst == "instructions":
                        #print uses
                        for use in item.special:
                            rprint(f"[b purple]{use}[/] [b]-[/] [i purple]{item.special[use][0]}[/]")
                        #if the item has no uses
                        if len(item.special) == 0:
                            rprint(f"[red]The {itemname.strip()} has no uses!")
                    elif inst == "to":
                        commandname = ""
                        #find command name
                        for word in command[current+1:len(command)]:
                            commandname += f" {word}"
                        #if the item can perform the action
                        if commandname.strip() in item.special:
                            item.special[commandname.strip()][1](*item.special[commandname.strip()][2:len(item.special[commandname.strip()])+2])
                        else:
                            #if item cannot perform actions
                            if len(item.special) == 0:
                                rprint(f"[red]The {itemname.strip()} has no uses!")
                            else:
                                #find similar action
                                rprint(f"[red]The {itemname.strip()} cannot be used to {commandname.strip()}! Did you mean '{findsimilar(commandname.strip(), list(item.special.keys()))}?'")
                else:
                    rprint(f"[red]You don't have a(n) {itemname.strip()}!")
            else:
                rprint(f"[red]Use {itemname.strip()} to do what?")
        #unspecified item
        elif command == ["use"]:
            rprint("[red]Use what item?")
        elif command[0] == "achievements" and len(command) == 2:
            if command[1] in list(player["achievements"].keys()):
                achievement = player["achievements"][command[1]]
                title, splashtext, description, symbol, color = achievement[0], achievement[1], achievement[2], achievement[3], achievement[4]
                width = len(max([(title+" "*(3+len(symbol))), splashtext, description], key = len)) + 2
                space = [" "*width, " "*(width-(len(title)+3+len(symbol))), " "*(width-len(splashtext)), " "*(width-len(description))]
                rprint(f"[black on {color}]{space[0]}[/]\n[black on khaki3][b]{title.upper()}[/b] ([{color} on khaki3]{symbol}[/]){space[1]}\n[i]{splashtext}{space[2]}[/]\n[not b]{description}[/]{space[3]}\n[black on {color}]{space[0]}")
            else:
                symbols = list(player["achievements"].keys())
                rprint(f"[red]You don't have an achievement with the symbol '{command[1]}'. Did you mean '{findsimilar(command[0], symbols)}'?")
        elif command == ["achievements"]:
            for trophy in player["achievements"]:
                rprint(f"[white on {player['achievements'][trophy][4]} b]{player['achievements'][trophy][3]}[/]", end="")
            print()
        #clear terminal/cmd prompt
        elif command == ["clear"]:
            os.system("cls||clear") #multiplatform clear command!
            rprint("[green]Cleared!")
        #changelog
        elif command == ["changelog"]:
            rprint(versions[version])
        #access specific changelog
        elif command[0] == "changelog" and len(command) >= 2:
            #reassamble version names that have spaces
            name = " ".join(command[1:len(command)])
            try:
                rprint(versions[name])
            #if the version doesn't exist, find a similar one
            except KeyError:
                rprint(f"[red]'{name}' is not a valid version name. Did you mean '{findsimilar(name, list(versions.keys()))}'?")
        #quit game
        elif command == ["quit"] or command == ["q"]:
            rprint("[b green]Are you [i]sure[/i]?[/b green] (Y/n)")
            ynprompt = input().lower()
            if ynprompt in ["y", "yes"]:
                rprint("[green]Quitting game...")
                break
            elif ynprompt in ["n", "no", "nevermind"]:
                continue
            else:
                rprint("[red]Sorry, I don't understand. Can you try again? Valid answers are 'Y', 'Yes', 'N', 'No' (Case insensitive).")
        #find a similar command
        else:
            rprint(f"[red]Command not found. Did you mean '{findsimilar(command[0], list(commands.keys()))}'?")
    else:
        rprint(f"[red]Please enter a command.")












enter command
West of House
This is an open field west of a white house, with a boarded front door.
There is a small mailbox here.
A rubber mat saying 'Welcome to Zork!' lies by the door.

>examine mailbox
I see nothing special about the mailbox.

>
















Python 3 Text Adventure
cool new browser game - cursed laughing-crying emoji - Illuminati - you know waterbenders, but do you know stock-imagebenders? - snek - vibin' - Bump song (vevo) - Speed bump - yee - fred - m i c k e y



ScratchCatHELLO
I have 4300+ posts, I've been on scratch for 3 years, I'm a Forum Helper™ and I have a Scratch Wiki account!
I like: Python, CSS, Javascript, Rust

imfh
Scratcher
1000+ posts

PyRPG (Python Text Adventure)

ScratchCatHELLO wrote:

imfh wrote:

You might want to make it so there are multiple words you can use for the same action. For example, I kept trying to use “examine item” rather than “look at item” since that is what I usually use in other text games.

noted. is there a place i can find common command names?
Not that I know of.

ScratchCatHELLO wrote:

imfh wrote:

Also, a matter of preference, but you could use command.startswith(“blah”) rather than command == “blah”.

I've actually stopped slicing strings. now I'm using this method:
command = input().split
to make commands a bit easier to parse and make the code easier to understand. I'm not sure if this is the right method, but it works pretty well.
Yeah I think that way is actually much better in the long run. It is more difficult for things like “look at blah” though with multiple words. Maybe you could make a list of words to throw away? (eg. throw away “at”, interpret [“look”, “rock”] )

ScratchCatHELLO wrote:

imfh wrote:

It is also handy to have abbreviations for commands, particularly with movement. With Zork, for example, you can just type ‘w’ to go west, which becomes really helpful when the map gets larger. Another common abbreviation is an L for look.

I have abbreviations for movement commands (in the latest version), but I'll definitely think about adding abbreviations to commands like “look” or maybe “help”.
It might help to make a dictionary with synonyms. Eg.
words = {
    "look": ["look", "l", "examine", "see"],
    "grab": ["grab", "get", "pick", "loot"],
    "west": ["west", "w"]
}
if command in words['look']:
    ...

ScratchCatHELLO wrote:

thanks for the feedback!
No problem!

Scratch to Pygame converter: https://scratch.mit.edu/discuss/topic/600562/
zahmbie1
Scratcher
1000+ posts

PyRPG (Python Text Adventure)

Delta135
Scratcher
100+ posts

PyRPG (Python Text Adventure)

I haven't been on Scratch in 3 months -_-

how is the adventure going???


NorthenSuperCoders
Scratcher
100+ posts

PyRPG (Python Text Adventure)

Hello Everyone!
Do you want to Edit and Run your Codes with Python? Yes? - Follow My Video that I've Uploaded to my YouTube Official Channel
In E - Coders
How To Download & Install Python and Setup For Editing & Previewing || Best ★★★
https://www.youtube.com/watch?v=VSLhxl6gsC4
Watch now, Like, Share and Always Subscribe!! and To Be Up-To-Date, Also Turn on the bell

Last edited by NorthenSuperCoders (Aug. 21, 2021 12:33:33)


NorthenSuperCoders
A self-programmer - also writes books, him self.
===================================================
NorthenSuperCoders
Scratcher
100+ posts

PyRPG (Python Text Adventure)

We can always use the PyCharm - The World Best Python IDE For Editing, Making and Running Python Projects!

NorthenSuperCoders
A self-programmer - also writes books, him self.
===================================================
-Quantum_Studios-
Scratcher
500+ posts

PyRPG (Python Text Adventure)

NorthenSuperCoders wrote:

Watch now, Like, Share and Always Subscribe!! and To Be Up-To-Date, Also Turn on the bell
no u

Vote Rascal in 2022!
K710kl
Scratcher
14 posts

PyRPG (Python Text Adventure)

1.

Last edited by K710kl (Sept. 9, 2021 21:16:16)


K710kl

Powered by DjangoBB

Standard | Mobile