• Create Account

# Zork like text input

Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

9 replies to this topic

### #1ZorkLover23  Members   -  Reputation: 101

Like
0Likes
Like

Posted 06 September 2012 - 11:33 PM

Hey I have just started programming not so long ago and I was thinking about making a Zork like game but I keep getting stuck. I really want it to have text input like Zork so the player can type for example "Hello" and the game will respond with "Hi" or "Greetings". can any one help me with this Thanks.

### #2Servant of the Lord  Crossbones+   -  Reputation: 12677

Like
2Likes
Like

Posted 07 September 2012 - 01:24 AM

Well, the actual implementation depends on the language you are using, but the basic idea is:
if(playerInput == "hello")
{
Display("Greetings!");
}
else if(playerInput == "goodbye")
{
Display("Cya later!");
}
else
{
Display("I don't recognize that sentence.");
}


To further expand on it, you could add verbs and nouns:
Words = BreakIntoWords(playerInput);
if(FirstWord == "Use")
{
if(SecondWord == "Banana" AND PlayerHas("banana"))
{
Display("You threw the banana at the Rhino in disgust!")
}
else if(SecondWord == "Apple" AND PlayerHas("apple"))
{
Display("You fed the Rhino your apple, and he munches on it thoughtfully.")
Display("Rhino: 'Mmm, that was delicious. Here, you can have my extra backup horn as thanks.")

GivePlayer("Rhino Horn");
Display("Dun dun dun duhhh! You got the Rhino Horn! You can now go gore some Kangaroos.")
}
else if(SecondWord == "")
{
Display("What do you want to use?")
}
else
{
Display("You don't have any " + SecondWord)
}
}
else if(FirstWord == "Take")
{
if(ExistsInRoom(SecondWord))
{
Display("You take the " + SecondWord)
GivePlayer(SecondWord);
RemoveFromRoom(SecondWord);
}
else if(SecondWord == "")
{
Display("What do you want to take?")
}
else
{
Display("You can't take any " + SecondWord)
}
}
else
{
Display("I don't know what you said. Could you try: 'Use', 'Take', 'Look', 'Go', or 'Talk'?")
}

Required knowledge:
• 'if()' statements
• 'if else()' statements
• 'else' statements
• 'while' loops
• What kind of food rhinos like
• Strings
• String comparison
Tips:
• If you convert player input to lowercase before comparing it, you only have to check for "the word", and you automaticly handle "The Word", "THE WORD", and "ThE WoRd".
• If you break things into small functions, you can make your program more stable, easy to read, easy to expand, and also save alot of typing.
• Any time you find yourself copying and pasting your code into multiple places, turn it into a function instead.
• If you want to do something, and find out that you can't, instead of getting frustrated, ask yourself how you can use the limitation to improve your game, or how you can work around the limitation.
• A quick google search shows that Rhinos actually do like apples. Odd.
• Quick google searches can also answer most problems you encounter - but make sure you actually understand the answer, don't just copy and paste the answer.
• Everyone knows that mules have a terrific sense of humor... which is why they make such great game designers.
• Using graph paper (or plain computer paper and a ruler) map out the rooms, location of items, and the required order of getting/using each item, before you actually start adding anything other than test rooms.
• Hard code everything if you have to. Use global variables if you need to.
• Aim small for your first game (20 rooms top). For your second game, figure out how to load text files, and make rooms, items, npcs, and the connections between rooms be as much as possible controlled by files and not hard-coded. Also try to not use a single global variable. Consider it a challenge or puzzle to solve.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.

All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.                                                                                                                                                       [Need free cloud storage? I personally like DropBox]

### #3Endurion  Crossbones+   -  Reputation: 2804

Like
1Likes
Like

Posted 07 September 2012 - 01:41 AM

I'd actually do not direct string comparison. It's easy in the beginning, but will grow too fast to be managable.

Back then the programmer had a list of verb strings (with index so different verbs with the same id existed) and list of object strings.

Then you would parse the input string, split for spaces and try to find all the single words in the lists. The puzzle logic would then analyse the verb and object indices and act accordingly.
If you want to get fancy allow for a secondary object (put xxx in yyy) and fill words that would be discardid ("the", "in", etc.).

Steps:
* Split a string by a separator (space)
* Handle string to index maps (std::map<std::string,int>)

Edited by Endurion, 07 September 2012 - 01:44 AM.

Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

### #4ZorkLover23  Members   -  Reputation: 101

Like
0Likes
Like

Posted 07 September 2012 - 07:26 AM

Hey and thanks guys Im using c++ I forgot to mention that sorry.

### #5Inuyashakagome16  Members   -  Reputation: 829

Like
0Likes
Like

Posted 07 September 2012 - 07:48 AM

If you could use .net i'm sure a dictionary would work fine as well. http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

To me, if you're using C++ at first I would say string comparison as well. (From if this == this) or possibly with an array? Just store an array of commands for a subset of the program. (ie. Attacking, moving, talking, etc)

### #6Servant of the Lord  Crossbones+   -  Reputation: 12677

Like
0Likes
Like

Posted 07 September 2012 - 10:43 AM

I'd actually do not direct string comparison. It's easy in the beginning, but will grow too fast to be managable.

I wouldn't use it either, but I don't know the OP's skill level, and am guessing from his post he hasn't yet mastered basic comparison. I could be wrong though!

Edited by Servant of the Lord, 07 September 2012 - 11:07 AM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.

All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.                                                                                                                                                       [Need free cloud storage? I personally like DropBox]

### #7Inuyashakagome16  Members   -  Reputation: 829

Like
0Likes
Like

Posted 07 September 2012 - 11:10 AM

I'd actually do not direct string comparison. It's easy in the beginning, but will grow too fast to be managable.

I wouldn't use it either, but I don't know the OP's skill level, and am guessing from his post he hasn't yet mastered basic comparison. I could be wrong though!

Instead of direct comparison what should be used? Because that's what pops into my head first when i think of string and comparing.

### #8Servant of the Lord  Crossbones+   -  Reputation: 12677

Like
3Likes
Like

Posted 07 September 2012 - 11:31 AM

For handling alot of string comparisons std::map abstracts it better, making it easier to make your game data-driven and less hardcoded.

Probably std::map<std::string, scriptCallbackFunction>
Or std::map<std::string, classThatHandlesAction>
Or maybe using C++11 lambdas: std::map<std::string, lambdasCallback>,but in this situation that's unlikely.

Then you could do:
actionMap.push_back(std::make_pair("Use", UseActionHandler(pointerToPlayerData, pointerToWorldData)));
actionMap.push_back(std::make_pair("Go", GoActionHandler(pointerToPlayerData, pointerToWorldData)));
actionMap.push_back(std::make_pair("Say", SayActionHandler(pointerToPlayerData, pointerToWorldData)));
actionMap.push_back(std::make_pair("Get", GetActionHandler(pointerToPlayerData, pointerToWorldData)));
actionMap.push_back(std::make_pair("Attack", AttackActionHandler(pointerToPlayerData, pointerToWorldData)));
actionMap.push_back(std::make_pair("Run", RunActionHandler(pointerToPlayerData, pointerToWorldData)));
actionMap.push_back(std::make_pair("Climb", ClimbActionHandler(pointerToPlayerData, pointerToWorldData)));


You could also easily handle synonyms.
actionMap.push_back(std::make_pair("Say", SayActionHandler(pointerToPlayerData, pointerToWorldData)));
actionMap.push_back(std::make_pair("Speak", SayActionHandler(pointerToPlayerData, pointerToWorldData)));
actionMap.push_back(std::make_pair("Talk", SayActionHandler(pointerToPlayerData, pointerToWorldData)));

actionMap.push_back(std::make_pair("Go", GoActionHandler(pointerToPlayerData, pointerToWorldData)));
actionMap.push_back(std::make_pair("Walk", GoActionHandler(pointerToPlayerData, pointerToWorldData)));


Or maybe use Regex instead (which is also abstract comparison of complex strings), and use a single action handler.
Or just map the word "Go" to a script function that handles the action.
actionMap.push_back(std::make_pair("Go", "handle_go"));

if(actionMap.contains(playerFirstWord))
{
functionName = actionMap[playerFirstWord];
CallScriptFunction(functionName, inputWords, playerPtr, worldPtr);
}
else
{
Output("I don't recognize " +playerFirstWord + ". Did you mean: " + actionMap.keys());
}

This doesn't keep you from having to write the logic, but it makes the logic easier to alter or expand during development, and easier to understand than 1500 lines of if(), else-if(), spaghetti going several scopes deep, and when and where you need actual if() statements, you only have them grouped together in twos and threes based on context, not hundreds.

It also makes it easier to create things like:
"Give to Bob the Monkey" -> You gave Bob, the Friendly Monkey you found. Bob looks at you quizzically.

'Give' goes to GiveActionHandler or script function, parses 'to' if present and discarded it, and using the pointer to the world, finds what NPCs exist in the room the player is in, finds a NPC named 'Bob' (otherwise outputting, "You don't see anyone named Bob around here"), parses and discards 'the' if present. Then using the pointer to the player's data, checks if the player has an item called 'Monkey' (otherwise outputting, "You don't have a Monkey"), and passes the text "Monkey" to Bob's script file for processing.

Bob's script file looks like this:
HandleLook()
{
Output("Bob stares back at you.")
}

HandleTalk()
{
//...
}

HandleGive(itemName, playerPtr, worldPtr)
{
if(itemName == "Monkey")
{
playerPtr.RemoveItem(itemName);
Output("Bob: You found Fibi! Oh thank you, " + playerPtr.name + "! I looked all over for her.")
Output("Bob: Here, take my spare scuba gear as thanks. You may find it comes in handy.")

playerPtr.GiveItem("Scuba gear");
}
else
{
Output("Bob: Uh, thanks, but I'm not interested in " + itemName + "s at the moment.');
}
}

This would be my first attempt, anyway. When working on the game, a better architecture may come to mind once I encounter the strengths and limitations of this approximation, having never worked on this type of game before (aside from a few attempts when first starting out as a programmer seven years ago).

Edited by Servant of the Lord, 07 September 2012 - 11:55 AM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.

All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.                                                                                                                                                       [Need free cloud storage? I personally like DropBox]

### #9BeerNutts  Crossbones+   -  Reputation: 1892

Like
1Likes
Like

Posted 07 September 2012 - 12:23 PM

If just making interactive fiction games (text adventures) is your goal, there are a few good game-makers available, and pretty dang cool.

http://inform7.com/ Inform is a good one

Take a look at them, and see if it fits what you're looking for.

If you want to do it specifically in C++, then these may at least give you an idea of how to move forward.

Good luck, and have fun!
My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

### #10jefferytitan  Members   -  Reputation: 1039

Like
1Likes
Like

Posted 08 September 2012 - 04:32 AM

Essentially you're trying to write something that parses English (or whatever language), which is challenging as human speech is generally not strictly rule-based and is sometimes ambiguous. Generally assume that there will be limitations on your program's ability to parse text, so you will have to draw a line somewhere.

On to practicalities, the guys here have suggested some good stuff. The solution depends upon your programming skill and whether you just wan results or want to do it yourself. The interactive fiction engines mentioned do a pretty good job of interpreting text.

If you want to write your own you can do what the guys mentioned above. Or you could take the more complex route and create a grammar and parse the text into trees based on the grammars and see which fits best, for example the rules "[verb] [noun phrase]" (e.g. "go north") and "[noun]" (e.g. "north"). If you want to be really smart, interpret the nouns (and maybe even verbs) in a context-sensitive way, e.g. if they say "pick up the sword" interpret sword as a nearby sword that they are not holding. You can rule out interpretations if there are no matching nouns in the context.

Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

PARTNERS