Showing posts with label game dev. Show all posts
Showing posts with label game dev. Show all posts

Wednesday, April 7, 2010

How I Learned Python

Being primarily a C++ programmer, I have lived a hard life: All the rules, all the syntax, all the mean spirited compiler errors from the STL...

While I have dabbled in scripting languages in the past, I never really put too much time into learning one. I decided it was time to learn a scripting language in more detail, and I chose Python. The best way to learn a new language is to create a relatively complex program in it, so to accomplish this task, I set out to make a game in no more than 7 days using Python and PyGame (SDL wrapper). Being familiar with using SDL from C++, I felt confident this project would be a success, and it was. 4 days later, I had a new game, "Cloud Cover", and I knew a decent amount of Python. Here's how it happened.

Game Design

I had been toying with an idea for a game that involved the rain theme for quite some time. Originally, I wanted to develop the game for the iPhone and take advantage of the tilt-control. The idea at that point was to tilt the iPhone left and right to tilt platforms in order to fill up buckets with water in order to progress in the level. However, not particularly liking Objective-C or the hoops needed to jump through in order to develop for the iPhone, I nixed that idea.

After hearing the instrumental "2 Die 4" by 'John 5' and then going to sleep, I awoke with the game design in my head. It literally came to me in my sleep. In fact, I even feature the song in my game because it fits so well (and it should since it inspired the game!).

Essentially, the game design is as follows:
  • You play the part of a bowling ball who must fill up beakers with rain drops.
  • On each level, you will have either 1 or 2 beakers to fill, and they may be positioned with at most 1 beaker on each side of the player 
  • The game will only have 2 controls: roll left and roll right. This adds to the challenge of the puzzles because you can only move each beaker in 1 direction.
  • Rain is created by a dynamic rain system from 1 or 2 clouds per-level.
  • The clouds can be configured to behave in many different ways, such as: being stationary, moving left/right (single or multiple passes), being restricted to certain x-value bounds, having endless rain drops, or having a limited supply of rain drops.
  • Tweaking the dynamic rain system along with the placement and movement of the cloud(s) and beaker(s) can be used to create challenging puzzles
Implementation

Dynamic Rain System

Implementing the dynamic rain system was a lot of fun, and a lot easier than you may think. Basically, it boils down to this:
  • Assign each cloud a life span (number of drops it can produce)
  • Assign each cloud an intensity value (number of drops it produces per-frame)
  • Using the dimensions of the cloud, generate a random x,y coordinate at which to generate a new rain drop within the bounds of the cloud.
  • Generate the rain drops in a loop ranging from 1 to the intensity value
  • For each drop created, subtract 1 from the life span of the cloud
  • As long as the life span is > 0 (or the cloud has an infinite life span), continue to generate rain
Pretty simple, eh?

Beakers

There were a few things I had to deal with when implementing the beakers. First, I wanted to have some sort of physics effect so that the character would be slowed down while pushing them. I decided to fake the physics first and see how well it worked before implementing the real deal. I got lucky on my first attempt at this. I gave each beaker a fractional weight value (settled on .5). Then, on collision, I would multiply the player's speed by the weight of the beaker. Since it is a fractional value, it would decrease the player's speed by a factor of the beaker's weight. The result is a very believable friction effect. Sorry, Newton, I don't need you today...

The next issue with the beakers was getting them to "fill up" as they caught rain drops. This one took a little bit more time to nail down, but I'm pretty happy with the solution I came up with. Basically, each beaker keeps track of how many drops it can hold, and how many it's already caught. Using these values, combined with the height and width of the beaker, I do some simple division to create a fill percentage and draw a filled rectangle inside the beaker. This gets updated on every game update, so as you collect more drops, the box grows taller and taller, thus the beaker appears to be filling up. Until the beaker is full, the box is the same color as the rain drops, and once full, it turns red so the player knows to stop trying to fill it. Some normalization had to be done for when the beaker does fill up, as well as to account for leaving some space on the sides, but the code for this is pretty straightforward:



I did have to address one issue with the beakers in that they were detecting "caught" drain drops anytime they collided with a rain drop. Clearly, you could collide with low-falling drops by pushing the beaker into them, but that's hardly catching them, so it had to be fixed.

See this post for details on how I went about that.

Player

The player is a fairly simple piece of code, although there is one neat trick I employed. I was faced with the question of, "How do I make the bowling ball roll around?". Sure, I could do some involved math to do it, but I'm just using a static image for the player character. So, what to do? Rotate the image!



Conclusion 

All in all, the game took around 4 days, but probably only about 15-20 hours of time. It was essentially the first non-trivial program I had ever written in Python, and it turned out really great if I do say so myself.

You can find the game here

                         
 


Just A Drop In The Bucket (or was it?)

I had a known bug in my new game, "Cloud Cover" which involved detecting a "caught" rain drop when the drop actually hit the side of the beaker instead of in the opening. I knew about the issue, but due to the mechanism I was using to detect collisions (a pre-made function from the PyGame library), the solution wasn't immediately apparent. It would have been difficult and clunky to adjust the iteration on each collision detection to then ensure that the drop that had been detected as a collision was in the acceptable range, being y <= the top of the beaker (y increases towards the bottom of the screen).

So, after some thinking, I came up with the following solution: Instead of checking the y-value of the drop once a collision is detected, only check for collisions against rain drops that are within the acceptable range. It works great, and it's pretty slick if I do say so myself.

First, I store the heights of all beakers in the current level. Currently, each level has at least 1 beaker, no more than 2, the beakers exist for the duration of the level, and they are all of the same height. However, in the future this may change, and beakers may even be destroyed as the level plays on, so I had to ensure that I was able to keep track of the beakers that were currently on the screen: having a static list of the beakers that the level started with wouldn't have been sufficient. Then, I sort the list of beaker heights. This ensures the smallest beaker height will be in the front of the list. This is crucial because I need to use the y-value of the *smallest* beaker as my baseline for accepting collisions because even if I have taller beakers, a y-value of <= the smallest one will also suffice for any beakers taller (remember, y gets larger as it approaches the bottom of the screen). Now that I have the y-value of the shortest beaker, I check against this value when a collision is detected. If the rain drop's y-value is <= this number, I know it is within the area of the opening of the beaker, and I can consider that a collision, and thus a "caught" rain drop.

This also has a nice benefit in that it eliminates a number of otherwise useless and costly collision comparisons. Before, every drop on the screen was being checked for a collision. Now, any drop that is below the shortest beaker is ignored entirely. With enough drops on the screen, this can be a big savings in performance.

The code for this is as follows:

Thursday, April 1, 2010

Game In A Day - "Hangman"

The second installment to my Game In A Day series is a project I started many years ago, and have maintained in not-so-consistent fashion: Hangman.

I wrote this about 5-6 years ago in C++. The interface was console-based only and this lead to a lot of added headaches and bugs. I've been meaning to throw a GUI on this project for a while, but just never got around to it... until now!

As part of my Software Engineering capstone, my group and I are making a set of educational games to teach 4th and 5th grade curriculum in Math, English, and Reasoning Skills. The English side of things was lacking a bit, so I decided to create Hangman in the context of my capstone project. Note that at the time, there were only 4 weeks left in the course and we had moved every other project into their final phase. So, if Hangman was to be added, it would definitely have to be developed in less than 1 day!

Interface Design
I came up with the design in a fairly short amount of time while I was sitting in one of my morning classes. Obviously, Hangman is a classic game and interfaces for it can only vary so much, but I did add a few tweaks. First, I designed it so that the vowels and consonants are displayed to the user in horizontal list form. This assists in the curriculum for the target audience as they can learn to identify the different letters as well as learn the words and definitions. Second, guessed letters (both correct and incorrect) get removed from their respective lists. This helps the player keep track of what they've already guessed and what's available to guess. Last, I added a "Solve" button to the interface so that at any time they can choose to solve the puzzle.

Game Design
Much like the interface design, the gameplay for Hangman is relatively set in stone. The flow that I went with is as follows:
  • A definition is displayed to the player
  • Below the definition, a series of _ characters are displayed to the player to represent the number of letters in the answer
  • When the player types a letter, the game checks to see if that letter is in the puzzle, and if so, replaces each corresponding _ with the guessed letter.
  • A wrong guess results in the next Hangman image being displayed to the player on the interface. The images are looked up using the number of questions wrong as the index into the vector of images. In total, there are 9 images, and the game is over when you've missed 9 questions.
  • At any point the player can choose to hit "Solve" and try to solve the puzzle. An incorrect guess results in the player losing.
Pretty simple, eh?

Tools
I decided to use C++ and QT for this project because I'm very familiar with QT and it is an incredibly powerful library.

Implementation
Instead of adding a GUI to the pre-existing code I had, I decided to write the entire game from scratch. Using QT made this quite simple, actually. It allowed me to use the built-in QT types for everything (QString, QChar, QVector, etc...) and keep the code clean and consistent. You would think that writing a game entirely console-based would be easier, but when you have to deal with validating user input, alternating between std::string, char*, and char, things get messy in a hurry. Also, organizing game flow and game state create equally messy situations. A GUI environment like QT eliminates this mess with the use of dialogs and events to properly handle flow and state changes.

All in all, the implementation was fairly straight forward and consisted of the following pieces:
  • Event handler to grab alphabetic input (ignores all other input)
  • Function to check if a letter exists in the answer (and every location in which it does)
  • Function to handle solving the entire puzzle
  • Function to remove the last guessed character from both the vowel and consonant lists.
  • Functions to handle a correct and incorrect guess
  • Function to handle the end of the game
  • Function to handle resetting the game to the initial state
That's it. Total, the project only took around 5 hours from start to finish, so I'm very pleased with that result. The only thing left to do is to plug it in to our QuestionManager to dynamically grab pre-made questions.

Notable Code Snippets

Determining If Input Is An Alphabetic Character



Finding Every Occurrence Of A Letter In A Word

Tuesday, July 28, 2009

Designing A Hockey Power-Play System: Part 3

I finally found some time to sit down and revisit this problem. I made the decision a few days ago that I would wake up and devote my entire day to solving this problem once and for all, and I did just that. I realized that I had been going about the problem in the wrong fashion, which is why I never seemed to be able to come up with a solid solution.

If you haven't read the other 2 posts on this topic (or if you haven't read them recently), I suggest you do that now in order to get a good grasp on the evolution of this design.

Part 1
http://zachelko-gamedev.blogspot.com/2008/07/designing-hockey-power-play-system.html

Part 2
http://zachelko-gamedev.blogspot.com/2008/07/designing-hockey-power-play-system-part.html

To summarize though, my initial thoughts were to design some sort of power-play "system" which would encapsulate all of the tricky details of managing complex penalty situations. At first thought, this seems logical. In software engineering we commonly encapsulate complex things into easy to use interfaces. However, something about this particular problem just wasn't meshing with this approach. You see, the most complicated part of a power-play situation (or set of power-play situations) isn't managing the players who commit the penalties (taking them off the ice, the length of the penalty, placing them back on the ice, etc...). Instead, the complex part is informing the user of the situation via the HUD (heads up display). The behind the scenes work is simple because you simply set a timer for each player who commits a penalty, draw him in the penalty box for that duration, and when it expires you place him back on the ice. With the HUD, you have to verbalize to the user the exact situation that is currently in effect (5 on 4, 5 on 3, 4 on 4, or 4 on 3), and the duration that situation will last. To do this requires knowledge of all other currently running penalties. When you start to think of all of the permutations, you'll get a headache.

So, how did I alter the design to negate these issues? Simple: I solved the problem procedurally. Instead of using an object-oriented "system" approach to nicely encapsulate away all of the nastiness, I simply broke the problem set down into very simple functions. It took some detailed doodling on paper to get things right, but if you can't make an algorithm work on paper, you'll never get it working in code.

Here is the algorithm I came up with:

  1. Maintain a list of times that represent penalties that are currently being served. Tick each of the times in the list once every second (elapse time)
  2. When a penalty occurs, remove this player from the ice and add his time to the list of penalty minutes.
  3. Count the players on the ice for each team (should be a simple call to a size() function on the container they are held in for each team)
  4. Set the situation timer (5 on 4, 5 on 3, etc...) equal to the smallest remaining time in the penalty times list. We use this time because as soon as a penalty expires, the situation will change, so we choose the time that expires soonest.
  5. When a penalty expires, place the player back on the ice and repeat the process of counting players and setting the situation timer.
If the situation is 5 on 5, no display needs to be shown. Also, whichever team has the advantage, the situation label will appear under their label on the screen. For example, if the Penguins have a 5 on 4 power-play advantage, under the team label "Penguins" on the screen, the text "5 on 4" would be displayed. If it is an even strength situation (but not full strength), the display can be shown in the middle of the 2 labels. This all depends on your interface and isn't really important as far as the algorithm is concerned, but it does have to be accounted for.

The problem seems so much simpler once it is broken down into 3 or 4 very basic functions. At first I felt it odd and maybe even "hacky" to count the players in this fashion in order to display the situation, but then I realized that the serving of the penalties and the HUD are two totally different issues, so trying to put them into one solution was pointless and just led to more problems. I also believe this solution is very fast and light-weight. Consider the fact that you are adding the penalty times to a container of some sort. If you always insert them at the back, and tick each one every second, you can guarantee that the penalty which will expire soonest will always be in the first position. No searching, no sorting. Just grab the first element and you can set the situation timer. And as I mentioned before, chances are the players on each team are in some sort of container themselves, so "counting" the number of players simply means calling a size() function on that container which should be as fast of an operation as possible being that it is a standard library function (not to mention there are < 20 players on a hockey team... =p ).

Hopefully this has been helpful to someone out there. I'm putting the finishing touches on the code, so I'll post some screenshots of the demo in action once I complete it.

Friday, March 21, 2008

Team Game Project - Update

We had our first meeting today, it went really well. I met the girl from the music department for the first time today, she's really into the software side of the game, so that's a huge plus. At the meeting I basically gave them the run-down of my idea for the checkers game that I've mentioned in a previous post. It was more or less an absorption session for them to sort of get on the same page with me. I was/am open to another game idea, but they seemed to like it.

We seem to have agreed on using C++ and SDL, so I'm happy about that. I've got a pretty substantial project already completed using these technologies, so that should save us some time right off the bat.

They asked me to put together a design doc for the game, and I've now done that. I may attach it to the end of this post if I remember... As I was outlining the gameplay features I'd like to have in the game, it was amazing how quickly things branched into other things. It really sparks the creative process. I imagine that increasing when the other members of the team get into it and they'll form their own ideas as well, should be exciting.

The goal is to meet up again sometime soon and essentially play checkers offline and incorporate some of the gameplay tweaks. This will allow us to see what will work, what won't, and what needs to be adjusted. It should also give us some other ideas too. I can't wait for this stage, should be really fun. After that, the design document should be close to finalized and then we can start breaking the project down into tasks and assign people to them.

Sometime concurrently to all of this we'll be getting some server software setup to house some version control, simple website, maybe even spring up a blog just for the project, etc...

All in all the meeting was a total success. We were all able to communicate freely, everyone got along, and things just flowed. Very good signs. I'll keep you updated.

Friday, March 14, 2008

Team Project Update

Sorry about the delay on this, by the way. The original meeting never took place, scheduling issues I suppose on part of the other programmer. I sort of anticipated that, but it's a busy time of the year, so no hard feelings. In the mean time I've been thinking about various game design ideas and some of the basic utility classes that any game may need, and how I may implement them.

I had planned on coding the game in C++ because, well, it rocks, I love it, and C++ sits atop the Kingdom of Game Programming throne and shuns non-believers with it's 7ft scepter. The other programmer seemed fine with this, but now he's suggesting we use Java with some 2D graphics lib he's found online. Meh. I checked it out, seems alright I guess, but it is Java and that's usually a deal breaker for me. It does however offer us the ability of fast iteration of ideas and whatnot, so I'm willing to do it. I'm really not too stubborn on this stuff, but if I can use either C++ or Java, I'm almost always choosing C++, but I don't want to even get into that...

He didn't seem to have any details on how "involved" the girl from the Music department wanted to be, so we'll see how that unravels. Along that note (get it, note?) though I have thought more about my idea of a music-driven gameplay element.

The basic abstract concept is to have a simple 2D world which is very stage oriented such that you only see the current area until you complete all tasks or whatever it may be. The visuals would be very vivid. The vision I have for one stage is that of a very drab and dramatic village which is actually more like a small neighborhood. The view is behind the little character and it's viewing 3 or 4 huts. The huts would be very dark colored with really intense colors and the sky would share that sentiment. Just picture a sky before a really terrible storm. The music would coincide with this of course. The gameplay concept I've got in mind is that the music in each stage (coupled with the look of the scene) would lead the player to perform their tasks. Changes in tone, speed, etc... should be evident enough as the player moves or does something that ideally it would be apparent what they need to do. I've tossed around the idea of the character needing to save the inhabitants of these small villages, whether they be creatures or plants, or something. It would incorporate some sort of time incentive which would be pushed by the music, so as you were running out of time the music would get more dramatic sort of like in a movie. An image that comes to mind is as the clouds roll in for a storm more and more of an area is covered in shadow. I think something like that could work well with my idea.

Game design is a process, so I'll just have to keep working it out, but I welcome any comments. Oh, and sorry if I just described someones favorite game that they've played for 30 years, I don't exactly "get out much". Oh, and, don't steal my idea =p

Monday, March 3, 2008

How sweet the sound...

I recently contacted a friend of mine here at school to get together and work on some games. He told me he'd definitely be interested, and not only that but he knew of a girl in the music department (student) that would probably love to get involved. Turns out, he was right. I must say, I'm really excited about the notion of sitting down with someone that isn't a programmer but still wants to be involved in the process by contributing their art form to the overall "product". This will definitely be my first experience of that sort.

I think what intrigues me most is the fact that sound is often ignored/overlooked in games, and I'm as guilty of that as anyone. The only game music that comes to mind that wasn't immediately replaced by my mp3 collection is Doom / Quake III Arena. Granted, I don't play a large variety of games, but the music in the ones I have played annoyed the hell out of me. It may seem weird to see a game developer (aspiring nonetheless) that doesn't play a large variety of games. Well, I guess you'd be right, it is. However, I've played games like Zelda and Sonic since I was just a tiny lad. Not to mention the fact that I learned my multiplication tables of 7 from Tecmo Super Bowl for the NES (great music, by the way) and Joe Montana's Football for the Sega Game Gear. More recently though, for the past 5 years I've been a competitive gamer on the Madden tournament circuit. I tend to stick to one group of things that I like in all aspects of life, not just games. I'm sort of backwards in the sense though that my love of programming has inspired me to play as many different games as possible. Most people are the opposite. They love games, they love computers, let's program games! I digress...

The part that really excites me about this is that I love music. I always have my music playing, and I honestly can't function without it. I'm huge into playing guitar as well. I'm really interested to see if/how she will propose a game idea based on something she wants to do with music. I think that would be so cool if she had an idea for something she wanted to do with music that would be instrumental (no pun intended) to the game itself, aside from just serving as a supplement. Of course, she may not have that idea, but now I have it, and anyone reading this does as well, and I'm sure someone else has already made a game like that, so go nuts!

I'll keep you posted and let you know how the first meeting goes on Thursday and hopefully I'll have a constant supply of updates related to the game we make.