Show sourcecode
The following files exists in this folder. Click to view.
webbserverprogrammering/exercises/DICE/
Dice3.php
94 lines UTF-8 Windows (CRLF)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
<?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 <a href='?roll=XYZ'>1 gång</a>, <a href='?roll=3'>3 gånger</a>, <a href='?roll=6'>6 gånger</a>, <a href='?roll=25'>25 gånger</a> och 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 = isset($_GET['roll']) && is_numeric($_GET['roll']) ? $_GET['roll'] : 1;
/* Alternative
if (isset($_GET['roll']) && is_numeric($_GET['roll']) ) { $times = $_GET['roll']; }
else { $times = 1}
*/
if($times > 100) {
die("Kan inte kasta fler än 100 gånger.");
}
$dice->Roll($times);
$rolls = $dice->rolls;
// Print out the results
$html = "<ul>";
foreach($rolls as $val) {
$html .= "<li>{$val}</li>";
}
$html .= "</ul>";
$html .= "<p> Du kastade ".count($rolls)." gånger. </p>";
$html .= "<p> Summan = {$dice->GetTotal()} </p>";
// Alternative 1
// $html .= "<p> Summan = ".$dice->GetTotal()."</p>";
?>
<?=$html?>
<p>Medel = <?= $dice->GetAverage() ?>.</p>
</body>
</html>