I am working on a small dice game just for fun and dont understand how to solve the followig problem:
The problem is that everytime you roll the dice you should input a number (only number 1)
And once that is done, the program will output an svg image of a dice displaying a random number ranging between 1 and 6. You will get an arbitrary number of runs, up until you reach the dice value 1. At that point the game will terminate, and your total score will be evaluated.
The problem I have is that the program only evaluates the latest point acquired. I really can´t seem to fix it though.
the form
$form = <<< EOD
<div>
<form action='{$_SERVER['PHP_SELF']}' method='get'>
<fieldset>
<input type='text' name='antal' value='{$antal}' />
<button type='submit'>Kasta</button>
</fieldset
</form>
<a href='{$_SERVER['PHP_SELF']}'>Starta om</a>
</div>
EOD;
the functions that do the random dice roll
class CDice {
private $iLastThrows = Array();
public function Roll() {
return rand(1,6);
}
public function RollRepeatedly($aNumber) {
$this->iLastThrows = Array();
for($i=1; $i<=$aNumber; $i++) {
$this->iLastThrows[$i] = $this->Roll();
}
return $this->iLastThrows;
}
public function GetLastThrows() {
return $this->iLastThrows;
}
}
This is the function that displays the correct svg dice, I removed the svg code. Each GetDice1, 2, 3 correspond to a function containing the svg code. public function GetSvg($aDice) {
$html = $this->GetSvgHeader();
switch($aDice) {
case '1': $html .= $this->GetDice1(); break;
case '2': $html .= $this->GetDice2(); break;
case '3': $html .= $this->GetDice3(); break;
case '4': $html .= $this->GetDice4(); break;
case '5': $html .= $this->GetDice5(); break;
case '6': $html .= $this->GetDice6(); break;
}
$html .= "</svg>";
return $html;
}
This is how I am evaluating the TOTAL, which is not working correctly.
public function Total($anArray) {
foreach($anArray as $key => $value){
return array_sum($anArray);
}
}
$antal = filter_input(INPUT_GET, 'antal', FILTER_VALIDATE_INT);
if($antal) {
$dice->RollRepeatedly($antal);
//$slag = $dice->iLastThrows;
$slag = $dice->GetLastThrows();
$total = $histogram->Total($slag, 1);
// Show all dices as Svg
foreach($slag as $key => $value) {
$diceHtml .= $dice->GetSvg($value);
}
// Present the result in text'
Lastly I check the value to make sure that once it reaches 1, I will end the program
if($value != 1){
$html
{$form}
{$diceHtml}
}
else{
$html = <<<EOD
<div>
<p>Game over.</p>
<p>You threw a ONE.</p>
<p>Total points: {$total}</p>
<div>
{$diceHtml}
</div>
EOD;