私はPHP
セッションの仕組みに頭を悩ませようとしています。私は単に、最初のプレーヤーが秘密の単語を入力し、2番目のプレーヤーが一度に1文字を推測し始める絞首刑執行人ゲームを試しています。
レッツは、秘密の言葉であることを言うcat
、プレイヤー2トライ、c
そしてa
その後s
。最終的な出力をにしたいと思いますc a _
。
<?php
session_start();
global $word;
global $guess;
global $hangman;
if (isset($_POST['player1'], $_POST['word'])) {
$_SESSION['word'] = $_POST['word'];
$word = $_SESSION['word'];
}
if (isset($_POST['player2'], $_POST['guess'])) {
$_SESSION['guess'] = $_POST['guess'];
$guess = $_SESSION['guess'];
}
$counter = 0;
$word = strtolower($_SESSION['word']);
$guess = strtolower($_SESSION['guess']);
echo $word . "<br>";
$found = [];
$counter = 0;
for ($i = 0; $i < strlen($word); $i++) {
if ($counter < strlen($word)) {
if (strpos($word[$i], $guess) !== false) {
$found[] = $guess;
$counter++;
} else {
$found[] = " _ ";
}
}
}
print_r($found);
found
配列のすべての内容を印刷する代わりに、毎回1文字しか印刷できません。ただし、前述のように、完全に連結された文字列を見たいと思います。
ユーザー入力データを$ _SESSION配列に継続的にプッシュしてから取得するにはどうすればよいですか?
これを行う簡単な方法は、変数を$ _SESSION配列の要素にバインドすることです。これは、マニュアルにはない便利なトリックです。簡単な例:
$foo =& $_SESSION['foo'];
その割り当ては同じ値にバインドされるため$foo
、$_SESSION['foo']
へのすべての更新はへの更新$foo
でもあり$_SESSION['foo']
ます。
絞首刑執行人ゲームのスタイルでの使用例を次に示します。
<?php
session_start();
$word =& $_SESSION['word']; //bind $word with $_SESSION['word']
$found =& $_SESSION['found']; //bind $found with $_SESSION['found']
if (isset($_REQUEST['word'])) {
$word = str_split($_REQUEST['word']);
$found = array_fill(0, count($word), '_');
}
if (isset($_REQUEST['guess'], $word, $found)) {
$guess = array_fill(0, count($word), $_REQUEST['guess']);
$found = array_replace($found, array_intersect($word, $guess));
}
echo join(' ', $found);
結合すると、の値$word
とは、$found
実行する必要がなく、セッションデータの一部として保存されます$_SESSION['word'] = $word;
と$_SESSION['found'] = $found;
、スクリプト内の任意の場所。
ブラウザでのテストを簡単にするため$_REQUEST
に、の代わりにを使用していることに注意してください$_POST
。必要に応じて変更します。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加