ROFLBALT

Share this article

Today, we’re going to dissect a project that a couple of Rubyists we are fond of wrote for RailsCamp last month. Paul Annesley (twitter) and Dennis Hotson (twitter) joined forces at RailsCamp Australia and the result was ASCII-based fireworks.

First, though, if you are unfamiliar with RailsCamps, here is a blurb from their site:

Imagine yourself and a posse of like-minded ruby hackers on a country retreat with zero internet for a weekend of fun. You’ll laugh, hack, learn, cry (well, you probably won’t cry… but you know… it felt poetic) and most likely play a crap-load of Guitar Hero.

The point of a RailsCamp, from what I can tell, is to disconnect with everything except Ruby and the other attendees. It is a programming fest where they encourage hackery and creativity, two things that live in abundance in the Ruby community. Everyone that I know who has attended a RailsCamp has come back saying it was a gamechanger for their career. I need to get one scheduled near Charlotte.

The Project

The project that Dennis and Paul settled on was entitled ROFLBALT. It is a Ruby port of the somewhat famous Canabalt game that you can play online or download to your mobile device. The goal of Canabalt (and all -balt type games) is to run and jump from building to building, going for as long as you can. Your score is directly proportional to how long you go before you die. It’s just a bit of brain candy in simple gaming form, the kind of candy my brain likes best.

Paul and Dennis aimed to complete ROFLBALT using less than 500 lines of Ruby, and they pulled it off. Let’s see how.

How They Did It

I am going to attempt to breakdown the code for ROFLBALT. I am warning you now that Paul and Dennis are, seemingly and unsurprisingly, much smarter than I am. In some parts of this code, I had no idea how they 1) came up with what they did or 2) what the heck the code does. This is, in no way, a reflection on the code or project, but more on the author, who is, um, “special.”

You can find the code for the project on github.

ROFLBALT is broken into the following classes.

  • Game
  • Screen
  • Pixel
  • BAckground
  • WindowColor
  • FrameBuffer
  • World
  • BuildingGenerator
  • (module)Renderable
  • Building
  • Player
  • Blood
  • Scoreboard
  • GameOverBanner
  • RoflCoptor

The executable (in the bin dir) simple runs Game.new.run, so we’ll start there.

Game

[gist id=”1726822″]
Game, as you may have guessed, puts all the bits in place to start the game, as well as handles exiting of the game. It depends on a World and a Screen. In the Game methods, things are pretty high-level, as we’re dealing with a World object and Screen object, both abstractions created by this project. The game starts the fun, basically, in the render method. It draws the buildings, the player, and the rest of the world objects. Note that “drawing” an object means passing it to the screen’s draw method, something we’ll cover when we get to Screen. Other than that, the Game listens for a signal interrupt (Ctrl-C in this case) and kills the game when that happens.

World

[gist id=”1726854″]
World holds all of the renderable items that the game can contain. The Buildings, the background, scoreboard, and a player. it also has a couple of non-visible items, like a Building Generator and a horizon (screen width). The world has a lot of dependencies:

  • BuildingGenerator
  • Background
  • Player
  • Building
  • Scoreboard

The world also controls the speed of the game and the distance travelled, which is how scoring is calculated. The tick method is each “move” of the world. As the player moves right (or, more appropriately, the buildings move left) the tick method checks to make sure that a building is still under the player, otherwise it’s time to RENDER BLOOD and call PLAYER.DIE (Sorry, just feels like I should capitalize those) If you aren’t dead, it adds one to ticks

Screen

[gist id=”1726860″]
Screen is initialized with the width and height of our game “canvas”, along with the game world. If you look at the initialize method, it does some funky stty magic to clear the screen and disable the cursor. It’s things like this that make me love reading other people’s code. I always see and learn things that I would miss in my everyday coding routine. The Screen is responsible for rendering the initial game “canvas” and drawing Renderables onto the canvas. Renderable are classes that include the Renderable module, which we will get to soon.

Pixel

[gist id=”1726864″]
The Pixel class represents a game pixel, which is an ASCII character in ROLFBALT. A Pixel instance consists of a foreground color, a background color, and a character. The cool thing I learned from the Pixel class is how to mess with my terminal colors. The to_s method shows this, using a fancy string interpolation method (http://apidock.com/ruby/String/%25). I was switching my terminal from black-on-white to white-on-black and giggling when my wife walked by and asked what I was giggling about. All I could say was “um, nerd stuff” and realize that it’s situations like this that separate us from the “normals.” Anyway, I digress… back to the code…

Background

[gist id=”1726875″]
Background takes a world as a dependency and is mainly responsible for returning the color behind everything else. For example, when the player is rendered, it passes backround.color() as the background color to the players Pixels. Nice little, focused class. I like it.

WindowColor

[gist id=”1726881″]
The color of the windows on the buildings. BuildingGenerator uses it. That is all

Framebuffer

[gist id=”1726883″]
Framebuffer is instantiated by the Screen class and takes a background. The initialize method reminded me of the cool way to pass a block to the Hash intializer to get a hash that has a default value for any member that is accessed. Rendered pixels are fed into the framebuffer, and then other things (like the screen) can grab them later. It also uses Background, passing back background pixels as a default when the Framebuffer does not have a pixel for a requested x,y.

BuildingGenerator

[gist id=”1726891″]
BuildingGenerator takes a World and a Background and, as you may have guessed, it creates the buildings. The methods here focus on destroying building objects (by taking them out of the world.buildings property) and creating builidings as the world turns moves. The generate_if_necessary method is a loop that keeps creating builidings while the last building’s x coord is less than the worlds Horizon (which is the width of the screen, if you remember.) It calls the build method which builds the building. The next_y function takes the previous building into account and makes sure the new building isn’t too high for our player to jump. This is the kind of domain problem you have to solve when creating a video game. :)

Renderable

[gist id=”1726900″]
This brings us to the Renderable module, which is included in:

  • Building
  • Player
  • Blood (hee)
  • Scoreboard
  • GameOverBanner
  • RoflCopter

It defines two methods: each_pixel and right_x. Also, it expects the included class to define a pixel method, along with x, y, height, and width properties (or methods.) In a nutshell, the each_pixel method loops over every pixel for the object, and returns the x, y of that pixel, along with the character that represents that pixel for the given Renderable. In a way, it works just like your TV, scanning through the images and rendering them, pixel by pixel. I like how Renderable delegates the pixel method, making a clear contract with things that include Renderable as well as things that use Renderables.

Building

[gist id=”1726907″]
Looking at our first Renderable, Building, it takes an x,y, which is the left most x and the highest y, a width, and a background object. Moving it left is as simple as decrementing its x property. The complexity happens in the pixel method expected by Renderable. The goal is to figure out, for the given x/y, what character and color to render. Looking at the start of the if statement, if the distance between the y of the current pixel and the y of the building is zero, then we are at the top of the building, so draw a “=”. The rest of the logic is the same, figuring out which character and color to return. Pretty smart.

Player

[gist id=”1726918″]
Player is another renderable, but it handles what character to draw differently than building. Looking at the code, it uses the delta in between the current x,y and the player x,y to figure out which character to return based on one of three states: dead, walking, or other (jumping). Each state is made up of a two-dimensional array that holds the actual characters, which you can literally see. The code here is very clever in its structure, forming the player in the state, then using the rx/ry indices to grab the character. Pretty ingenious.

Blood

[gist id=”1726952″]
The Blood class always uses the same character and color, but I had to give it its own section. I just LOVE that there is a Blood class.

Scoreboard and GameOverBanner

[gist id=”1726974″]
Both of these renderables use a template method to find the character to render. Again, the structure of the code is awesome, as it reads like it looks in the game. This makes it easy to figure out what the code is doing. If only you could make all code this visually obvious.

RoflCoptor

[gist id=”1727010″]
The coup de grace, our ROFLCopter. The approach here is, again, similar to the other template-based renderables, but here we have multiple templates or frames. The x and y of the coptor change based on current time, using a formula I don’t really understand. I think my favorite bit is the rescue, where it claims that “RoflCopter” crashes from time to time.

Time to Play

Well, Paul and Dennis pulled it off. A port of Canabalt to Ruby that is highly playable, as well as being comprised of interesting code. When I asked the gents for any anecdotes about it, they came back with “Ask the readers to make it work in Ruby 1.8 as a challenge.” So, anyone up for the that? In the meantime, I am going to try and beat my record in ROFLBALT.

Glenn GoodrichGlenn Goodrich
View Author

Glenn works for Skookum Digital Works by day and manages the SitePoint Ruby channel at night. He likes to pretend he has a secret identity, but can't come up with a good superhero name. He's settling for "Roob", for now.

Share this article
Read Next
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Getting Started with Content Collections in Astro
Getting Started with Content Collections in Astro
Tamas Piros
What Does the Java Virtual Machine Do All Day?
What Does the Java Virtual Machine Do All Day?
Peter Kessler
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Mayank Singh
Layouts in Astro
Layouts in Astro
Tamas Piros
.NET 8: Blazor Render Modes Explained
.NET 8: Blazor Render Modes Explained
Peter De Tender
Mastering Node CSV
Mastering Node CSV
Dianne Pena
A Beginner’s Guide to SvelteKit
A Beginner’s Guide to SvelteKit
Erik KückelheimSimon Holthausen
Brighten Up Your Astro Site with KwesForms and Rive
Brighten Up Your Astro Site with KwesForms and Rive
Paul Scanlon
Which Programming Language Should I Learn First in 2024?
Which Programming Language Should I Learn First in 2024?
Joel Falconer
Managing PHP Versions with Laravel Herd
Managing PHP Versions with Laravel Herd
Dianne Pena
Accelerating the Cloud: The Final Steps
Accelerating the Cloud: The Final Steps
Dave Neary
An Alphebetized List of MIME Types
An Alphebetized List of MIME Types
Dianne Pena
The Best PHP Frameworks for 2024
The Best PHP Frameworks for 2024
Claudio Ribeiro
11 Best WordPress Themes for Developers & Designers in 2024
11 Best WordPress Themes for Developers & Designers in 2024
SitePoint Sponsors
Top 10 Best WordPress AI Plugins of 2024
Top 10 Best WordPress AI Plugins of 2024
Dianne Pena
20+ Tools for Node.js Development in 2024
20+ Tools for Node.js Development in 2024
Dianne Pena
The Best Figma Plugins to Enhance Your Design Workflow in 2024
The Best Figma Plugins to Enhance Your Design Workflow in 2024
Dianne Pena
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Christopher Collins
Build Your Own AI Tools in Python Using the OpenAI API
Build Your Own AI Tools in Python Using the OpenAI API
Zain Zaidi
The Best React Chart Libraries for Data Visualization in 2024
The Best React Chart Libraries for Data Visualization in 2024
Dianne Pena
7 Free AI Logo Generators to Get Started
7 Free AI Logo Generators to Get Started
Zain Zaidi
Turn Your Vue App into an Offline-ready Progressive Web App
Turn Your Vue App into an Offline-ready Progressive Web App
Imran Alam
Clean Architecture: Theming with Tailwind and CSS Variables
Clean Architecture: Theming with Tailwind and CSS Variables
Emmanuel Onyeyaforo
How to Analyze Large Text Datasets with LangChain and Python
How to Analyze Large Text Datasets with LangChain and Python
Matt Nikonorov
6 Techniques for Conditional Rendering in React, with Examples
6 Techniques for Conditional Rendering in React, with Examples
Yemi Ojedapo
Introducing STRICH: Barcode Scanning for Web Apps
Introducing STRICH: Barcode Scanning for Web Apps
Alex Suzuki
Using Nodemon and Watch in Node.js for Live Restarts
Using Nodemon and Watch in Node.js for Live Restarts
Craig Buckler
Task Automation and Debugging with AI-Powered Tools
Task Automation and Debugging with AI-Powered Tools
Timi Omoyeni
Quick Tip: Understanding React Tooltip
Quick Tip: Understanding React Tooltip
Dianne Pena
12 Outstanding AI Tools that Enhance Efficiency & Productivity
12 Outstanding AI Tools that Enhance Efficiency & Productivity
Ilija Sekulov
React Performance Optimization
React Performance Optimization
Blessing Ene Anyebe
Introducing Chatbots and Large Language Models (LLMs)
Introducing Chatbots and Large Language Models (LLMs)
Timi Omoyeni
Migrate to Ampere on OCI with Heterogeneous Kubernetes Clusters
Migrate to Ampere on OCI with Heterogeneous Kubernetes Clusters
Ampere Computing
Scale Your React App with Storybook and Chromatic
Scale Your React App with Storybook and Chromatic
Daine Mawer
10 Tips for Implementing Webflow On-page SEO
10 Tips for Implementing Webflow On-page SEO
Milan Vracar
Get the freshest news and resources for developers, designers and digital creators in your inbox each week