Tag Archives: keyboard handler

The Great Soul-Searching Odyssey, Part I

March has come and gone, and the blog has lain dormant this whole time. Not cool, Ryan. Not cool. So what have I been up to in that time? It turns out quite a lot, though not as much of it was as productive as I would have liked. Here is my tale.

Remember back in February when I happily wrote about creating my first keyboard handler? (If not, just jump down to the next post. Go ahead. I’ll wait.) It turns out that, despite the awesomeness of said handler, JAWS, the eternal programming thorn in my side, didn’t want to play nice with my code. In particular, it wanted to steal the use of the arrow keys for itself, thus keeping them out of my program. As any of you who have had to put JAWS to sleep in order to play a large chunk of audio games can attest, this is pretty annoying.

I was determined to figure this problem out, however, so I started searching high and low for solutions. The title didn’t lie. This really is an odyssey.

First, I traveled to the land of the great and powerful Pygame developers. Well actually, I just wrote an email to their listserv. Be that as it may, many of them recommended a module called pyHook, a powerful artifact which, according to legend, could freeze the dreaded JAWS in its tracks and prevent it from making off with my arrow keys. But oh man. PyHook is something like 10 points beyond my current skill level, and even its documentation was nearly indecipherable to my n00b mind.

Nevertheless, I threw everything I had against pyHook, aided somewhat by a wise old sage named Alec the Brave.* After what seemed like 10 days—because that’s about how long it was—I managed to throw together a workable solution that allowed me to run my demo side scroller and keep JAWS up and running at the same time. Some of you probably saw my exuberant tweet on the subject.

*Alec’s wisdom is beyond reproach, though his age and sage status have yet to be determined.

Alas, though, my struggles were for naught, for as soon as I began to tweak and debug the program, I realized that pyHook—and here I’ll use the technical phrase—“broke the hell out of” my keyboard module. I’ll spare everyone the gritty details, but suffice it to say that holding down keys was a nightmare, and even though the arrow keys kind of worked, they absolutely didn’t work if something like the control key was held down. All of this meant that if I chose to continue to use pyHook, I would invalidate the eight days I had spent designing and implementing my keyboard handler. What’s more, I had once again run out of ideas on how to proceed.

So what did I learn from the first leg of my journey? I learned that sometimes, the problem I need to solve isn’t as immediate as I think. More than that, I learned that it’s way too easy to get bogged down in side projects that leave me no time for working on important things—like punching a clown in the face. When the day comes that JAWS speech is a deal breaker, I’ll figure out the arrow key problem. Either that, or I’ll have it done for me by someone with a lot more expertise and skill.

Until then, I want to code a game, and that’s just what I intend to do.

Therein, however, lies the next step on my soul search, but since it’s almost midnight, I’ll have to save it for another day.

Building Tools

One of the things that makes coding particularly awesome—especially in the case of Python—is the ability to reuse code. If the programmer writes things in such a way as to make them generic enough, he can then take those generic sections of code and apply them to different situations. As one might expect, reusing code that has already been written speeds up development time considerably by allowing the programmer to automate different chunks of the program. To illustrate, let’s put this in the context of one of my apparently recurring themes, doughnuts.

Say you decide one morning that you’re going to start your own bakery. You get the space, buy the equipment and groceries, and refine your recipes. The problem with your bakery setup, however, is that you’re the only employee, which means you’re responsible for everything from purchasing groceries to preparing pastries to dealing with the customers to cleaning up afterward. If you continue in this fashion for a while, you will get things done. In fact, you might even turn a profit if you’re lucky. Unfortunately, though, your business won’t grow very much until you can get some help, and, quite frankly, you’re getting tired.

To take some of the pressure off of you, you decide to hire and train someone to help out around the place. You hire a new kid, train him to do basic jobs like cleaning the seating area and washing dishes, and as a result, free up more of your time to invent, cook, and socialize with customers. Things are going just fine for a while, but you eventually come to realize that your business could be even more productive if you hired a third person to help you with the morning doughnut frying and filling. Side note: jelly doughnuts, you guys. Seriously. Jelly doughnuts.

Reusing code is a lot like the metaphorical bakery. You find a task you have to accomplish pretty regularly, and you farm the work of that task out to a separate process. Either that, or you take a complicated, time-consuming activity and wrap that up in a function somewhere. Here’s an example in non-bakery terms.

I am currently using Pygame for its ability to process keys. When I want to figure out what keys are being pressed, it can look a little something like this:

  1. for event in pygame.event.get():
  2. if event.type == pygame.KEYDOWN:
  3. if event.key == pygame.K_LEFT:
  4. player.walk(x=-1, y=0)
  5. if event.type == pygame.KEYDOWN:
  6. if event.key == pygame.K_RIGHT:
  7. player.walk(x=1, y=0)
  8. if event.type == pygame.KEYDOWN:
  9. if event.key == pygame.K_UP:
  10. player.walk(x=-0, y=1)
  11. if event.type == pygame.KEYDOWN:
  12. if event.key == pygame.K_DOWN:
  13. player.walk(x=0, y=-1)

If you didn’t bother reading all of that, I don’t blame you. I certainly don’t want to have to write it every time I want to create a game. To solve the problem, I created a code module whose job it is to carry out those basic functions, and all I have to do is give it two pieces of information: which key should call which function, and when the module should check to see what keys have been pressed down. The code for the first part looks like this:

  1. keyboard_handler.register_keydown(‘left’, player.move, x=-1, y=0)
  2. keyboard_handler.register_keydown(‘right’, player.move, x=1, y=0)
  3. keyboard_handler.register_keydown(‘up’, player.move, x=0, y=1)
  4. keyboard_handler.register_keydown(‘down’, player.move, x=0, y=-1)

And when I want to have the program check which keys are down, I just do this:

  1. for event in pygame.event.get():
  2. keyboard_handler.process_key_events(event)

With a single call to process_key_events, I tell the program to go look at my shiny, new keyboard handler and run all that bloated code you saw above. Instead of having to type 13 lines of code, I now only need to type 6, thus slashing my required code by more than half. This makes my programs easier to write because there is less writing to do. At the same time the code is easier to debug because there is less of it to read. Productivity 1, frustration 0.

I’m excited to be finished with the tool-making process—at least for now. I’m equally excited, however, to have designed something that can really speed up coding and simplify development, not just for myself, but for anyone who wants to code in Pygame. Che Martin of Blind Adrenaline Simulations once told me about two weeks he spent building a module to make jaws speak in his games. At the time I couldn’t fathom spending two weeks coding something that wasn’t directly connected to a game. Now that I’ve spent 8 days creating my own tool to build into all of my future projects, though, I understand what he meant, and I appreciate the experience.

Downs and Ups

I looked at the website today as Randi and I were searching for the renewal email, and it occurred to me that I haven’t posted an update in over a month. In fact, it has been closer to two months since I posted anything, and as of my last writing, I was still hard at work on boxing. I think the biggest reason for my absence has been that while a lot has happened, not much has been accomplished. Let me try to explain.

My last post was full of optimism about the coming break and the progress I would make on the boxing game. As soon as school finished for the year, however, I managed to contract a really nasty piece of malware, and I found myself having to reformat my computer. As I was upgrading from Windows XP to Windows 7, however, I neglected the fact that the new install didn’t wipe out the old one, but rather installed alongside and throughout it. Thus, I wound up with a tangled amalgamation of two operating systems with a virus lying dormant somewhere in the ruins of the Windows XP side.

No problem, I thought. I’ll just reformat again.

This time, the reformat and reinstall went off without a hitch, and I figured I was Scott free. Side note: I bet there is totally some dude out there named Scott Freeh, and he probably gets a lot of grief from people. Poor guy. Anyhow, I set up Carbonite to start restoring my files, but a mislabeled checkbox caused the program to start dumping the entire backed-up contents of my old format into my pristine new one. This meant that I had directories for Windows 7 that were bare and desolate, and I had jam-packed directories that followed the Windows XP folder structure, all of which were hopelessly entangled once again. Because several gigs had been dumped into my pristine format before I realized the error—that’s what I get for restoring overnight—there was no way to quickly fix the problem.

You can probably guess what I ended up having to do yet again.

Amongst my 3 reformats were all the things that ordinarily occur throughout the holiday season: traveling, dinners, spending time with family, etc. As a result, New Year’s came and went, and I hadn’t written a single line of code. I ended up going back to work on January 2 having accomplished absolutely nothing during the Christmas break.

And then came the coding craziness. I finally realized, after banging my head against the problem for some time, that there was no immediately plausible way to carry out key commands that utilized multiple key presses. For example, holding up arrow and pressing a could not throw a left hook to the head using my current library. So I needed to find a new library—one that would allow me to press multiple keys simultaneously.

First, I tried looking for python-based solutions to the problem. The only solution I could find, however, was the Pygame library. In talking to other audio game developers, I found very little support for Pygame, with criticisms ranging from speed of execution to a lackluster sound library. When I brought up Sound RTS as an example of a great game that just happened to be written in Pygame, it was pointed out to me—accurately, I might add—that even it suffers from very slight execution lag on things like key presses.

So, scared off by the boogie monster of latency, I started looking at BGT, the audio game development toolkit written by Philip Bennefall of Blastbay Studios. Because the core components of BGT are written in C++, execution of almost anything is incredibly speedy. Another feather in its cap is the fact that Philip is an INCREDIBLY NICE GUY! I cannot stress that last point enough.

However, I soon discovered two problems with using BGT, neither of which had anything to do with the language itself. The first of these was the fact that I had already spent a year learning to program in Python, and I was loathe to throw away all of that practice and knowledge in favor of a different language. The second was that I had incredible difficulty switching from a Python mindset to a BGT one, and as almost everyone who has ever rerolled their character and become a newbie again will tell you, starting over sucks.

In order to reconcile the conflict in my head—Python versus anything else, speed of execution versus speed of development—I did what I should have done a long time ago. I signed up for the Pygame mailing list and started asking questions. I received a number of intriguing answers, but probably the best of them went something like this:

You’re so busy spending all of this time worrying about speed and lag and all of these other things that haven’t come up yet that you haven’t even written a single line of code. Many, many people have written great games in Pygame, and they haven’t run up against a speed barrier. So program something—anything—and if you start having problems with speed, there are work-arounds for that.

When I decided to adopt this mindset, it opened up a whole new world of possibility to me. Instead of seeing potential difficulties as obstacles, I started seeing them as barriers to be broken down. Instead of looking at things through a lens of negativity, I started finding more positives. So what if Sound RTS has a tenth-of-a-second lag on key presses. It’s not like that style of game requires lightning reflexes anyhow. And I didn’t even notice the lag until someone pointed out to me, so what did I care? It’s still a great game.

But I didn’t want that lag, because the kind of games I’d like to develop will require lightning reflexes. So I started looking into why it existed in the first place, and almost immediately, I found the answer. It turns out the chief Python critic on the Audyssey list was right, though it chaps my hide to admit it. The sound support for Pygame isn’t the greatest, and when used in a certain way, it can create all sorts of slowdown in programs to the point that, if you make the sound buffer size too large, it can take over a second to modify any currently playing sounds. Huge problem, right?

Well no. If the Pygame sound module slows things down too much, don’t use it. Problem solved! Seriously, it’s that simple!

And just like that, I’m back in business. I’m using the Pygame keyboard module to handle all of my key presses, and I’m stoked about the things it can do:

  • It keeps track of each key press that the user generates, and it gives the program the opportunity to act on these. If, when looking through the key presses, the program finds an “up” in the list, it can run through its analyses and decide to make the player jump.
  • It has a key_pressed function which allows the program to check what keys are held down. If, while walking across a level, the player holds down the control key, the get_pressed function will see this and make the player run.
  • It tracks when players release keys, and it can use this information to call additional events. If, for example, I wanted to program a laser gun that charged itself up as long as the player held down the control key, then fired when the control key was released, I could do that!

As for the sound library, I just switched back to using sound_lib, the library that’s served me well through both Block Party and boxing. It has all of the functionality I need to program with none of the lag, and if I need it to do more, I can tweak the programming myself.

With all of this in place, I have one last hurdle to overcome, and that’s learning to write comfortably in Pygame. I’ve made a car engine that revs up and fades as you press the up and down arrow keys and steers from side to side as you press left and right. I’m in the process of making a character that walks from left to right and back when you press the left and right arrows. These things still don’t feel fluid to me, though, and only time and experience will change that.

What does this mean in terms of game development? Sadly, it means it’s going to take a little while to get things back off the ground and headed in the right direction. More importantly, however, it means that game development is still progressing. Those of you following the twitter feed will note that activity has started to pick back up as I run Pygame through its paces. Things will get moving again, but they may take a bit longer than any of us would like. I’m not out of the race, though. I can promise you that.