私はあなたが4つのランダムな色を与えられ、勝つために正しいワイヤーを切る必要がある爆弾処理ミニゲームを作ろうとしています。私が今抱えている問題は、それを取得する方法を理解しているので、カットする色を選択するプレーヤーからの入力が必要な各部分にタイマーがあり、タイマーがなくなるとプレーヤーは失敗します。
setTimeoutを間違って使用しているように感じます。希望どおりに機能させる方法がわかりません。
const asdf = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
asdf.question('What will you cut?', wire => { //First part where you are given 4 colors
setTimeout(asdf.question, 7000, console.log("asdf"))
if (!allowedColors.includes(wire)) {
console.log("You need to pick one of the 4 colors!");
return;
}
console.log(`You cut ${wire}!`);
asdf.close();
ruleEnforcer(wire, fourRandomColors, f);
})
調整しなければならないことがいくつかあります。
setTimeout
のコールバック関数を呼び出しているquestion
ので、ユーザーが色を入力してEnterキーを押すと、タイマーが開始されます。
使用方法は、7000ミリ秒後setTimeout
に関数を呼び出し、呼び出された関数asdf.question
にconsole.log("asdf")
引数として渡します。setTimeoutのAPI定義をもう一度確認する必要があります
setTimeout
は非同期であるため、タイマーが切れたときにゲームを停止したい場合は、ゲーム全体も非同期にする必要があります
このプロセスの非常に基本的な実装(複数の質問や実際に入力された色が正しいかどうかの確認なし)は、次のようになります。
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
// start game and react to callback
startGame((win) => {
readline.close()
if(win) {
console.log('you won')
} else {
console.log('you lost')
}
})
function startGame(callback) {
// set timer when game starts, if it runs out player loses -> call callback false
let timer = setTimeout(() => {
callback(false)
}, 7000);
readline.question('What will you cut?', wire => {
// stop timer from running when player enters a color
clearTimeout(timer);
// wire is correct and player won the game -> call callback true
callback(true)
})
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加