Alfredo's blog

Backgammon - an HTML/Javascript game for mobile and desktop browsers

Go to http://mytinylab.com/out/backgammon/index.htm to play backgammon with a friend. You can play it on Android (tested on Firefox in a Galaxy S2) or a desktop (tested in IE9, Firefox, and Chrome). The default Android web browser and Dolphin don't show the board image for some reason. I'll look at that problem at some other time. Until that's fixed use Firefox on Android.

Note that I said "play ... with a friend." The code has no logic regarding the rules of the game. It just simulates a physical backgammon board. You and your friend take care of the rules and moving the pieces.

The code is taken from other sources and modified to fit my needs. The original code was written by Mark Khan. My contribution was to make draggable elements you click come to the front of everything else. So, if you have several images that can be dragged then clicking on an image will bring it to the front of other images. This is useful in doll-dressing games or doll-house games (show a piece of furniture in front of or behind other pieces of furniture). I haven't seen this feature in any other drag and drop Javascript code. Minor contributions were the backgammon theme, pieces, and dice.

The bit of Javascript code that handles mobile is from Ross Boucher. It makes drag and drop work in mobile devices by translating mouse events to mobile events. Without this code the game will only work on desktop browsers.

There you have it, a physical backgammon board and pieces simulation written in HTML and Javascript that allows drag and drop in mobile and desktop browsers with the added benefit that elements can be brought to the front. Enjoy the code!

Monte Carlo to Solve Monte Hall

The Monte Hall Problem (http://en.wikipedia.org/wiki/Monty_Hall_problem) is a probability puzzle that says:

"Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice?"

Let's solve the Monte Hall Problem using a Monte Carlo simulation. We'll write a PHP program that simulates thousands of games and random choices. It will simulate you choosing a door randomly, Monte Hall opening one of the remaining doors (one without a car), and the result if you don't switch doors and if you switch doors.

Before you run the program, should you switch to the other door or stick with your choice?

<?php
// Using a Monte Carlo Simulation to solve the Monte Hall Problem by My Tiny Lab LLC (http://mytinylab.com). 2011/02/20
$car = 1;

$youDidntSwitchDoors_wins = 0; // how many times you win the car if you don't switch
$youSwitchedDoors_wins = 0; // how many times you win the car if you switch doors

$iterations = 100000; // # of iterations to solve the Monte Hall Problem
for ( $iters=0; $iters < $iterations; $iters++) {
// Randomly assign a car (value 1) and two goats (values 1 and 2) to three doors
$door[1] = rand(1,3);
// $door2 can't be the same value as $door1
do { $door[2] = rand(1,3);}while ($door[2] == $door[1]);
// $door3 can't be the same value as $door1 and $door2
do {$door[3] = rand(1,3);} while (($door[3] == $door[1]) || ($door[3] == $door[2]));

// Your random choice of door
$yourChoiceOfDoor = rand(1,3);

// Monte Hall randomly opens one of the other doors that don't have a car
do { $doorOpenedByMonte = rand(1,3);} while ($door[$doorOpenedByMonte] == $car);

// if you don't switch to the other door
if ($door[$yourChoiceOfDoor] == $car) {$youDidntSwitchDoors_wins++;}

// if you switch to the other door
if (($door[$yourChoiceOfDoor] != $car)) {$youSwitchedDoors_wins++;}
}

echo "If you don't switch you win ".$youDidntSwitchDoors_wins/$iterations."% of the time<br/>";
echo "If you switch you win ".$youSwitchedDoors_wins/$iterations."% of the time<br/>";
?>

That's all there is to the simulation. If you run it, you will see that not switching has a 1/3 chance of winning the car. Switching has a 2/3 chance of winning the car.

Update (2011/02/22): Here is the code in javascript:

<html>
<head>
<script text="type/javascript">
function start() {
var car = 1;

var youDidntSwitchDoors_wins = 0; // how many times you win the car if you don’t switch
var youSwitchedDoors_wins = 0; // how many times you win the car if you switch doors

var iterations = 100000; // # of times we'll play the game. The more you play the more accurate the result

var door = []; // the doors
var doorOpenedByMonte = 0; // the door opened by Monte Hall at the end
var yourChoiceOfDoor = 0; // your choice of door

var iters = 0; // keep count of the number of times we've played the game
for ( iters=0; iters < iterations; iters++) {
// Randomly assign a car (value 1) and two goats (values 1 and 2) to three doors
door[1] = Math.floor(Math.random()*3) + 1;

// $door2 can’t be the same value as $door1
do { door[2] = Math.floor(Math.random()*3) + 1;}while (door[2] == door[1]);
// $door3 can’t be the same value as door1 and door2
do {door[3] = Math.floor(Math.random()*3) + 1;} while ((door[3] == door[1]) || (door[3] == door[2]));

// Your random choice of door
yourChoiceOfDoor = Math.floor(Math.random()*3) + 1;

// Monte Hall randomly opens one of the other doors that don’t have a car
do { doorOpenedByMonte = Math.floor(Math.random()*3) + 1;} while (door[doorOpenedByMonte] == car);

// if you don’t switch to the other door
if (door[yourChoiceOfDoor] == car) {youDidntSwitchDoors_wins++;}

// if you switch to the other door
if ((door[yourChoiceOfDoor] != car)) {youSwitchedDoors_wins++;}
}

document.write("If you don’t switch you win " + youDidntSwitchDoors_wins/iterations + "% of the time.<br/>")
document.write("If you switch you win " + youSwitchedDoors_wins/iterations + "% of the time.");
}
</script>
</head>

<body onload="start();">
</body>
</html>

How to Use a Monte Carlo Simulation to Calculate PI in PHP (tutorial and code)

I'm currently reading Fooled by Randomness by Nassim Nicholas Taleb. The book is about the role randomness plays in the markets and in life. It says that what we often consider to be talent is just luck. But, what caught my eye in the book is the idea of Monte Carlo simulations.

The Monte Carlo method is a way of using random samples to compute a result. This blog post by Ian Barber explains it and includes two examples written in PHP. One is for determining the number of good SEO companies and bad SEO companies and how many of the bad SEO companies could have good results just by chance. The other example is a projection of time estimate for a project.

This wikipedia article talks about the Monte Carlo method and how to use the Monte Carlo method to compute the value of PI. Before calculating the value of PI using the Monte Carlo method we need to know that:

  • The area of a circle = PI * (radius * radius)
  • The area of a square = (length of one of its sides * lenght of one of its sides).

If the circle is inscribed inside a square that means the length of one of the sides of the square = 2 * radius of the circle. This means we can write the area of the square as (2 * radius) * (2 * radius) = 4 * (radius * radius). So, if we divide the area of the circle by the area of the square we get PI / 4. So, if we multiply the area of a circle by 4 and divide the result by the area of the square that inscribes that circle we get the value of PI.

The Monte Carlo method to calculate PI consists of generating random numbers and counting how many fall in the square and how many fall in the circle, then multiply by 4 the number that fall in the circle and divide that by the number that fall in the square. To make it easier to understand, here is PHP code that generates the value of PI using the Monte Carlo method:

<?php
// How to compute the value of PI using the Monte Carlo method by My Tiny Lab LLC (http://MyTinyLab.com). 2010/10/20
// Let's take a square of 1 unit by 1 unit with an inscribed circle. lcg_value() returns a random number between 0 and 1.
// We just use the top right quadrant of the square, so we only deal with positive numbers.
// To increase the accuracy, increase the number of iterations.

$iterations = 1000000; // # of iterations to estimate PI
$radius = 1.00; // radius of the circle
$radiusSquare = $radius * $radius; // so, we don't have to calculate radius^2 over and over later

$count=0;
for ( $iters=0; $iters < $iterations; $iters++) {
$x = lcg_value(); // x-coordinate (random # from 0 to radius)
$y = lcg_value(); // y-coordinate (random # from 0 to radius)

// we use the pythagoras' theorem to determine how many points are in inside the circle
// It's hard to explain in words. Draw a square. Inscribe a circle inside the square.
// Considering only the top right quadrant, you will see that any square trinagle you draw that has a
// hypothenuse that starts from (0,0) and ends at the edge of the circle has a length equal to the
// radius of the circle. Thus, using that idea and pythagoras' theorm we have that
// for a circle inscribed in a square, hypothenuse^2 = radius ^2 = x-coordinate^2 + y-coordinate^2.
$areCoordinatesInsideSquareOfTheRadius = ($x*$x)+($y*$y);
if ($areCoordinatesInsideSquareOfTheRadius <= $radiusSquare) {
$inTheCircle++; // count the number of points that are in the circle
}
}
// all points are inside the square, so we just use $iterations for the number of points in the square
$pi= ($inTheCircle * 4) / $iterations;

echo ("# in the square = ". $iterations); echo "<br/>";
echo("# in the circle = ". $inTheCircle); echo "<br/>";
echo ("estimate of PI is ". $pi); echo("<br/>");
?>

For 1000000 iterations, I got that PI is about 3.140064. I noticed in one of the runs that the value was 3.139... Now, how do I determine how many digits to trust using this method? A rule of thumb for how many digits to trust is to run the simulation many times and only trust the digits that don't change.

The Hidden Role of Chance in the Markets and in Life

Pages

Subscribe to RSS - Alfredo's blog