Hangman(吊死鬼)經典猜字遊戲,隨 Yii 框架附贈。透過此例掌握:MVC 分層、狀態持久化、URL 管理、表單處理、視圖渲染等核心流程。

<?php
class GameController extends CController {
// 屬性透過 getter/setter 綁定頁面狀態
public function getWord() {
return $this->getPageState('word');
}
public function setWord($value) {
$this->setPageState('word', $value);
}
public function actionIndex() {
$this->newGame();
$this->render('guess');
}
public function newGame() {
$words = array('YII', 'FRAMEWORK', 'PHP', 'DEVELOPER');
$this->word = $words[array_rand($words)];
$this->guessed = array();
$this->wrongGuess = 0;
}
public function actionGuess() {
$letter = isset($_GET['g']) ? strtoupper($_GET['g'][0]) : '';
if ($letter && ($result = $this->guess($letter)) !== null) {
$this->render($result ? 'win' : 'lose');
} else {
$this->render('guess');
}
}
protected function guess($letter) {
if (isset($this->guessed[$letter])) return null; // 已猜過
$this->guessed[$letter] = true;
if (strpos($this->word, $letter) === false) {
$this->wrongGuess++;
if ($this->wrongGuess >= 6) return false; // 失敗
}
if (strspn($this->word, implode('', array_keys($this->guessed))) == strlen($this->word)) {
return true; // 勝利
}
return null; // 繼續
}
}
getPageState()/setPageState() 自動處理隱藏欄位或 Session 儲存,無需資料庫。'game/guess/<g:\w>'=>'game/guess' 將 /game/guess/A 映射至 actionGuess 並傳遞 g=A。CHtml::linkButton() 產生提交字母的按鈕鏈接。<h2>猜單詞遊戲</h2>
<p>單詞: <strong><?php echo $this->displayWord(); ?></strong></p>
<p>錯誤次數: <?php echo $this->wrongGuess; ?>/6</p>
<div>
<?php
for ($i = 65; $i <= 90; $i++) {
$letter = chr($i);
$disabled = isset($this->guessed[$letter]);
echo CHtml::linkButton($letter, array(
'submit' => array('guess', 'g'=>$letter),
'disabled' => $disabled,
)) . ' ';
}
?>
</div>
getPageState/setPageState 實現跨請求持久化createUrl() 自動生成友善網址CHtml 產生互動元素,保持關注點分離guess() 方法,清晰可測試