Monte Carlo Analysis of Chutes & Ladders with Python

If you spend time around young children, sooner or later you’ll end up playing the game Chutes and Ladders. This game actually has quite an interesting history, dating back to ancient India. The Milton-Bradley version dates from the 1940s.

The game’s history is probably the most interesting thing about the game, beause it is utterly devoid of strategy or technique. The players’ only interaction with the game is to spin a spinner that provides a random number from 1 through 6; there is no skill aspect, there are no decisions to be made. And certainly, while perfectly enjoyable as a family pastime that brings people together, in and of itself the game offers little intellectual distraction.

This intellectual idle-time led me to think about the nature of the board. I wondered if the game, being entirely stochastic, had any hidden patterns within. After all, it’s reasonable to assume that Milton-Bradley didn’t have access to any sort of automated analysis of their game back in 1943. I wondered things like:

  • What’s the average number of spins to win?
  • How many chutes and ladders will a user typically hit?
  • Are the chutes and ladders balanced?
  • Are some squares hit more often than others?

What’s neat is the nature of the game lends itself well to numerical analysis. There’s no human component that requires estimation or approximation. Literally the only action a player takes is to spin a spinner. Why not use Monte Carlo analysis to play bulk trials of the game and look for answers?

Coding this in Python was fairly straightforward. Although not the most performant language, Python’s excellent visualization tools make it the language of choice for this project. Using joblib to parallelize the task meant that I could simulate 500,000 single-player games in 7 seconds. (Why single-player? The game doesn’t change at all by the number of players. There are no exclusions or conflicts or indeed any alterations at all, from a numerical analysis perspective.)

The results are kind of interesting if you’re the sort of person who wonders about these sorts of things.

For half a million games, I saw this:

7.633320899999944 seconds elapsed time
Minimum number of spins to win: 7
Maximum number of spins to win: 446
Arithmetic mean number of ladders hit by player: 3
Arithmetic mean number of chutes hit by player: 4
Arithmetic mean of spins to win: 40.092362
Median of spins to win: 33.0
Standard deviation = 25.522641855046196

There’s more information to be found in the visualizations:

Noting the average number of spins to win the game is 40, the cumulative number of spins to win a game rises in a smooth curve. You can see, for example, that the probability of concluding a game between 50 and 60 spins is about 81-82%, and that most games are won under 40 spins (the median number-of-spins-to-win being 33).

The heatmaps of board positions are particularly interesting to me. There are two heatmaps of note:

  1. a heatmap of where the user lands initially after spinning (i.e. before following any chute/ladder)
  2. a heatmap of where the user ends up at the conclusion of their turn (i.e. after following any chute/ladder)

The former shows two notable darker/cooler bands across the board: along the bottom, and in the upper third. These cooler bands are areas of infrequent landing. Once chutes/ladders are taken into account, however, the picture becomes much noisier. The squares with ‘0’ values may seem counter-intuitive until you realize those are the heads of chutes or bottoms of ladders — no turn ever ‘ends’ on these squares. This heatmap shows some particular hotspots such as the top of the “big ladder” and the bottom of Square 48’s yellow chute. Also note how it’s very, very common to get stuck at square 99, waiting for an exact spin of ‘1’ to finally win the game.

If you care to try this out locally, the source code is on Github.

On the ground at CppCon 2014

I’ve just returned from the week-long CppCon 2014 in Bellevue, Washington. Here’s what I experienced.

I’ve absorbed a great deal from a variety of C++ developer conferences – CppNow, Going Native, C++ And Beyond – but always virtually, via video and webcast. This was an opportunity to jump into the thick of things and participate in person. With community heavyweights like Herb Sutter and Scott Meyers in attendance I knew the content would be stimulating and informative. (Honestly, the speaker list featured nearly every name in the “C++ royalty” that you could imagine. I smiled to myself seeing Bjarne Stroustrup standing in the registration line like he was just another attendee.) So when the conference’s early-bird admission opened in March, I eagerly sent in my hard-earned dollars and blocked off the week of September eighth on my calendar.

Continue reading

Unit test your private methods for great justice

The continuing dissent and confusion about unit testing of private class methods surprises me.

The access specifier is much like your choice of software license: it exists to limit consumers’ actions, not to limit yours. A method’s access specifier is completely irrelevant to testing, and only describes what you want the consumer to use; any code that takes inputs and produces outputs, private or not, should be tested.

The opponents of private-method testing tend to argue in quasi-religious terms: that private methods are mere hidden implementation details; that users of the class will only care about the public API; that testing of private methods breaks encapsulation. A typical unhelpful “solution”: private methods should be put into a different class and made public there.

To argue against granular testing of private methods is to mean well while being thoroughly unhelpful. The purpose of testing is more than just to guarantee the viability of your public interface – it is also to examine the inner machinery and support routines of your class to ensure that they themselves function correctly for a spectrum of inputs and edge cases. The private implementation will contain non-trivial complexities that are more readily and precisely tested directly than via the public API.
Continue reading

Beautiful logging for Ruby on Rails 4

In a previous post I showed you a simple way to get beautiful, easy-to-read logs in your Rails 3.2 application. Rails 4 changed the game again; for Rails 3.2 or earlier, refer to my earlier post; but for Rails 4 read on…

It’s really easy. Just make a new file in your ‘config/initializers’ directory called something like ‘log_formatting.rb’ and paste into it the following code. Restart your app, and voila: pretty logs again!

UPDATED. Konrad’s comment below was correct. I’ve altered this code to work with both the regular logger and the new tagged logger. Now you can configure your logger as

config.logger = ActiveSupport::Logger.new('your_app.log')

or

config.logger = ActiveSupport::TaggedLogging.new(Logger.new('your_app.log'))

… both will work. Here’s the updated monkey patch:

class ActiveSupport::Logger::SimpleFormatter
  SEVERITY_TO_TAG_MAP     = {'DEBUG'=>'meh', 'INFO'=>'fyi', 'WARN'=>'hmm', 'ERROR'=>'wtf', 'FATAL'=>'omg', 'UNKNOWN'=>'???'}
  SEVERITY_TO_COLOR_MAP   = {'DEBUG'=>'0;37', 'INFO'=>'32', 'WARN'=>'33', 'ERROR'=>'31', 'FATAL'=>'31', 'UNKNOWN'=>'37'}
  USE_HUMOROUS_SEVERITIES = true

  def call(severity, time, progname, msg)
    if USE_HUMOROUS_SEVERITIES
      formatted_severity = sprintf("%-3s",SEVERITY_TO_TAG_MAP[severity])
    else
      formatted_severity = sprintf("%-5s",severity)
    end

    formatted_time = time.strftime("%Y-%m-%d %H:%M:%S.") << time.usec.to_s[0..2].rjust(3)
    color = SEVERITY_TO_COLOR_MAP[severity]

    "\033[0;37m#{formatted_time}\033[0m [\033[#{color}m#{formatted_severity}\033[0m] #{msg.strip} (pid:#{$$})\n"
  end
end

Steering Behaviors for Ruby game dev now on Github, Rubygems

I just released my Steering Behaviors package to Github, and an accompanying Gem to Rubygems.

If you’re building a game, you’ll want your game agents and characters to exhibit realistic motion. A standard way of doing this is with ‘steering behaviors’.

The seminal paper by Craig Reynolds established a core set of steering behaviors that could be utilized for a variety of common movement tasks. These include such behaviors as predictive pursuit, fleeing, arrival, and wandering. This Ruby library can accomplish many/most of those tasks for your Ruby / JRuby game.

The basic behaviors can be layered for more complicated and advanced behaviors, such as flocking and crowd movement.

Embellishments and expansions are planned, but this is working software you can use to drive your own game’s characters. (I’m using it in my own game programming.) The Github repo includes working graphical examples, and you can install the Gem for easier and more direct use in your own game.

Pull requests are enthusiastically encouraged.

 

On Github: my Fuzzy Associative Memory (FAM) package

I’ve just released to Github my working fuzzy logic module, Fuzzy Associative Memory.

A Fuzzy Associative Memory (FAM for short) is a Fuzzy Logic tool for decision making. It uses Fuzzy Sets to establish a set of rules that are linguistic in nature; examples might include:

  • “If the room is a bit warm, turn the fan up a little bit”
  • “If the orc’s hit points are a little low, retreat from the enemy”
  • “If the ship is off course by a little bit, correct just a little to the right”
  • “If the bird is much slower than the flock, speed it up a lot”

As you can see, the rules are deliberately vague and use qualifiers like “a little” and “a lot”. This is the nature of fuzzy sets; they capture such human fuzziness in a way that extracts highly natural behavior from the fuzzy rules.

It has a wide range of applications:

  • Industrial control, such as governing a fan to keep a room at the “just right” temperature
  • Game AI, such as giving human-like behavior capabilities to NPCs
  • Prediction systems

Status

This is working, functional software. It currently supports:

  • Triangular fuzzy sets for input/output
  • Larsen Implication (scaling)
  • Atomic antecedent propositions (if A then Z)

To do:

  • Trapezoidal (and other shapes) for fuzzy sets
  • Hedges (‘very’ and ‘fairly’)
  • Mamdani Implication (clipping)
  • Composite antecedent propositions (if A or B, then Z)
  • Additional examples

Examples

The bin directory contains the following examples:

  • hvac_system_example illustrates how a FAM could govern an HVAC fan unit to maintain a constant, comfortable temperature

Get it here!

Entity-Component game programming using JRuby and libGDX – part 8

Introduction

Our Lunar Lander game is somewhat playable by this point but it still lacks some key features. After all, it would be nice if we could detect collisions and determine if the lander has safely landed on the pad. Let’s see how our flexible Entity-Component system permits us to expand our game with minimal fuss.

Collision Detection

First, a frank disclaimer: the following collision detection algorithm is entirely inefficient. It’s kept simple for our basic teaching purposes here but is probably undesirable in a game of any scale. But that’s OK: E-C will permit you to swap in a much more advanced collision detection system when you’re ready. 🙂

Read the rest of this story…

Entity-Component game programming using JRuby and libGDX – part 7

Introduction

Entity-Component systems, we’ve learned, are easy to implement and maintain; the elegance is basically “baked in” due to the way components and entities are married in the Entity Manager.

One particularly tidy aspect of an entity-component system is how well it lends itself to data persistence, or in practical terms: saving game state. Let’s take a look.

Where Is State?

In a conventional object oriented design, state is scattered all over the place, embedded in your far-flung object instances. But in E-C everything is neatly gathered together under one roof: the Entity Manager. This manager knows every entity “instance” along with every entity’s components, which are where the entity state data are stored.

Therefore, persist the entity manager to disk and you’ve saved the game in its entirety. Load from disk to memory and you’ve just loaded the game. It really is that easy.

Read the rest of this story…

Entity-Component game programming using JRuby and libGDX – part 6

Introduction

Now that we have laid the entity-component foundation and introduced some necessary libGDX concepts, we can finally get around to putting together a little game. Let’s make a “Lunar Lander” type game to illustrate all the concepts we’ve learned so far.

Remember that the source code for this Entity-Component Framework and the game we’re writing is all available at Github. The Github version is, of course, the “final version” that includes features I might not have addressed so far in the blog series, but if you’re eager to jump ahead…

Entities and Components

For this exercise let’s begin by defining our entities and some of their relevant components.

What are we going to need for this game?

  • The lunar lander module
  • A platform for it to try to land on
  • Ground to collide with

That seems like a fair assessment of our initial entity needs. Now, moving on to components. What are some of the aspects / behaviors / features that we should provide to our entities?

Read the rest of this story…

Entity-Component game programming using JRuby and libGDX – part 5

Introduction

In previous installments we learned about Entity-Component theory, and we are almost ready to employ this in a real game. Before we do, however, we need to cover some basic game engine concepts.

The Java world is a fertile place for gaming, and there are numerous game engines available. JOGL and LWJGL are low-level frameworks that ease and abstract certain game-construction duties, whereas high-level frameworks like libGDX and Slick2D provide you with all the tools you need to easily author your game — often for multiple platforms at the same time. Both of those are fine choices, but for this series we’ll leverage libGDX. It has as robust community, excellent documentation, and can be used to target the Windows, Android, Mac and Linux platforms.

This post will not attempt to be a tutorial for installing libGDX nor a configuration guide for its many powerful features. Rather, we’ll walk through basic libGDX usage to get a high-level overview of how it works — often a helpful starting point for a newcomer to the technology. The canonical source for libGDX is its official wiki, with supplemental information found at the libGDX-users wiki.

Note that here we are now embracing one of the key features of JRuby: leveraging Java libraries. libGDX is, after all, a Java framework. But why write your game code in ugly, verbose, old-fashioned Java when you can use your favorite language to do it? The code will certainly be tidier, more readable, and a lot more enjoyable to write and maintain.

Now is an appropriate time to point you to the official Github repository for this blog series’ source code. This repository not only includes all the source code that has been (and will be) discussed in this blog series, but also includes a simplistic but runnable “lunar lander” type game to help cement the concepts with real, working code. I believe you’ll find it very helpful as a learning tool.
Read the rest of this story…