php - 如何制作可以从数组中为刽子手游戏选择单词的按钮
问题描述
我正在尝试为学校项目创建一个刽子手游戏,但我被卡住了。所以我有一个单词数组,我希望玩家选择其中一个单词,以便另一个可以尝试猜测字母/单词。
像这样的东西:示例
这是单词数组:
public $words = [
'apple',
'tree',
'car',
'school',
'table',
'laptop',
'house',
'summer', ];
我不知道这是否有帮助,但这是我的其余代码:
<?php
class game {
public $letters = [];
public $chosenword;
public $words = [
'apple',
'tree',
'car',
'school',
'table',
'laptop',
'house',
'summer',
];
function randomWord() {
$this->chosenword = $this->words[rand ( 0 , count($this->words) -1)];
return $this->chosenword;
}
function addLetter($letter){
array_push($this->letters, $letter);
}
function ShowWord(){
$pattern = '/[^' . implode('', $this->letters) . ']/';
return preg_replace($pattern, '-', $this->chosenword);
}
function isWord($woord, $randomRandom){
if ($woord == $randomRandom) {
return "Found";
}
return "Not Found";
}
}
$game = new game ();
$randomRandom = $game ->randomWord();
echo $randomRandom;
$game->addLetter('a');
echo "<br>";
echo $game->ShowWord();
echo "<br>";
echo $game->isWord('apple', $randomRandom);
?>
我想在不同的 PHP 文件中制作按钮,但真的想不出我应该从哪里开始。有没有人给我提示或可以告诉我如何继续?
提前致谢!
解决方案
一种方法是使用表单并将您的表单发布chosenword
到服务器。在此示例中,首先显示表单。提交后,游戏将启动:
// your game class
class game {
public $letters = [];
public $chosenword;
public $words = [
'apple',
'tree',
'car',
'school',
'table',
'laptop',
'house',
'summer',
];
function randomWord() {
$this->chosenword = $this->words[rand ( 0 , count($this->words) -1)];
return $this->chosenword;
}
function addLetter($letter){
array_push($this->letters, $letter);
}
function ShowWord(){
$pattern = '/[^' . implode('', $this->letters) . ']/';
return preg_replace($pattern, '-', $this->chosenword);
}
function isWord($woord, $randomRandom){
if ($woord == $randomRandom) {
return "Found";
}
return "Not Found";
}
}
// init a new game
$game = new game();
// if the form is not sent before, show the form
if( !isset( $_POST['chosenword'] ) ) { ?>
<form action="" method="post">
<select name="chosenword">
<?php foreach( $game->words as $word ) { ?>
<option value="<?= $word; ?>"><?= $word; ?></option>
<?php } ?>
</select>
<button type="submit">Submit</button>
</form>
<?php } else {
// this will be executed if the form was sent before
// set the chosenword from the post data
$game->chosenword = $_POST['chosenword'];
// do the rest of your code
$randomRandom = $game->randomWord();
echo $randomRandom;
$game->addLetter('a');
echo "<br>";
echo $game->ShowWord();
echo "<br>";
echo $game->isWord('apple', $randomRandom);
}
?>
推荐阅读
- qt - 我的应用重新加载时如何自动播放音乐
- laravel - 如何从与自身有关系的项目中检索完整的关系?
- python - 访问views.py中的静态文件
- ruby-on-rails - Mime::Type::InvalidMimeType(“charset=utf-8”不是有效的 MIME 类型)
- javascript - 在使用 Redux 更新状态后渲染所有元素
- opengl - 如何在OpenGL中映射球体表面上的点击点?
- java - Android Studio 中的某些 Java 文件未显示在 GitHub Desktop 上
- python - 令牌键中的反斜杠
- spring-integration - 将 .json 文件转换为 Map 的问题
- lua - 像在 C 编程中一样在 lua 中创建位域结构