Creating your own custom Handlebars bounded if’s in Ember

Ember.js, JavaScript, Programming

Ember uses the Handlebars templating library to create views.
Ember ‘registers’ a whole bunch of Handlebars helpers to make creating templates easier, for instance the {{link}} helper to create links to different routes.

In the same way Ember registers / adds new helpers to Handlebars you can do the same, you could for instance create a helper that capitalizes a word:

The ‘registerBoundHelper’ creates a helper that reevaluates whenever the argument changes. So if the ‘name’ changes the helper is rerendered with the new name.

However in older versions of Ember it was not possible to add bounded block helpers to Handlebars.

A block helper is defined as:

“Block helpers make it possible to define custom iterators and other helpers that can invoke the passed block with a new context.”

Examples of block helpers are {{if}}, {{with}} and {{each}}. Bounded versions of these helpers mean that they get reevaluated / rendered when the condition changes.

So creating your own version of an if statement that updated when the condition changed was very difficult. Here’s a usecase and the story of why I needed to create my own custom bounded {{if}}, and how I eventually did it:

In an App that I made we had the following case: We wanted to display a rain meter, it shows the user how many millimeters precipitation fell on a day.
The rain meter works via radio waves, which can get scrambled, missed or otherwise interfered. If this is the case our server sends the value ‘null’
to the Ember application. If the server tells me the “mm” key is ‘null’ I want to display “No data” if it was anything other than “null” I want
to display that number. This was my first attempt:

On first glance this worked well, unless it was a clear day when rainmeter.mm was actually the value ‘0’ as in zero, then it would display no data. This is because {{if}} is only true when the value is not an empty array, zero, null, undefined or “”. I had to create my own {{if}} that handles
accepting the value 0 as truthy. My if should work as follows, everything is true except null and undefined:

This approach worked for the longest time, until I got reports that “No data” was visible whilst the rainfall.mm was not ‘null’. This puzzled me for the
longest time, until I realized that the condition only gets evaluated once. Meaning that if rainmeter.mm was ‘null’ once and then changed to 12.3 it would not recheck the {{if}}’s condition. Changing from 12.4 to 13.0 would still work because the condition would be true in both cases. I needed a way to write my custom {{if}} so that got reevaluated each time the condition might change.

For the longest time I could not find any way to fix this, but then ‘registerBoundHelper’ got released. It created a way to make bound helpers in Ember, still no bounded {{if}}’s but it was a nice place to start digging. It looks like this:

The last line looked very promising it calles this function called bind which creates a binding which reevaluates when the condition changes. Now all I need to do is change the function that determines the condition’s value. It is called ‘func’ so I changed it to:

Now it worked like a charm. The only thing was that the ‘bind’ function used to be private so I had to alter Ember itself so I could reach it. But in the new version of Ember ‘bind’ is visible through Ember.Handlebars.bind.

So that’s my story about creating custom Ember bounded {{if}}’s

I do however like to point out that my case ‘ifData’ was used many times throughout the app. I do not recommend creating custom bounded {{if}}’s when only needing it once or twice, in that case I would use computed properties instead, which is way more emberesque.

Here’s a Ember JS bin so you can play with it yourself, and where you can see al versions of the {{if}} side by side:

http://emberjs.jsbin.com/ebobilUS/10/edit

e-4917 emulator in Clojure

Clojure, Programming

Introduction

Years ago I was introduced to Richard Buckland’s excellent ‘Higher Computing Series” on Youtube. It featured a little microprocessor called the e-4917.

It taught me how to program computers on the lowest level, and how memory can be both instructions and data.

The e-4917 has 2 registers called R0 and R1 for storage, a register for the current instruction called IS and a pointer to the next instruction in memory called IP. But most importantly it has a whopping 16 memory locations to store numbers in.

Instructions

These are the one bit instructions:

0 = exit
1 = add (R0 = R0 + R1)
2 = subtract (R0 = R0 – R1)
3 = increment R0 (R0 = R0 + 1)
4 = increment R1 (R1 = R1 + 1)
5 = decrement R0 (R0 = R0 – 1)
6 = decrement R1 (R1 = R1 – 1)
7 = ring a bell

These are the two bit instructions. Each instruction takes an argument which is a location in memory. Except for print which uses the next location in memory! When a two bit instruction is ‘found’ it will skip 2 memory locations instead of 1, since the next location is the argument for the instruction.

8   = print the value of the next location in memory
9   = load value from argument location into R0
10 = load value from argument location into R1
11 = write value of R0 in argument location
12 = write value of R1 in argument location
13 = jump to argument location, and continue instructions from there
14 = jump to argument location but only if R0 == 0
15 = jump to argument location but only if R0 != 0

Example programs

A simple program looks like this:

[8, 7, 0]

It prints 7 and then exists. Why? because the program first encounters the instruction called 8, 8 means print the value of the next location in memory which is 7.

Here’s a program that makes a buzzing sound three times:

[7, 7, 7]

This is a complex program that subtracts 6 and 4:

[9, 15, 10, 14, 2, 11, 8, 8,
0, 0, 0, 0, 0, 0, 4, 6]

First it encounters the 2 byte instruction 9, which means load value from the argument location into R0. So it looks at its argument which is 15, so it grabs the value stored in memory location 15 which is 6 and stores it into R0. Since it is a 2 byte instruction it will skip location 1 and move to location 3. There it will find instruction 10 which will store 4 into location R1.

Then it will finally do the subtraction since it encounters the 1 byte instruction 2. Now R0 = 6 – 4 = 2. Now we need to print the result otherwise the program will be useless.

In order to print something we need to use instruction 8. Which prints the value of the next memory location. So in order to print R0 we need to write it to memory next an 8 instruction. Here’s the trick:

We write R0 to memory location 8 with instruction 11. We write to memory location 8 because it is the location after memory location 7 which contains the instruction 8.

To visualize this, this is the memory before instruction 11:

[9, 15, 10, 14, 2, 11, 8, 8,
0, 0, 0, 0, 0, 0, 4, 6]

This is the memory after:

[9, 15, 10, 14, 2, 11, 8, 8,
2, 0, 0, 0, 0, 0, 4, 6]

So when the next instruction 8 is called it will look at memory location 8 and it will see the 2 and it will print it.

This example shows how  instructions and data are both numbers, and that data = code. I especially like that there are two 8 next to each other each meaning a different thing.

Clojure

Data = code is very Clojureish so I thought it would be appropriate to create an emulator in Clojure.

Lets start with the definition of the computer’s state:

The first argument the “State” record is called: memory. It represents all the memory locations and their values. Since data = code the memory is also the program. The other arguments represent the registers of the processor.

We can now define a program which starts at instruction 0 with:

Having a State is not enough we need to be able to run the instructions on it. Lets define the “add” instruction which is represented by the number 1. Remember it adds R0 and R1 and stores the result in R0.

The code is very simple it takes a State which it deconstructs into memory, r0, r1, ip and is. So we can manipulate it easier. It will then return a new state where r0 = (+ ro r1). Also because it has ran the instruction the instruction pointer must be updated, and since it is a one byte instruction it must be increased by one. We will also change the instruction pointer to 1 since that is the operation we’re preforming.

A demonstration of ‘add’ in the repl:

It added 2 and 4 and stored it in R0, yay it works!

Instructions 2 to 6 require little imagination now that we’ve seen how it works:

I’ll skip instruction 7 / 8 and leave it for later since we don’t have a GUI to print something too yet.

Instruction number 9 (load value from argument location into R0) looks like this:

Nth is a function that takes a sequence and returns the value of the second argument which is the location. So ([5 6 1] 1) returns 6.

We use nth to get the value of the location which the argument value of the instruction points to. So if the program looks like this [9 3 0 1] it will load 1 into R0.

Since 9 is a two pointer instruction the instruction pointer must be incremented by 2 instead of 1 so it skips it’s argument.

Instruction number 10 (load value from argument location into R1) is instruction 9’s twin:

Instruction number 11 (write value of R0 in argument location) looks like this:

Assoc is a function that can takes a collection and changes it based on the second and third argument. In this case we use it to change a vector, here the second argument is the value we want to assign to the location in the vector which is the third argument. So (assoc [0, 1 2] 0 3) results in: [10 1 2].

store-r0 uses assoc to change the program / memory. It changes the value of the memory location that the  Argument to instruction 11 points to, to the value that is currently in r0.

Instruction 11 also has a twin in instruction 12 (write value of R1 in argument location). Since you can probably guess by now what it looks like, I’ll leave it be. You can see it in the source however.

13 is the jump instruction, it can be used to change the instruction pointer to anywhere you’d like. Basically a GOTO, just don’t let Dijkstra hear it 😛

In jump nothing happens to the memory, r1 or r2 instead IP is changed to the value of the arguments location.

Instructions 14 and 15 are variations on jump, in fact they use jump:

Now that we can execute every instruction imaginable we need a way to run every instruction until a ‘exit’ instruction is found. We use two functions to do this:

The function ‘run’ simply calls itself recursively until the “step” returned the function “step” is false. This happens when a halt instruction is found. The step function acts as a router for the numbers to the actual Clojure functions.

Now it’s time to create a GUI:

The UI looks like this:

4817-UI

In GUI you find the only variable in this program called “prog”. It is a ref which points to a State. It will be used when the “run” button is clicked. The run button calls the “run” function on that state.

The load button takes the input from the “input” textarea and parses every “int” into a vector. That vector will then be used as the memory / program for the “prog” State.

The step button runs each instruction one step at time and prints all registers each time it is pressed. This way you can see what is going on inside the microprocessor.

Now that we have an output screen is time to define the last two instructions 7 and 8:

Bell is very simple it appends the string “buzz” to the “output” textarea.

Print is the strangest 2 byte instruction, it actually uses it’s argument directly where the others use their arguments indirectly because they are pointers to the “real” arguments. It prints the value of the argument to the “output” textarea.

Note: I recommend the glorious seesaw to create the UI. When I originally wrote the program it was not available. But I would have used it if it were!

And there you have it an e-4917 emulator in Clojure.

Source code can be found on GitHub, note that there’s also an imperative version. It uses the STM to simulate the processor.

Sudoku Solver in Haskell

Haskell, Programming

Background

A couple of years ago I was introduced to functional programming. At first it sounded bizarre and totally impractical, how could you ever program anything without using variables and state!

But the more I read the more intriguing the concept sounded. In a purely functional language there are no side effects. That means that if you call a function with the same parameters it will always return the same result. So coding in this style would reduce bugs and the need for unit tests because functions don’t depend on state. And that’s the reason I started learning Haskell.

I found this Learn you a haskell to be a great introduction to Haskell. And I also bought Real World Haskell a book which focuses on solving real world problems instead being purely academic. Which what some claim is the problem of functional programming.

Anyhow I wanted to get my hands dirty and see if I could do a little project in Haskell using my current knowledge. And a Sudoku solver seemed like the natural choice because there is a lot of lists involved. And lists are the default data structures in FP so its good practice.

But first a word of warning: I’m not a good Haskell programmer, and even though my solver works I don’t think this is how a professional Haskell programmer would do it. If you read this post and you can improve my code please leave me a message. Your help is appreciated.

The solver

To solve Sudoku’s we must first define what the puzzle is. Sudoku’s are 81 cells and each cell belongs to 3 elements: a column, row and block.

Sudoku

The image above depicts these elements. Blue represents block 0, Red column 4 and Green row 4. Note that I start counting at 0 you’ll see why later. The goal of Sudoku is to put the numbers 1 to 9 in each element. Human’s have developed different strategies such as Hatching, Scanning and nishio. But they are all variants on the same solution.

To solve a cell we need all of the cells possibles. We get the possibles by first getting the impossibles: Lets take cell 5 of the Sudoku puzzle in the image above. Its the empty cell in row 0 next to the 7. The impossibles of a cell are the numbers already filled in in that cells row, column and block. Lets take the block impossibles first: these are [1, 5, 7, 9]. The impossibles for its row are [3, 5, 7] and for its column [3, 5, 9]. If we combine all the impossibles of cell 5 we get [1, 3, 5, 7, 9] duplicates excluded.

Now that we have the impossibles we can get the possibles. The possibles are all numbers from 1 to 9 that are not in the impossibles list. That means the possibles for cell 5 are [2, 4, 6, 8]. All we need to do now is pick the right number from our possibles list. We do this by comparing each possibility to all the possibilities of each of the cells elements. If we find that a possibility of the cell we are trying to solve is unique in one of its elements. Then we have found the correct number. I know that this sounds confusing so I’ll show you a detailed example.

Lets take cell 5 again as our example, we know its possibles are [2, 4, 6, 8] lets see if any of these numbers are unique possibilities in the Block, Row or Column.

The column of cell 5 is column 5 and column 5 has the following positions: [5, 14, 23, 32, 41, 50, 59, 68, 79]. But because we are solving cell 5 we don’t need to get cell 5′s possibles. So we must check the possibles of cell [14, 23, 32, 41, 50, 59, 68, 79]. And if any of these cells have the same possibles as cell 5. That possible is not a unique solution anymore so we can’t say without certainty that that number is the solution.

So lets see if any of the possibles are unique possibles in the column. Our possibles are [2, 4, 6, 8] the possibles of cell 14 are [2, 4]. That means our [2, 4] are no longer unique so there out. That leaves use with [6, 8]. So lets check them against the possibles of cell 32, those are [1, 4, 7] this time there not in cell 5′s possible list so nothing drops.

Now on to cell 50 because 41 is not an empty cell. 50′s possibles are [1, 4] again nothing drops. Cell 59 is [7] so nothing drops again but cell 77 is different those possibles are [2, 6]. That means that cell 5′s [6, 8] drops number 6 leaving only 8. And that means 8 is the only possibility left. So 8 must be the number belonging in cell 5. Logical deduction is what they call it.

Now if the number 8 had not been a unique possibility in the column the same process would have been repeated in the block and row of cell 5. Had there been no unique possibility then no solution could be found. Then we would leave the cell open and try the next cell. As the grid got fuller the number of possibles would have been reduced. And then it could be solved at a later point in time.

And that’s how we solve a Sudoku using logic alone. This process is far to tedious for us humans because we can see within a second that the answer is 8. This is because our eyes cross hatch the number 8 . But because my computer has no eyes and I would have no clue on how to program a computer to do this. This method will have to do.

And as a side note my solver won’t ever guess an answer by using random numbers. The upside is that will never have to check if the puzzle is still integer. The downside is that it can only solve satisfactory puzzles. But since Sudoku is a game of logic using random numbers is a blasphemy anyway.

Converting the solution to Haskell

The sudoku grid

First of all we are going to need some way to get all the locations from a block, column and row. We are going to need them to get all the possibles and impossibles for a cell.

And remember that the grid has 80 cells starting at 0 and that each cell is a member of a column, block and a row.

Lets start with the column:

Column takes an Int and returns a list of Int’s. The function is pretty simple just add n to a list an then add (n+9) to the list and repeat this 8 times. So if you evaluate column 0 it evaluates to 0:(9:(:18:(27:(36:(45:(54:(63:(72:([]))))))))) which is an alternative for [0, 9, 18, 27, 36, 45, 54, 63, 72].

Row is pretty easy to:

The formula for row is: the row you want times 9 as the first item in the list. And then add (n + i) to the list 8 times. Lets take row 7 as an example. 7 * 9 = 72 so 72 will be the start point of the list. Then it adds 71 + 1, 72 + 1, 73 + 1 etc to the list. And this results in [71, 72, 73, 74, 75, 76, 77, 78, 79, 80].

Block is a bit harder:

To calculate the cells in a block we need the blocks startpoint. The startpoint is the up most left cell in the block. The startpoint for block 0 is 0 and for block 1 its 3 and block 3 is 6. So the first 3 blocks has the formula: n*3 for the startpoint. The blocks more than 2 but less than 5 need a adjustment of plus 27. So does more than 5 but less than 8. I chose to use guards to implement this. It keeps things clean in my opinion. Now that we have the startpoints for each block we need to get the other cells. We need to get (startpoint + 1) (startpoint + 2) (startpoint + 3) for the first row of the block. For the second row we need (startpoint + 9) (startpoint + 9 + 1) and (startpoint + 9 + 2). The third row is (startpoint + 18) (startpoint + 18 +1) and (startpoint + 18 +2). But instead of describing it overly verbose as I just did I used recursion. Each time number is (startpoint + n + x) where x is the adjustment for the row and n is the column of the block. When n == 2 the row moves up by adding 9 and n is reset to 0. And this a total of 9 times to get every number in the block. Now that we can query for every location of a block, row and column. We need to be able to get the column, row and block for a cell. So I made 3 functions to search for a cell in a block, column or row. These functions take a cell number and return the element the cell belongs to. Lets start with searchBlock:

SearchBlock takes an Int and returns a list of Ints. The list of Ints is the block of the cell. The function again is recursive and tries to find the cell number in each block. The block function we wrote before is used by this function to generate the blocks. If the cell is an element of the current block than it will return that block. If its not an element it calls itself with (n + 1) so the next block is checked for the cell. And because there are only 8 blocks. The function will fail if n equals 9 and raises an error.

Note that I use the infix notation by using back ticks on the function elem. The function elem checks if the first parameter is part of the second parameter and returns a Bool.

searchRow is almost identical:

And so is searchColumn:

You could argue that I should have written a function that would take an element as an argument. That way we’d only have 1 function in stead of 3. The reason I did not do this is clarity, like I said before I’m not a good Haskell programmer. This way I’ll understand my own code after a year.

Impossibles and Possibles

The next step is to be able to calculate all the possibles for a cell. And in order to do that we need all the impossibles. But first we need a way to get a cells block, row and column. We’ll create a function that uses searchRow, searchColumn and searchBlock and combines their results.

This function is named searchCell:

As you can see the function takes n and uses that to add (++) the results of the search functions. You’ll also see sort and nub. Nub apparently means “essence” and it removes duplicates. Sort is used to make the result more appealing for us humans. For some reasons sorted list are easier to debug in my case.

Now that we can get the locations of importance for solving a cell. We can use these locations to find all impossibles. Remember that the impossibles are all the values that are already filled in in a cells row, column and block.

But before I explain “impossibles” I must add that to test my code I created a variable called grid. Grid is a list of 80 elements representing the puzzle:

The 0′s in grid represent empty cells that need to be solved.

The function impossibles:

This is the first function that actually does something with the puzzle. The puzzle parameter is a reference to the puzzle in its current state. The impossibles function also checks if the cell is 0 or not. If the cell is zero it will get its impossibles. If the value of the cell is not zero then its already filled in and that means every number from 1 to 9 is impossible.

The getImp function does the actual work. It takes the locations from searchCell and finds the values for these locations in the puzzle. This is done by looping through the puzzle with a counter: i that increments each time we loop. If i is part of cells the x should be included in the list. Otherwise just ignore it and skip x. If the puzzle is empty will end the list by appending [].

The function also sorts and nub’s the list that is returned.

The isZero function is almost the same as getValues from impossibles:

Again we loop through the puzzle and if i == n where n is the cell. We check if that cell is 0 by checking x. If i is 81 we’re out of bounds and it will throw an error.

Now that we have the impossibles its time to get the possibles for a cell:

If x from [1..9] is not in the impossibles list its a possible so add it to the list. The function continues until it runs out of numbers. If there are no impossibles every number gets added. If nothing is possible nothing gets added and it returns an empty list.

Solving Cells

Now that we have the possibles for a cell we can start solving cells:

This function gets all the possibles for a cell and loops through each possible. When a possible is not a element of the possibles of a block, row or column then its a unique possible. And that means that the solution to the cell is that unique possible.

We get the possibles of an element by getting all the possibles from each cell of that element. Excluding the cell we are currently solving. Thats what the filtering on (/= n) in pos is for. The pos function adds every possible of the element together in a list.

We can now solve cells lets solve the entire puzzle:

I cheated a little here because I’ll always enter the grid value in this function. To remind you: grid is the list representing the puzzle. The solve function tries to solve the puzzle at least 5000 times. The solver can only solve satisfactory puzzles meaning without randomly guessing. So if the solver can’t solve it in under 5000 times it must be a broken puzzle. If that is the case we’ll just display how far we could get. The puzzle stops solving if all the elements are not 0. Because that means there are no empty places and therefore we solved the puzzle. If its not solved we’ll call loop: a function that loops through each cell and tries to solve it.

Loop has two puzzle’s as parameters. One to keep track of the whole puzzle which the solveCell function needs. And the other to loop recursively through. If the value of the cell is 0 we’ll try and solve it and append the solution to the list. Remember that the solution can also be 0. If the value of the cell is not 0 in the function loop. Then that cell is solved already so we’ll just add it to the list. If the whole puzzle is looped through will return the list to the solve function.

Pretty Please

solveSudoku returns a plain old list. And that is not very readable. So I decided to create a prettyPrint function to address the problem. Now this function is very hairy and I’m the first person to admit it, but it works.

prettyPrint:

The function returns IO () so its not a pure function. It starts by printing a verticalLine of 25 ‘-’ characters. Then it will call myprint, a function that needs a solved sudoku and a number to keep track of the iterations. If the puzzle is empty it prints a vertical line to “close” the box. If the iteration is 3 will draw another vertical line and reset the iterator. If the iterator is not 3 will print a line.

The line function takes a list and prints each element of that list. But every 3 prints it will add a “|” character creating the blocks of the sudoku puzzle. At the end of the line functions recursion it adds one final pip.

Note that “myprint grid n” uses take and drop to iterate through the sudoku puzzle.

And the result of prettyPrint is:

 

Conclusion

And thats how I made a Sudoku solver in Haskell. There are probably a million ways to speed up my solver, so if you spot any please let me know.

Animate Mario using Pygame

Programming, Pygame, Python

Getting started

First things first I needed a game loop.

From the file game.py:

Nothing special here I import Pygame and start a loop that ends when there is a pygame.QUIT event. The loop paints a new screen at 15 frames per second. And lets the Mario instance handle events on line 19, and handles animation on line 20.

Line 22, 23 and line 24 are used to draw Mario and the World. But before that happens the screen is painted black. I do this because if you don’t everything gets drawn over each other. You can comment this line out to see it, its a pretty weird effect.

World

Mario needs something to walk on so I looked for an image online and found this one:

background

The image has various ridges and cliffs so I needed a way to make these solid so Mario could walk on them. I decided to put all the solid locations in a list. The list stores the X positions and the Y position of the ridges. Later I’ll use these locations to calculate if Mario is standing on something.

The file world.py looks like this:

Mario

Now that the stage is set, I’ll show you how I made Mario.

Its a bit long but here is mario.py:

Mario gets animated by using a sprite sheet. A sprite sheet contains all the different states (walking, running, flying) of a character, in this case Mario. Because a walking image of every Mario in existence is no fun, I needed to find someway to cut all these Mario’s apart. Luckily there is a way to do that, without actually splitting the sprite sheet into separate images.

Every Sprite has three things an Image a Rect and an Area. The Rect is the position of the sprite on the screen (x, y, width, height). The Area of a Sprite determines what part of the Image gets drawn. Basically an Area allows you to crop the Image of a Sprite. All I needed to do them was to calculate the Area’s of every Mario I wanted to use. But I had to save these Area’s somehow where I could easily access them. So I used a dict the key’s of the would be the name of the Area. This dict is called actions and is located on line 13.

Here’s the sprite sheet:

smw_mario_sheet

Starting from line 40 you can see that I’m assigning states. These states represent what Mario can do such as jumping or running. I use states to determine how Mario reacts to user input, and which Mario to use for animation. But more on that later.

The function handle_event on line 61 handles all user input or lack thereof by passing them over to the current state of Mario. The states will decide what animation Mario should be using by returning a string which responds to a key in the actions dict. This action is then used by the function handle_animation on line 70 which picks the right Area from the actions dictionary.

As you can see in the constructor Mario holds a reference to the World he’s in. In the function check_if_falling on line 74 you can see that Mario uses this reference to check if he is standing. This is where the “solid list” from world.py comes in. If Mario is between X1 and X2, and Y is almost the same height Mario will stop falling.

Mario also checks his bounds in the function check_bounds. If he exceeds the limits of the screen he is teleported to the opposite side like in Super Mario Bros 2.

States

Like I said before Mario’s animation and user input is handled by a version of the state pattern. Before I’ll explain how let’s do the why first.

Handling Mario events may seem easy at first, when you press the spacebar he jumps, and when you press “d” he goes right. But Its not that simple! What happens when you press the spacebar twice, surly Mario doesn’t double jump. The solution is to create a massive amount of if-statements to accommodate for every situation. This, and I’ve tried, leads to an unreadable wall of code, and most importantly you just can’t see where to add new functionality.

I needed a way to make the code more intuitive. Enter the state pattern, a pattern according to the GoF to be applicable when: “Operations have large, multipart conditional statements that depend on the object’s state”. My interpretation: use this when you have a massive switch-statement.

Let’s look at my implementation: state.py in package “states”

This is the template state, It is supposed to be extended by the other states. It provides defaults actions such as walk, run and jump that the child should override when needed.

Lets look at the function run on line 19. Run changes Mario’s internal state to running_state, and then asks Mario’s state to call the run method. The run method will then return the correct animation.

It’s pretty simple when you call jump, fall, walk, run or stand it changes Mario’s state and returns the right animation.

State also provides a way to handle frames of animation in the function get_frame. This function takes a frame_set: a list of strings each representing a Mario, and returns its current frame. When the last frame is returned it resets self.frame to 0. This creates a loop of animations. Some states later such as Running and Walking use get_frame to make Mario run/walk.

Standing

Lets look at the simplest state: Standing in standing.py in package “states”

The __init__ calls the parent __init__ with mario as an argument. This way the state has a reference to the Mario instance. The constructor also assigns some animation variables, left_stand and right_stand. The values are key’s in the actions dictionary in mario.py.

The next function is handle_event this function handles all the keyboard events for the Standing state. Because standing is a neutral state, every action changes the state of Mario. Spacebar makes him jump, “a” makes him walk and so does “d”, pressing and holding “j” makes Mario run.

When there are no events Standing just returns its own stand function. The stand function handles the actual animating part, it just returns left_stand or right_stand based on the direction of Mario.

There is also a __str__ function this function is used for debugging. I used this to determine if Mario reacted properly to events.

Walking

Here’s is walking.py in the package “states”

Walking has the exact same functions as Standing, the difference is the implementation. handle_event its just as you expect it to be, when Mario is already walking and you press “a” you continue walking. Jumping is a little different this time around. When you’re walking and you jump you also jump forwards, instead of just upwards. Thats what the variable mario.jump_forward is for.

When no events are fired Mario will stop Walking and change state to Stand.

Now the actual walking happens in the function walk on line 30. To move Mario forward I move Mario’s Rect to the left or right depending on Mario’s direction. After that its a matter of returning the right animation frame by calling State’s get_frame.

Running

Lets make Mario run: this is running.py in the package “states”

Running is not that much different from Walking. The frames are different and it has a slightly higher jump_forward power.

Jumping

This is Jumping in jumping.py in the package “states”

Lets start with handle_event, this time its smaller than usual and thats because most input doesn’t affect Mario during jumping. It is possible however to steer Mario while he is jumping. The power of this movement is called mario.jump_air_power.

The actual jumping happens in jump, this function moves Mario upwards and depending on events left or right. Mario only jumps a specific height, line 26 checks if that height is met. If that happens jumping is aborted and the state is changed to Fall. If the height is not met then Mario continues to jump.

Falling

Falling shares handle_event with Jumping, the only difference is that Falling returns fall instead of jump. Fall itself makes Mario move down. Each time fall is called, Fall will check if Mario has hit solid ground by calling mario.check_if_falling. If he is standing some variables are reset and the state is set to Standing. If Mario is not hitting solid ground he’ll continue falling.

Conclusion

Well thats it thats how I made a animated Mario. Its not perfect however, some variables could use a better name, and it could use more animations such as turning. I also regret that I didn’t save a version of the insane if-else-tree that I used for state previously. Its the first time that I’ve actually used a pattern, and it shows. I think the code is pretty clear, Its really easy to add a ducking Mario for instance. Maybe one day I’ll create the whole level. That means figuring out how they move the screen through the level, as Mario walks by. But thats something for another post.