PHP计算单词中的字母(HANGMAN)

时间:2016-08-30 07:57:55

标签: php html

我正在尝试制作一个刽子手游戏。我在数组中有几个单词,当其中一个单词被选中时,我想要计算该单词中有多少个字母,这样它就可以制作那些空格或破折号。此外,我需要一种有效的方法将单词的每个字母放在屏幕上。每个字母都是不可见的,所以当猜到这封信时它会被显示出来。

<html>
<head>
<title> Hangman </title>
</head>
<body>
<h1> Hangman <h1>   
<?php
session_start(); 
$maxAttempts = 6; 
$letters = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o',
'p','q','r','s','t','u','v','w','x','y','z');
?>
<form name="lettersubmit" method="post" action="Hangman.php" > 
<input name="letterguess" type= "text" value="">
<input name="submit" type="submit" value="Guess a Letter!"><br>
<p> Guesses Remaining <p>
<input name="triesRemaining" type="text" value="<?php print("$maxAttempts"); ?>">
</form>
<?php
$letterguess = $_POST["letterguess"];

if($letterguess= $word){
    echo ("correct");
}
if(!isset($_POST["submit"])){
    $words  = array (
    "giants",
    "triangle",
    "particle",
    "birdhouse",
    "minimum",
    "flood",

    $word = $words[array_rand($words)];
);
}
if(isset($_POST["submit"])){
    $maxAttempts--;
}

$word = $words[array_rand($words)];
    echo $words[array_rand($words)];
?>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

您的计划仍处于早期阶段。您需要存储一些值,否则它将无法工作。请参阅手册中的session reference

您的实际问题可以通过以下方式解决:

// these both must be stored (see php session)
$letters_guessed_correct = array('g', 's', 'a');
$word = "giants"; // the current word which is searched for

foreach(str_split($word) as $char) {
    if (in_array($char, $letters_guessed_correct, true)) {
        echo $char;
    } else {
        echo '_';
    }
} 

这将输出

g_a__s

答案 1 :(得分:0)

要计算字符串中的字母数,您可以使用strlen()或多字节环境mb_strlen()