Show sourcecode
The following files exists in this folder. Click to view.
webbserverprogrammering/exercises/DICE/
Dice2.php
86 lines UTF-8 Windows (CRLF)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
<?php
/**
* A CDice class to play around with a dice.
*
*/
class CDice {
/**
* Properties
*
*/
public $rolls = array();
/**
* Roll the dice
*
*/
public function Roll($times) {
$this->rolls = array();
for($i = 0; $i < $times; $i++) {
$this->rolls[$i] = rand(1, 6);
}
}
/**
* Get the total from the last roll(s).
*
*/
public function GetTotal() {
return array_sum($this->rolls);
}
/**
* Get the average from the last roll(s).
*
*/
public function GetAverage() {
return round(array_sum($this->rolls) / count($this->rolls), 1);
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Tärningsexempel</title>
</head>
<body>
<h1>En tärning</h1>
<p>Tärningen kastas 6 gånger, här är resultatet.</p>
<?php
// To save the outcome of each dice roll
$rolls = array();
// Create an instance of the class
$dice = new CDice();
// Roll the dice
$times = 6;
$dice->Roll($times);
$rolls = $dice->rolls;
// Print out the results
$html = "<ul>";
foreach($rolls as $val) {
$html .= "<li>{$val}</li>";
}
$html .= "</ul>";
$html .= "<p> Summan = {$dice->GetTotal()} </p>";
// Alternative 1
// $html .= "<p> Summan = ".$dice->GetTotal()."</p>";
?>
<?=$html?>
<p>Medel = <?= $dice->GetAverage() ?>.</p>
</body>
</html>