PHP CLI - 在后台运行时获取用户输入 [英] PHP CLI - get user input while still doing things in background

查看:197
本文介绍了PHP CLI - 在后台运行时获取用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一款用PHP编写并在控制台中运行的游戏。回想一下旧的MUD和其他基于文本的游戏,甚至是一些ASCII艺术!

I'm working on a game, written in PHP and that runs in a console. Think back to old MUDs and other text-based games, even some ASCII art!

无论如何,我想要做的就是让事情发生,同时也接受用户输入。

Anyway, what I'm trying to do is have things happening while also accepting user input.

例如,让我们说这是一场双人游戏,而玩家1正在等待玩家2进行移动。只需听一条消息即可轻松完成。

For instance, let's say it's a two player game and Player 1 is waiting for Player 2 to make a move. This is easily done by just listening for a message.

但是如果玩家1想要改变某些选项怎么办?如果他们想要查看有关游戏状态方面的详细信息怎么办?承认游戏怎么样?在等待对手移动时,玩家可能想做很多事情。

But what if Player 1 wants to change some options? What if they want to view details on aspects of the game state? What about conceding the game? There are many things a Player may want to do while waiting for their opponent to make a move.

不幸的是,我现在最好的事实是完全按Ctrl + C杀死该计划。然后另一个玩家被挂起,直到连接断开。哦,游戏完全丢失了。

Unfortunately the best I have right now is the fact that Ctrl+C completely kills the program. The other player is then left hanging, until the connection is dropped. Oh, and the game is completely lost.

用户输入 fgets(STDIN)。但是这会阻止执行直到收到输入(这通常是一件好事)。

I get user input with fgets(STDIN). But this blocks execution until input has been received (which is usually a good thing).

这样的控制台程序是否可以同时处理输入和输出?或者我应该只看一些其他界面?

Is it even possible for a console program like this to handle input and output simultaneously? Or should I just look at some other interface?

推荐答案

对不起马修,我将不得不接受你的回答,因为我自己找到了它:

Sorry Matthew, I'm going to have to un-accept your answer, because I have found it myself:

使用以下代码接收用户输入,同时还要做其他事情:

Use the following code to receive user input while still doing something else:

while(/* some condition that the code running is waiting on */) {
    // perform one step or iteration of that code
    exec("choice /N /C ___ /D _ /T _",$out,$ret);
    // /C is a list of letters that do something
    // /D is the default action that will be used as a no-op
    // /T is the amount of time to wait, probably best set to one second
    switch($ret) {
        // handle cases - the "default" case should be "continue 2"
    }
}

然后可以用它来中断循环并进入选项菜单,或触发其他一些事件,或者如果正确使用,甚至可以用来键入命令。

This can then be used to interrupt the loop and enter an options menu, or trigger some other event, or could even be used to type out a command if used right.

这篇关于PHP CLI - 在后台运行时获取用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆