开发者

How to parse a command line type instruction with PHP?

开发者 https://www.devze.com 2023-03-05 18:29 出处:网络
I have an idea for a text based game where I would pass commands and arguments to php for it to decide what to do with the player next.

I have an idea for a text based game where I would pass commands and arguments to php for it to decide what to do with the player next.

I would type say "go north" or something more complicated like "use key door" into an AJAX form which would send the command to the php script, and I want the php script to know what action it was using eg "use" and also the first and secon开发者_高级运维d arguments "key" and "door" and decide what to do next, but Im not sure how to go about it.

Please note I do NOT want to run this from the command line, but from a web based interface.


Say the AJAX form would send a request to /game.php?do=use+key+door...

Then in game.php you could:

$do = $_GET['do'];
list($action, $object) = split(' ', $do, 2);
// $action == 'use'
// $object == 'key door'

You can check out a code and output example here.

(Same goes for$_POST['do'] if you choose to implement your form in POST.)


It seems to me that if you are using ajax, you would use either get or post so in your php script you simply check $_GET or $_POST.


You can acquire the entire string of arguments from one request (textarea, input). You can get this information from _GET or _POST. As for how to handle the information, you have to build a parser. Its complexity is up to you. One of the simpler things you could do would be to split up the request into tokens by spaces (you would get 'go', 'north', or 'use', 'key', 'door'). Inspect your list of keywords to add actions to the stack (go, use) and add actors and actees to the stack (key, door, north). Throw out unnecessary words (on, a, the, etc.). Then go through the stack. If you get "use," you expect two arguments following (actor and actee, e.g. use the key on the door). If you are missing this information, or if it's nonsense (use the blorb on the foon) tell the user the command is invalid. Give them a list of common commands. You may also want to give them a bit of leeway for certain objects and misspellings. You can also read more about lexical parsers to get a better idea about how to do this in a more complex manner.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号