Källkod
Följande filer och mappar finns under mappen webbserverprogrammering.
Mappar visas till vänster och filer till höger. Klicka på en fil eller mapp för att öppna nedan eller visa dess innehåll.
webbserverprogrammering/exercises/classes_dice/
10 filer
Dice.php
DiceImage.php
Histogram.php
dice_1.php
dice_2.php
dice_3.php
dice_4.php
dice_5.php
dice_6.php
dice_7.php
DiceImage.php
Histogram.php
dice_1.php
dice_2.php
dice_3.php
dice_4.php
dice_5.php
dice_6.php
dice_7.php
dice_3.php
83 lines UTF-8 Windows (CRLF)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
<?php
error_reporting(-1); // Report all type of errors
ini_set('display_errors', 1); // Display all errors
ini_set('output_buffering', 0); // Do not buffer outputs, write directly
?>
<!DOCTYPE html>
<html lang="sv">
<head>
<title>Tärning 3</title>
<meta charset="utf-8">
<style type="text/css">
body {
font-family: Arial;
}
</style>
</head>
<body>
<h2>En tärning</h2>
<?php
class Dice {
private $sides;
private $rolls = [];
function __construct($sides = 6) {
$this->sides = $sides;
}
function roll($times = 1) {
for ($i = 0; $i < $times; $i++) {
$this->rolls[count($this->rolls)] = rand(1, $this->sides);
}
}
function printRolls() {
echo "<ul>";
foreach ($this->rolls as $roll) {
echo "<li>$roll</li>";
}
echo "</ul>";
}
function getSumOfRolls() {
return array_sum($this->rolls);
}
function getAverageRoll() {
return round($this->getSumOfRolls() / count($this->rolls), 2);
}
}
if (isset($_GET["roll"]) && $_GET["roll"] > 0)
$rollCount = $_GET["roll"];
else
$rollCount = 6;
echo "<p>En tärning med 6 sidor kastas $rollCount gånger.</p>";
?>
Kasta: <a href="?roll=3">3 gånger</a>, <a href="?roll=6">6 gånger</a>, <a href="?roll=11">11 gånger</a>, <a href="?roll=26">26 gånger</a>.
Default är 6 gånger. Alla heltal större än 0 är tillåtna.
<?php
$myDice = new Dice(); // default is 6 sides
$myDice->roll($rollCount); // roll X times
$myDice->printRolls();
?>
<p><strong>Summa:</strong> <?= $myDice->getSumOfRolls() ?></p>
<p><strong>Medelvärde:</strong> <?= $myDice->getAverageRoll() ?></p>
</body>
</html>