## Math RPG - Part 9: Importing image sprites on Khan Academy CS platform

Since the semester started, I haven’t worked on my Math RPG project. Most of my time has been spent memorizing terms in my Anatomy and Physiology course and working on some smaller programming projects. One of those projects was an attempt to port my RPG to the Khan Academy Computer Science platform. There are some cool programs there, especially the 3D-Minecraft program created by John Resig. My first experiment was to see if I could use my sprites on their platform since external images are not allowed for obvious reasons.

There were already programs that imported images using various techniques. One popular approach imported jpeg images using an image optimization algorithm and then generated the necessary function calls to draw the image.

Since the sprites I planned to used were small images (32x32 or 48x32), my simple solution was to convert the bitmap data into a 2D array of RGB values. Pasting this array into the KA CS platform caused the editor to freeze and lag. Eventually I was able to write the code necessary to draw the sprite mainly using the point() function.

The demo using this approach can be seen here.

My first optimization was to use a hash table to look up RGB values. This was possible since the images use a limited set of colors. Here is a link to this demo.

Although performance improved, this approach didn’t seem scalable to multiple animated images, so I looked for other solutions.

When I inspected the code from the 3D Minecraft program, I noticed that the canvas element was used. This turned out to be somewhat of a hack since the canvas element is normally not accessible. The hack involves knowledge of how Processing JS works and considering John Resig developed Processing JS and is involved with the Khan Academy CS program, it makes sense that he knew how to get around the restrictions.

The tricky part was figuring out how to modify the code to work for my use case. Access to to the canvas element would definitely make it possible to render animated sprites with good performance. The hack seems to involve overriding certain functions used during initialization of either Processing JS or the Khan Academy CS platform. It’s difficult to determine what modifications are needed, but my set of changes worked and allowed me to draw a static background with my characters. The demo can be viewed here.

The next step would be to further optimize the size of the sprites. When there are multiple sprite arrays pasted into the editor, it can crash Chrome and make you lose all your work since there is no auto-save. What I have in mind is maybe using a discrete cosine transforms (DCT) and huffman encoding. I’m not sure if those techniques will help much. Mostly, I just interested in learning how to implement those algorithms.

Here is the relevant snippet of code: