• Skip to primary navigation
  • Skip to main content
The Data Lab

The Data Lab

Pruple button with the word menu
  • Business Support
        • Business Support

          We’ll help you harness the power of data so you can innovate and grow your business.

          Visit our Business Support page

        • Accessing Talent
          • Data Talent
          • Placements
        • Funding
        • Small Business Support
        • Digital Strategy
        • Academic Project Funding
        • The Data Lab Community
  • Professional Development
        • Professional Development

          We’ll help you harness the power of data so you can innovate at work and also advance your career.

          Visit our Professional Development page

        • Workshops
        • Online Courses
        • Data Skills for Work Programme
        • The Data Lab Community
  • Students
        • Students

          We’ll help you learn about the power of data and gain real-world experience and career-focused qualifications.

          Visit our Students page

        • The Data Lab Academy
        • PhD
        • TDL Academy Placements
        • Scholarships
        • The Data Lab Community
  • Partner With Us
        • Partner With Us

          We work in partnership with companies to help them gain maximum benefit from the strategic use of data.

          Visit our Partner With Us page

        • Collaborate With Specialists
        • Partnerships
  • About Us
        • About Us

          We discover opportunities, connect people and ideas, develop knowledge and expertise and bring game-changing data projects to fruition.

          About Us

        • Our Team
        • Careers With Us
        • Academic Opportunities
        • The Data Lab Community
        • Case Studies
        • News & Podcasts
        • DataFest
        • Scottish AI Alliance
        • Contact us

Snakes and Ladders (Part 3 of 3): Analysing the classic children’s game

Tech blog 07/11/2017

To recap the analysis from our previous article, we have now shown that the advantage to Player 1 in snakes and ladders is minimal (amounting to less than 6 extra wins out of every 1,000 games). In this post we look at visualising some results, focusing in particular on the distribution of game lengths and the frequency with which the 100 squares are landed on. Note that for simplicity we count any score above 100 as landing on square number 100.

We make a couple of alterations from our existing code in order to achieve this. First we need a variable to act as a counter of “ply” (a term borrowed from chess and other games, meaning the number of individual player moves, or half-turns), and then another variable to keep track of the frequency of visits to each square.

We also import Python’s default plotting package Matplotlib in order to generate the distributions of these variables later on.

import numpy as np
from collections import Counter
import matplotlib.pyplot as plt


def snakes_and_ladders(x):
    dict_sal = {21:3, 24:7, 35:9, 50:11, 53:15, 60:23,
                75:44, 89:48, 93:25, 97:65, 99:58,
                4:16, 12:33, 18:22, 26:37, 42:61,
                49:51, 55:74, 82:98, 85:95, 88:92}
    return dict_sal.get(x, x)

def roll_die(x):
    x += np.random.randint(1, 7)
    x = snakes_and_ladders(x)
    return x

p1_wins = p2_wins = 0
ply_count = Counter()
squares_count = Counter()

np.random.seed(42)

NUM_GAMES = 1000000

for games in range(NUM_GAMES):
    p1 = p2 = 0
    ply = 0
    while True:
        p1 = roll_die(p1)
        ply += 1
        if p1 > 100:
            squares_count[100] += 1
            p1_wins += 1
            ply_count[ply] += 1
            break
        else:
           squares_count[p1] += 1
        p2 = roll_die(p2)
        ply += 1
        if p2 >= 100:
            squares_count[100] += 1
            p2_wins += 1
            ply_count[ply] += 1
            break
        else:
            squares_count[p2] += 1

top_of_ladder = [16, 22, 33, 37, 51, 61, 74, 92, 95, 98]
tail_of_snake = [3, 7, 9, 11, 15, 23, 25, 44, 48, 58, 65]

ladder_tops = {k: squares_count[k] for k in top_of_ladder}
snake_tails = {k: squares_count[k] for k in tail_of_snake}
unmarked = {k: squares_count[k] for k in range(1, 101) if k not in top_of_ladder + tail_of_snake}

plt.bar(ladder_tops.keys(), ladder_tops.values(), 0.8, color="green", label="ladder top")
plt.bar(snake_tails.keys(), snake_tails.values(), 0.8, color="red", label="snake tail")
plt.bar(unmarked.keys(), unmarked.values(), 0.8, color="blue", label="unmarked")
plt.xlim([0, 101])
plt.ylim([0, 2500000])
plt.xlabel("Square")
plt.ylabel("Frequency")
plt.title("Distribution of Squares Landed On")
plt.legend(loc="upper right")
plt.draw()

plt.figure()
plt.bar(ply_count.keys(), ply_count.values(), 0.5, color="blue")
plt.xlim([0, 601])
plt.ylim([0, 18000])
plt.xlabel("Total Ply")
plt.ylabel("Frequency")
plt.title("Distribution of Half-Turns")
plt.draw()

plt.show()

The above code is available here.

The one piece of code that perhaps needs some explanation is the Counter container from Python’s collection module, which we use to track the squares landed on and the total number of half-turns. This is a subclass of a dict object but has the benefit of being able to use the increment operator even if the element is not already present.

We have also separated the squares into “ladder_tops”, “snake_tails”, and “unmarked” to allow us to plot the frequency of these different classes with different colours. We can see the effect of this here:

It is unsurprisingly clear to see that the snake and ladder squares are hit more frequently than their local unmarked squares. Note too that some squares are never “visited”. These correspond to ladder bases and snake heads, since the counters will always move away from these squares.

With some analysis offline we can discern that the most frequently visited square on this particular board is 22, whilst the least visited is 94.

Looking next at the distribution of game lengths we see a neat pattern which peaks at 39 half-turns. The quickest game took only 17 ply, whilst the longest weighed in at 544! That’s 272 rolls of the die per player!

So this rounds up our brief look at Snakes and Ladders using Python. Just remember that not all research into games needs to be at the level of IBM’s Deep Blue in chess, or the recent successes of Demis Hassabis’s team on AlphaGo. For some games just a couple of dozen lines of code can yield insights and lead to discoveries that could help shape your strategy in future.

Speaking of which, next time Eva it’s my turn to go first!

Tags: python, Snakes & Ladders

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Innovate • Support • Grow • Respect

Get in touch

t: +44 (0) 131 651 4905

info@thedatalab.com

Follow us on social

  • Twitter
  • YouTube
  • Instagram
  • LinkedIn
  • TikTok

The Data Lab is part of the University of Edinburgh, a charitable body registered in Scotland with registration number SC005336.

  • Website Accessibility
  • Privacy Policy
  • Terms & Conditions

© 2023 The Data Lab

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsReject AllAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-advertisement1 yearSet by the GDPR Cookie Consent plugin, this cookie is used to record the user consent for the cookies in the "Advertisement" category .
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
CookieLawInfoConsent1 yearRecords the default button state of the corresponding category & the status of CCPA. It works only in coordination with the primary cookie.
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
CookieDurationDescription
_ga2 yearsThe _ga cookie, installed by Google Analytics, calculates visitor, session and campaign data and also keeps track of site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognize unique visitors.
_ga_DPXX4XJSJ82 yearsThis cookie is installed by Google Analytics.
_gat_gtag_UA_54851888_11 minuteSet by Google to distinguish users.
_gat_UA-54851888-11 minuteA variation of the _gat cookie set by Google Analytics and Google Tag Manager to allow website owners to track visitor behaviour and measure site performance. The pattern element in the name contains the unique identity number of the account or website it relates to.
_gcl_au3 monthsProvided by Google Tag Manager to experiment advertisement efficiency of websites using their services.
_gid1 dayInstalled by Google Analytics, _gid cookie stores information on how visitors use a website, while also creating an analytics report of the website's performance. Some of the data that are collected include the number of visitors, their source, and the pages they visit anonymously.
CONSENT2 yearsYouTube sets this cookie via embedded youtube-videos and registers anonymous statistical data.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
CookieDurationDescription
personalization_id2 yearsTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.
VISITOR_INFO1_LIVE5 months 27 daysA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.
YSCsessionYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.
yt-remote-connected-devicesneverYouTube sets this cookie to store the video preferences of the user using embedded YouTube video.
yt-remote-device-idneverYouTube sets this cookie to store the video preferences of the user using embedded YouTube video.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
CookieDurationDescription
cl-bypass-cache1 hourNo description
muc_ads2 yearsNo description
SAVE & ACCEPT
Powered by CookieYes Logo