沃梦达 / 编程问答 / php问题 / 正文

PHP CLI - 在后台执行操作的同时获取用户输入

PHP CLI - get user input while still doing things in background(PHP CLI - 在后台执行操作的同时获取用户输入)

本文介绍了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?

推荐答案

抱歉 Matthew,我将不得不取消接受您的答案,因为我自己找到了:

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 - 在后台执行操作的同时获取用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PHP CLI - 在后台执行操作的同时获取用户输入

基础教程推荐