Focus

This post has very little to say, but I need to write it anyway. It’s a long ramble about where I’m at now, and where I want to be.

So, that little video game project didn’t pan out so great in the end. But you know what, that’s okay. I learned a lot about Python, Curses, and getting things to work on both Windows and Linux. Here’s a tip: It’s a pain, don’t bother. But as far as difficulties regarding getting a console-based game to work cross-platform go.. The only tricky bits were making sure the character encodings were set-up nicely across both platforms. The down-right DIFFICULT part was getting Curses to work on Windows at all.

Anyway, that was in the past. It’s time to look forward! Another abandoned project, but maybe that’s okay. I spend more time than I’d like sitting down regretting idle, wasted hours. The big problem with lamenting wasted and lost time is that the lament is often a waste of time itself. When I get in a slump, I remind myself that I’m not number one yet, so I have to try harder.

So I’ve started another endeavour. Yes, another one. It’s near the bottom of this post. I never follow through or finish anything, but maybe it’s time to change that? Looking back at unfinished project after unfinished project, it’s easy to fall into the trap of losing faith in yourself. I’ve lost faith in my own ability to finish things so many times, but I always manage to claw back some self-discipline and self-respect to try again. However, these salvaged feelings are suffering from diminishing returns. You can only fall so many times before you stay down, right?

Over time, I’ve become quite good at starting things. And if it’s not a huge thing, I can follow through without too much problem. For example, roughly a year ago, I sat down with a Rubik’s Cube for the first time. Within a few months of playing with it, devouring the vast amount of cube-related information, I was able to solve the cube. Fast. Like, forty seconds fast. Technically kind of slow compared to proper cubers, but you know. That was easy, because it’s just memorisation and repetition. After a while, you switch your brain off and idly practice on the bus or train, letting your fingers do the work while you think about what you’ll make for dinner.

There’s a few things about having learned the cube that bother me:

  1. I can’t tell you why I did it, other than ‘it looked kind of cool and seemed like a fun idea at the time’.
  2. I have absolutely zero use for a skill like that.
  3. It was one of the only things I finished.

Why would that last thing bother me? Well, it’s such a useless thing, completely inconsequential. It has not changed my life in any way. If I used that energy differently, I’d have a finished game (or maybe two) under my belt. At the same time, it’s okay. I want to be one of those amazing people who only do useful things, but maybe that’s an unrealistic ideal. Time will tell.

I have things I want to learn, things I want to do. Some useless things, and some useful things. Knowing the cube? Useless, but fun. It’s nice to watch people’s lips curl into a smile after they watch me solve a cube. I want to learn a foreign language. I want to write a book. I want to ride a unicycle (and maybe solve a cube at the same time?). I want to be better at physics. I want a perfect body (I want a perfect soul).

I never really considered that there wouldn’t be enough time. I didn’t consider that I’d have no willpower, or the attention span of a hyped-up kitten. After a lot of thought, I’ve identified these as the key problems:

  1. Willpower.
  2. Time.

The book ‘Mastery’ by Robert Greene claims that every human being has a calling deep inside them, they just have to find it. They’ll just ‘know’ when it comes, and they will be able to draw strength from this calling. It will be their muse and their motivator. It’s a romantic notion. I haven’t found that thing yet, and to be honest, I’m not really buying into the idea that it exists for even half of people, let alone all of them. So that willpower has to come from somewhere else, or that one thing has to be found.

I’m told by the Internet that a person needs 10,000 hours of practice at an activity before they can be considered ‘a master’. To put that in to perspective, you would have to train every hour of every day for over a year to reach that number of hours. If you spent seven hours a day working on your activity, it would still take over four years to reach the lofty height of master.

So we can’t waste time. If you’re going to become brilliant at something, you have to work at it. The problem is that you need to want it, and you can’t want to stop. That is so hard! It’s one thing to persevere through pain and difficulty, but it’s another thing to want to. Like, it’s the difference between studying because you need to graduate and get a job, and studying because you want to actually know the material and have a deep understanding of the subject for the sake of it.

This means we need to find what we want to do, soon. Earlier than soon, we’re talking like years ago. Probably should have figured out at least one thing to focus on by now. I knew I wanted to go to a good university, but that wasn’t an end goal in itself. I just had no other plans. And then I had to get a job, because that’s just how life is unless you’re pretty brilliant (or lucky).

I’ve rambled enough, so here’s the plan: I’ve put together a timetable. It’s not perfect, and it’s not meant to be. It is subject to change. I will spend my time a little more productively than I have in the past. I’m not going to try for miracles. I know better than anyone that my weekends are likely to fall apart. I know I couldn’t spend more than a few hours a day focusing on things right now. Hell, there’s hardly three hours per night anyway.

So that’s at least one hour a week on a bunch of different things. That won’t help me become ‘a master’ in any of these disciplines. Or rather, it will. In about 190 years, I’d expect to be amazing at all of the stuff in my timetable! The idea is to weed out the activities I don’t find interesting, and give more time to the ones I do enjoy. Some activities are ‘larger': ‘Maths’ and ‘Tumbling’ refer to the full disciplines of studying vector calculus, classic mechanics, contact juggling, riding a unicycle, and so on. I feel I want to be good at something in those areas, I just need to find out what. Others are more concrete, like ‘Blog’. Guess what time it is? The subject of each post isn’t set in stone, but the activity itself is known ahead of time.

Writing out the timetable was a horrifying experience. Subtracting all the time for work, eating, and sleeping, I’m left with maybe six hours a day, out of sixteen, seventeen waking hours.. But hey, that’s almost seven right? If I can find something I’m so enthralled with, that I only want to do that one thing.. Mastery is only years away.

The timetable is set for a reason. With past projects, it’s always a very ‘if I have time’ deal. Or worse, procrastination has reared its ugly head. “I’ll start this later, I need to finish this YouTube video first”. At first glance, setting things in stone seems to be detrimental to willpower as a whole. But I’m trying out a technique of habits. I want to practice things regularly, at set times. Or at least, in the same order. I want to take the choice of ‘what to do, when’ out of the equation, and focus more time on actually doing stuff.

For instance, it’s now 10pm, the end of my blogging hour. Next up, I’ll be reaching out and talking to people. About what? And to who? I have no idea, but the point is to just try. See what happens, maybe end up with a more specific goal for next week.

I’ll sum up quickly: I’m horrified and saddened at at how terrible I am, and how awful I am at stuff. In general. I have very little to show for twenty five years of living. That Rubik’s Cube has become a symbol of the pointlessness of everything I set out to do.

It’s not all doom and gloom. I said before that I always get up and try again. And that’s what I’m doing now. I will work on my willpower, and I will find a calling, something I want to do more than anything else. And even if I don’t, at least I’ll have spent my time doing things I want to do, and even some things that might actually be useful in the future.

That’s it! The most narcissistic post I’ve ever written.. Since I was like, thirteen or whatever, on the LiveJournal. If all goes according to plan, I’ll be back next week. I have no idea what I’ll write about now, and that’s both scary and exciting. If there’s no post here next week, I will have failed.

The Hullet Bells – Part 5 (Valuing your Input)

What is Input Handling, anyway?
Handling input is the process of taking the player’s key presses and converting them to actions in game. Pygame supports two methods for doing this:
1) Examining the state of the keyboard directly each frame, which I’ll refer to as the key state method.
2) Key events, where the game pumps an event queue that is populated only when keys are pressed and released.
Typically, we will attach a function to a key state or event and it will be called when the key is pressed or held.

For the key state approach, the part of your main loop that deals with input will look something like this:

...
  keystates = pygame.key.get_pressed()
  if keystates[pygame.K_UP]:
    moveUp()
  if keystates[pygame.K_DOWN]:
    moveDown()
... continues for each key tested ...

Meanwhile, if you take a key event approach, it will look more like this:

...
  events = pygame.event.get()
  for event in events:
    if event.type == pygame.KEYDOWN:
      if event.key == pygame.K_UP:
        startMovingUp()
      elif event.key == pygame.K_DOWN:
        ...
    elif event.type == pygame.KEYUP:
      if event.key == pygame.K_UP:
        stopMovingUp()
      elif event.key == pygame.K_DOWN:
        ...
...

The first obvious difference is that we won’t check the keys we’re watching for in the key event approach until someone actually presses a key to populate the events variable. The second is that we have a different idea about how movement should be handled: On key down, it starts and will likely continue every frame until key up. The key state approach typically moves players directly (I say typically, because we’ll see later on that it’s not always the case), while the key event approach modifies the player’s velocity, letting the game loop sort out actually moving the player. The former (direct movement) is frowned upon for a reason I’ll touch on later.

The Big Problem with Key Events

With that out of the way, I’d like to talk about one of the interesting challenges when implementing a multi-handler system. Suppose a player is moving their ship to the left when he pauses the game (switching the handler). If the player lets go of the left key and unpauses the game, what is their expectation? Is it:

  1. The ship comes to a standstill after unpausing, or…
  2. The ship continues moving to the left, with further movements to the left doubling the player’s speed, with right key presses causing the movement to stop while the key is held?

I have a pretty good idea myself about what I’d expect. The latter is a pretty serious bug, and it’s one I’ve encountered over and over again.

The above problems are caused when using key events for actions that require both the key down (begin movement) and key up (end movement) events to be caught in pairs. We have issues when beginning a movement, but then the corresponding end movement event is lost. In some implementations of key events, this can be achieved by losing application focus while the key is held, releasing the key, then giving the application focus again. The end result is that the game believes the key is still held down when it is not! Another example using our handler system: holding right and pausing the game will switch the current handler to the pause screen. Letting go of the key then sends the key up event to the pause screen handler, and not the game screen: The key up is lost. When we return to the game, we’ll see the dreaded behaviour above.

A brief aside to discuss the underlying method of moving a ship around the screen: Something you learn from a few game programming websites is that you should never directly modify a player’s position as a result of input. Instead, input should modify the player’s velocity. That way, because you’ve been a good programmer and decoupled the input and game logic, the game itself will be able to decide if the velocity applied will affect a movement. It shouldn’t if the player is at the bounds of the game area, for instance, but directly moving the player means you lose the information about how the player got out of bounds, so they may not be correctly placed back on the field. So directly modifying position is out. The idea that helps solve this: Key down means you affect the player’s velocity in some way, key up means you reverse that change.

This is a great piece of advice when implementing the movement stuff for your game. A common pattern I’ve seen on game tutorial sites is to add to the player’s velocity on key down events, and to subtract the same value on key up. This unfortunately causes the problems described above if a large number of precautions aren’t taken, including but not limited to:

  • Making sure a key up is ignored if we haven’t seen a key down from that key
  • Maintaining a list of all held keys when switching between handlers (can be rolled in to the above)
  • Making sure any paired events don’t let one half of the pair fire more than once (two key downs in a row, say)
  • When switching between handlers, checking every key in the new handler, seeing if it is waiting for an event, and firing it if the key state has changed (not ideal, because this means the player will have to repress the button after unpausing, say)

It’s a lot of messing about. I might add, it’s not wrong either (when you correctly code the safeguards). It can be a pain to code, and the edge cases extend beyond what I’ve outlined above. As a result, I attempt to keep things simple: we should never require an event pair in the first place. Instead, for movement functionality traditionally provided by events, I instead use the key state: A map of each key to a boolean value, either true for pressed or false for released. Every frame I check if the left or right key is pressed, I add to the velocity as normal. However, rather than subtract when the key is lifted, I reset the velocity at the end of the game logic for that frame. Suddenly, all of the above problems disappear: with no events to miss, we can’t get the velocity in a weird state, especially when it is reset at the end of every frame anyway.

This introduces something that some might be considered a bug: Suppose the game runs at 60 FPS and I’m moving to the right. That is to say, I am holding the right key. If I release the key after I’ve moved that frame and before the next frame hold the key again, it would be as though I never let go of the key in the first place. Given that we’re running at 60FPS, that gives you roughly 0.0167 seconds to push it. Most likely, you simply can’t release and re-press that fast. Even if you could, under most scenarios this is not a problem. Indeed, for movement this is the exact same behaviour you’d see with key events: On the second frame you would see a key up and a key down event, with the net result of no change in your velocity. There are conceivably scenarios where this is a problem. Consider you could charge a shot by holding space, and fire by releasing. If the player wants to fire a shot and then begin charging a new one, the key event approach would win out: Space bar comes up, space bar comes down, so you get both events on the queue and they’re processed on frame 2. Under the key state approach, we wouldn’t fire the shot. Again, this is a bug, but we would only see the problem if the player is really, really, really fast. I can’t stress how fast he would have to be! They would have to be faster than this dude. So we sacrifice a small bit of functionality in the case where the player is faster at pushing buttons than the world champion. It’s a sacrifice I’m willing to make.

In actual fact, key events will fall over here for movement too: If you tap the right key and get the key down/key up within 0.0167 seconds, the net result will be no movement, just like the key state approach. Maybe it’s not so bad after all! At least for movement. But what about performance? As it turns out, I did some number-crunching on my desktop computer and came up with the following: It takes one millionth of a second more to watch 10 key states than it does to wait for any number of key events (which takes no time, really, because the event loop isn’t populated until you actually press things). I think that’s acceptable! And even on a non-monster machine, it’s not going to take up a significant amount of time compared to the rendering or actual proper game logic. If you want to compare the approaches, here’s a gist of what I did. You’ll need pygame to run it, of course.

So, we’re trading a millionth of a second and a little bit of velocity resetting logic for the peace-of-mind of not having to deal with the edge cases of the key event approach for paired events. I’d call that a fair trade. Hullet Bells runs on a hybrid system: Key state-based function calls for movement (and later shooting), and key events for rarer events like using a special attack or pausing the game. In fact, the input handler presented in the gist is the same one used in Hullet Bells! Yes, it has some pretty gnarly named functions (what’s all this talk about callbacks? They’re just functions!), but it is basically the complete implementation of the system. One limitation is that I have no support for key combinations (say, calling a function if two keys are pressed, rather than just one), but for Hullet Bells (and many shooting games) this is an acceptable limitation.

The Hullet Bells InputHandler

The goal of the InputHandler was to allow isolation of the input logic between handlers, and to make programming input stuff as painless as possible. As long as you’ve defined the logic you want behind a key, actually attaching it is as easy as making the following calls:

# For key states
self.inputHandler.addPerFrameCallback(self._moveUp, pygame.K_UP)
# For key events
self.inputHandler.addPerFrameCallback(self._startMoveUp, pygame.K_UP, KEYDOWN)
self.inputHandler.addPerFrameCallback(self._stopMoveUp, pygame.K_UP, KEYUP)

These cause the event/key to be put in to lists that are evaluated every time inputHandler.update() is called:

  events = pygame.event.get()
  for event in events:
    if event.type == pygame.KEYDOWN:
      for keydownCallback in self.keydownCallbacks:
        if keydownCallback.key == event.key:
          keydownCallback.callback()
    elif event.type == pygame.KEYUP:
      for keyupCallback in self.keyupCallbacks:
        if keyupCallback.key == event.key:
          keyupCallback.callback()
...
  keystates = pygame.key.get_pressed()
  for perframeCallback in self.perframeCallbacks:
    if keystates[perframeCallback.key]:
      perframeCallback.callback()

For the key event stuff, it has just occurred to me that it would be nicer to store all KEYDOWN etc. events in a map of [event -> (key, callback)]. Also, for key states it might be nice to attempt to call all functions related to pressed keys regardless of whether a function exists or not, then we can eliminate the if statement too.. Anyway, those are actions for another time! As it stands, the input handler runs pretty well, so I’m not exactly looking to optimise yet. For the complete code, you can check out the Github or the above gist.

This was far too long, and didn’t really go anywhere. But that pretty much covers everything I wanted to talk about: Input handling in general, some of the problems you might have, and finally, my own implementation using the pygame library. I’d love to say the next post will be about the scripting system, but I’ll have to finish that before I can write about it. So if I want to write a post before then, I’ll talk about the game handler itself as it stands.

The Hullet Bells – Part 2 (Getting Organised)

Recently I embarked upon a quest: a quest to produce a platform game, the likes of which the world had never known. However, I got bored of that, but not before exercising my Python chops. Although I failed, I discovered the wonderful pygame library. Pygame is a Python wrapper for the ever-popular C++ SDL library, which I had used before when working on a small game project with a group of university friends. Much like the project preceding this one, the university project died an untimely death, this time due to heavy college workloads.

Still, both experiences provided a great number of learning opportunities, and during university a six month placement at a video game company let me take a peek under the hood of some pretty heavy AAA title stuff. I took what I learned then and tried to apply it to the platform game, but a general lack of interest on my part meant the project had no chance of survival.

Thinking back, there’s only been two genres I’ve really ever fallen in love with: Platforming and shmups. Sure, I’ve had my flirts with RPGs, particularly JRPGs. As I’ve grown however, I just don’t find them nearly as charming as I used to. Recently, I went back to Final Fantasy 7 to give it a proper playthrough, this time around older and wiser. I figured I might be able to appreciate the combat and magic systems a bit more, because now I’m a more patient, understanding guy. Sadly, I also have a lot less time than I used to, and it turns out those systems never had any depth after all: It was all just grinding in the end, like pretty much every other RPG I’ve ever played.

So I’ve come to appreciate the platformers and shmups. With less time to spend on leisure than ever before, it’s important to me that I maximise the enjoyment I get from the limited time I spend on games. Don’t misunderstand, I do branch out occasionally with new releases outside my comfort zone! But when I need to relax, being able to pick up a platformer and speed through it means a lot. The average shmup won’t take more than an hour per playthrough, so you already know in advance how long you’re likely to spend on it (Side note: There are some insane examples of shmups with multiple ‘loops’, meaning you start back and play through again on an increased difficulty level. These can take several hours to fully beat, and must generally be done in one sitting!).

Why did my platforming game die? I’m not sure myself. I think there was a deadly combination of boredom and laziness. While I’d love to get in to the Procrastination Formula, that might be a topic for another time. The short of it is; I didn’t block time to get my teeth in to it, and when I did have time I wouldn’t develop the right features to bring it towards a minimum viable game. Rather, I spent time developing fluff features like ladders or tweaking values that could wait until later.

This time around, there is a system. I intend to spend at least 25 minutes a day focused on this shmup engine, more if I’m on a roll. I have also mapped out some of the key requirements for what will constitute a complete shmup. In a somewhat mock-Agile approach, these requirements take the form of one-line user stories grouped by screen (title screen, game screen, options screen, etc.).

Having once taken a half-day Agile course, I’m something of an expert on the topic. I can do away with that separation of product owner, scrum master and development team garbage because I am in fact all three! Indeed, this is why I call this shaky approach ‘mock-Agile’, because I’m making a mockery of it. That said, taking parts of Scrum seems to work even for a one-man dev team. Here’s an example of the embarrassing list of requirements I came up with:

Title Screen

  • I want to be able to navigate a menu at the start of the game
  • I want to be able to start the game via the menu
  • I want to be able to quit the game via the menu

It might look silly and insignificant, but this sort of thing keeps me on task and aware of what needs to be done. At this point, you may be wondering if I’ve even done any development yet, what with all the mocking and pondering. Well, take a look at this!

The white box is the player, the green box is a baddie, and the blue one is a bullet! This is cutting edge stuff, guys.

The white box is the player, the green box is a baddie, and the blue one is a bullet! This is cutting edge stuff, guys.

Prior to finally buckling down and properly organising myself, I did a bit of development on and off, tearing bits out of the platform engine and transplanting them in to the shmup. In all, I estimate that about four to five hours of actual work went in to the shmup over the course of a month. It’s time to buckle down and make something. Next post I will give you a sneak peak behind the scenes of how I’ve structured the game.