<?php
/**
*
* 出題引擎一枚
*
* @author Tourmaline
* @copyright (c) 2013, Unary Inc.
*/
class QuestionEngine {
/**
* 出題范圍
* @var string $scope
*/
public $scope = array(1, 100);
/**
* 包含的運算符,含有多個則混合出題
* @var string $operators
*/
public $operators = '+-';
/**
* 運算次數
* @var int
*/
public $optTimes = 1;
public function generate() {
//按運算次數產生一組數值
start:
for ($index = 0; $index < $this->optTimes + 1; $index++) {
$elements[] = $this->randomValue();
}
$operatorType = strlen($this->operators); //有幾個運算符供選擇
//開始組裝算式
$question = '';
for ($index = 0; $index < count($elements); $index++) {
$question.=' ' . $elements[$index] . ' '; //放一個數字進來
if ($index < count($elements) - 1)//如果不是最後一個數字的話,在後面加個運算符
$question.=substr($this->operators, mt_rand(0, $operatorType - 1), 1);
}
eval('$anwser = ' . $question . ';');
if ($anwser < 0) { //排除結果為負數的情況
$elements = array();
goto start; //需PHP5.3的支持
}
echo "$question= " . $anwser;
}
/**
* 產生一個范圍內的隨機值
*
* @return int
*/
protected function randomValue() {
return mt_rand($this->scope[0], $this->scope[1]);
}
}
測試
<?php include 'QuestionEngine.class.php'; $hello = new QuestionEngine(); $hello->generate(); ?> 結果:26 + 85 = 111