Categories
Game Development Geek / Technical

The Best Random Number Generation Explanation Ever

Thanks go to Uhfgood in #gamedevelopers for finding the article Using rand(). I thought I already knew about the problems with using rand(). This article was great at clarifying the actual problems people have with using rand() as well as faults with “good” solutions people use. It also documents a simpler way to use rand() that actually produces better results! It turns out that rand() is better than many programmers thought.

For those of you who don’t know, the classic way people are taught to use rand() to get a random number between 0 and maxRange is as follows:


int picked = rand() % maxRange;

The problem with the above is that the value you get in picked will not be as random as it could be. Something about lower order bits repeating too often. So usually the “better” way to solve the problem is through some slightly more complicated code:


int picked = lowerBound + rand() / ( RAND_MAX / ( maxRange - lowerBound ) + 1 );

The article explains that this example also has problems!

So what do you do? Stop fighting rand()! I wasn’t happy with the example given as I don’t understand why simple variables have to be used with simple examples since they only make it more confusing. The following is my own code:


int highest = 100;
int randDivisor = RAND_MAX / highest;
int pickedValue;
do
{
pickedValue = rand() / randDivisor;
}
while ( pickedValue >= highest );

It may seem like you would waste too many cycles waiting for pickedValue to be within the range you desire, but it really doesn’t take long at all. It is more pseudorandom than the other examples and needs less complex code, too!

The document also explains the problem with the usual code to seed the random number generator:


srand(time(NULL));

The problem seems to come from the fact that changes from one time to another aren’t usually enough to change the first randomly generated number. The article explains a way to use time() in a portable manner by hashing the bytes of its return value.

The entire article is a good read, and I believe any game programmer will find it useful.

Categories
Games Politics/Government

Space Invaders and Politics

I have been looking into Space Invaders and how it was like to play the original. I played Love Invaders, which has an amusing intro (1978 was all just a big misunderstanding), and Invasion 3D, which actually had some interesting game mechanics, such as exploding UFOs that also destroyed nearby aliens and aliens that drop down to replace dead allies in the front lines.

During my research, I also found the Wikipedia entry on Space Invaders, and I learned that when it was first introduced in America, it apparently sparked outrage even that many years ago. I thought that the public rallying against video games was a fairly new phenomenon.

From Wikipedia:

This phenomenon led to the first outcries against video games by groups of concerned adults, who felt that the content of video games was a corrupting influence on children. In the case of Space Invaders, the issue was not usually the highly abstract and stylized violence, but with the fact that the game could not be “won” in any familiar sense. As framed by the critics, the player is powerless to do more than to delay an inevitable defeat. They suggested that the game taught an unwholesome life lesson, inculcated defeatism, and possibly was intended to put the United States at a disadvantage in its economic rivalry with Japan by undermining the competitive spirit of American youth.

Space Invaders taught defeatism? So is Grand Theft Auto sending a better message by actually allowing you to overcome the odds and win?

Categories
Game Development

Space Invaders Clone Progress: Finding My Way

I’ve been reading through the source code of a number of games, and I’ve been picking up some good ideas.

Specifically, I had been struggling with the idea of retrofitting a menu system to a finished game. I hadn’t been focused on the task (as I need a finished game first), but I had a vague idea that I would need to design the menu system and run it separately from the game loop. Interestingly enough, I found that a number of games have the menu system as part of the main loop! I was a bit confused by it at first, but apparently the game is paused for one reason or another, and the menu system has its own update() function that gets called if it is active. It seems fairly easy to implement, and there are plenty of code examples for menu system implementations out there.

I now feel more confident that I can leave the menu system to a later time, allowing me to focus on finishing Space Invaders. I have since added functionality to allow the aliens to move down the screen in formation, and once an alien hits the player’s ship, the alien is destroyed, and the player’s ship becomes invisible.

It becomes invisible because I have yet to actually define what it means for the ship to be destroyed. Technically you can still shoot and move the ship. You just can’t see it. To really destroy it, I will need a way to disable the player’s input, and I will also need a way to restore the ship after a few seconds.

Explosion effects would help, too. B-) Currently, the alien and the ship simply disappear when “destroyed”, although the alien sprite really does disappear for all intents and purposes. I am still making small changes, and being very careful with new ideas I come up with. I write them down and put them away, ready for v2.0’s development. I just want to finish v1.0 as quickly as I can.

At one point, I felt stuck. I didn’t know how to proceed, and I found myself sitting in front of the code without any real reason. I stopped, took out some notecards, and came up with a few scenarios. I basically wanted to determine what should happen in specific situations.

For example, what happens when an alien touches the player’s ship? Well, the alien and the player’s ship both get destroyed.

What happens when the alien gets destroyed? Well, some explosion animation should occur, the alien should be removed from the list of active aliens, and if it was the last alien, then the next level should start.

What happens when the player’s ship gets destroyed? What should happen when the game starts up for the first time? What happens if there is no player ship on the screen? What happens if the player has no ships left? What happens if the alien reaches the ground?

Answering each of these questions helps me to see what functionality is missing. I still need animations for the explosions, I think I may make use of a timer for the player’s ship to get restored, and I still need to add some font to display text such as “Game Over” and “Start Game”.

It is amazing how clear everything becomes when you stop and think, “What will happen in this specific circumstance?”

Categories
Game Development General

XNA Being Ported to Mono

Speaking of XNA, Mono.Xna “is an open-source implementation of Microsoft XNA”.

It is still a baby project, but hopefully it will actually allow developers to create truly cross-platform games. The source to it is available in the Mono subversion repository. Mono, of course, is the open source, UNIX version of the .NET development platform.

Categories
Game Development General

XNA Framework API?

The other day I decided to look through some source code of other games, and I downloaded a breakout clone written using the XNA Framework. It provided the source code, and I figured that C# can’t be that different from Java or C++, so it shouldn’t be a problem. At one point I thought that maybe C# allowed you to use two different names for the same function, such as calling Run() vs defining it as BeginRun(), but then I realized that the code I was trying to find was apparently in the XNA Framework.

I almost gave up looking for the XNA Framework API since it seems to be too difficult to find, which means that the game’s source is almost impossible to follow since I can’t find a way to start running the game. Since I do all of my development on GNU/Linux, and Microsoft isn’t porting their software over anytime soon, I am left with the source code that depends on a missing API to understand. I finally found the API in MSDN, but I had to use Google to do so. Why I couldn’t just search for it with MSDN itself I have no idea. I also wish that the documentation was a bit more useful. For instance, here’s the Game method Run():


public void Run ()

That’s it. I don’t even get to see what it is calling or doing. The comment says “Starts the game”, and I have to find a completely different part of the documentation that tells me that it “starts a loop that will call Update and Draw multiple times a second until Exit is called”. So now I know what it calls and what it does, but why couldn’t the function’s page tell me?

Is it secret code or something? I guess I am just used to seeing the code of implementations, such as C++ standard libraries. I mean, I understand that I shouldn’t have to know what the implementation is doing in order to use it, but since it seems so hard to get good documentation on what the API is and how to use it, what else could I do but go to the source?

Maybe it is because I don’t have Game Studio Express or any of the Microsoft XNA-related pieces of software. I believe there are tutorials provided, and I found a few videos that seem to explain how the content-pipeline works, so it is obviously documented somewhere. Maybe search terms like “xna framework api” aren’t the ones to use?

Well, anyway, after a few hours of research, I finally found the info that I needed. Now I can look at the breakout clone’s source code and figure out how it works. At least until I hit another mysterious XNA Framework API call, that is.

By the way, I kept hearing about how great the XNA Content Pipeline is, and I concluded that it simply integrates graphics asset collection into the same program you use to edit code. It’s nice, but I was expecting more from all the noise getting generated about it. Is there something more to it that I didn’t find in my admittedly quick research?

Categories
Game Development

Space Invaders Clone Progress

I woke up late, which pretty much set the tone for the rest of the day. I didn’t spend nearly as much time working on the Space Invaders clone as I would have liked. Still, it was progress.

I ran into two bugs, one for each small update I made. The first bug appeared when I tried to replace one alien with multiple aliens. I basically swapped out a single pointer for a vector of pointers. I actually liked how easy it was to get the aliens to move back and forth since I didn’t even have to change the variable I used.

Unfortunately, my program would seg fault whenever the last alien was shot. It turned out that I was using a for loop when handling collisions, which incremented the iterator each time through. Well, if I erased the object the iterator references, then the new value of the iterator is one after that object. If it happens to equal vector::end(), then the loop should end.

Except that the iterator gets incremented, so now not only does it not equal vector::end(), it doesn’t refer to anything valid! I switched to using a while loop, and I only increment if I am not erasing, and it fixed the problem.

The second bug was simpler but more subtle. Yesterday I decided to add rows of aliens as well as columns. I found that if you shoot the rightmost or leftmost column of aliens, the rest of the aliens would sometimes move all the way over to the right or left, just like they should. The problem was that it didn’t happen consistently. Sometimes they would move that far, while other times they acted like the column of aliens I just shot still existed. What was going on?

After adding debugging statements and checking the position of the aliens, I found out what was happening. The code was actually working correctly. The problem was that I had an extra row of aliens that were too high to be seen on the screen. Doh! Once I moved the aliens down, I could see that they were moving as far left and as far right as they could as a unit.

I want people to pick up this game and think that it is as finished as any regular game they played. I know I will need a menu and an interface to continue or select levels, but I want to see what else I will need. I am basically looking through source code from various games, and I will document my adventures reading through source in a later post.

Categories
Game Development Personal Development

Thousander Club Update: December 18th

For this week’s Thousander Club update:

Game Hours: 241.25 / 1000
Game Ideas: 616 / 1000

Target: 987

Only two more weeks!

So I found that I could still come up with 100 ideas, which was surprisingly difficult and easy, depending on the hour. I managed to get multiple aliens to move about, which involved replacing the single alien sprite with a vector of alien sprites. It was a bit tricky, but it was due to my lack of experience with erasing members from a vector.

To handle the movement of the aliens, I have a section of code that looks like:


static int step = 1;
...
if (alien->X() > 970 || alien->X() < 74)
{
step *= -1;
}

Basically, if the alien goes too far to either side, it reverses direction. I thought I would need to replace this variable with an array of variables, but it worked surprisingly well. The aliens all reverse direction together when the far left or far right aliens exit the range.

I am thinking that the alien sprite is too large, however. There are only eight aliens across right now, and they move back and forth too quickly. If I add code to allow them to move down after hitting the sides, the player would have almost no time to fight back. I should also find a way to slow them down in general.

The good news is that I am taking the rest of the year off at my day job, which means that I have this week to work on my own game development. Next week I will be celebrating Christmas and getting last minute shopping/gift wrapping/etc done. I will break down my week into certain tasks I would like to accomplish, and I will try to give progress reports each day.

Categories
Games General

Game Tunnel’s 2006 Game of the Year Awards

Did it sneak up on you? It snuck up on me! Game Tunnel’s 2006 Game of the Year awards calendar is up, and two categories have already been published!

The awards have already been distributed for the Best Sports Game and the Best RPG of 2006, and I don’t think who won was a big surprise.

In the coming month, you will see awards for Casual Game, Strategy Game. Sim Game, Action Game, and Quest/Adventure/Platform of the year. There are also dates to recognize outstanding games in Innovation, Multiplayer, and “Special Awards”.

And, of course, the month ends with a listing of the top 10 games of the year, including the winner of 2006’s Game of the Year. There is still time to vote for your favorite game, so do your duty!

Categories
Game Development Personal Development

Thousander Club Update: December 11th

For this week’s Thousander Club update:

Game Hours: 238.25 / 1000
Game Ideas: 507 / 1000

Target: 966

I managed to add the ability to shoot a weapon in my Space Invaders clone. As of now, if the bullet collides with the enemy sprite at the top of the screen, the enemy disappears.

Space Invaders clone

Yes, that orange thing at the bottom is the player’s ship. Hey, it works.

I am giving myself permission to stop every so often and plan my next move. Getting this far was actually simple since I had a fairly good idea what I needed to do. My next moves are not as clear. I think I will work on abstracting the interface. Right now, I have code that looks like “If Space is pressed, then make the bullet move up”. Everything is hard-coded, and I think at the very least the aliens can be made into a more abstract entity. In fact, I should be able to take my one alien and give it some friends. Otherwise, it would be a very boring game.

Also, I am not happy with the speed. It runs very fast, and I think I can experiment some more with the delta code I am using.

I don’t want to try to abstract things too much. I have already been down the road of abstracting too much, which resulted in not getting anything concrete accomplished. I don’t want my code to be completely hard-coded, either. If I keep doing small changes, though, I should be able to mold the project the way I see fit.

Categories
Game Design Game Development

Interesting Game Ideas: The Old Gym

Game Idea:
The Old Gym

Premise
Repair and improve your old high school’s gym on a limited budget.

Huh?
I honestly can’t remember where I thought this idea up, but my old high school recently merged with another one. I was probably thinking about the future, when I would be so wealthy that I could spare quite a bit of it to give back to those things that contributed the most to me. During the last few years, $1 million was raised to replace the gym floor, and I think I remember that there was a problem that required repairs soon afterwards. In grade school, there was also a gym that had sections that were warping, and I don’t know if they have been repaired yet. Maybe it was when I was there fairly recently that I thought about repairing it myself?

Possible Game Here?
Imagine that you had $1 million to repair a school gym, and you have only one summer to work on it. What would you do with the money? Who would you hire to work on it? What kind of features would you want? What materials would you use for the floor, seats, windows, and walls? What kind of sports can you play in it? How much space will you need? Will you need to buy more land for the school to accomodate the luxury locker rooms you plan to install?

I think that you can picture some kind of Tycoon game. You can’t earn revenue from the gym. After all, it is a donation of your money and time. Of course, maybe the initial $1 million might increase based on parents and alumni feeling generous after seeing such great progress? I think the primary goal is to leave your legacy, so your reputation is at stake.

Each day, you would need to monitor the progress of the gym. If you run out of money before completion, the children will have a partially finished gym, and you’ll have a lot of upset people. Your name will always be associated with failure. Similarly, if you run out of time, school will get back in session, and you’ll have to contend with students getting in the way or playing pranks on your workers.

Will you have hardwood, concrete, or tile floors? How many basketball nets will you have? Will the floor slide away to reveal an ice hockey rink underneath? Will you also install astroturf? How about the real stuff? A swimming pool on the roof? Will you put in bleachers, or will fans have to sit in lawn chairs? Will you use state-of-the-art scoreboards and announcer systems, or will scores need to be updated by hand and read through a megaphone?

Will you build quality into the project from the beginning, or will you cut corners? What if you get caught? What if someone gets hurt? What if no one notices?

Perhaps there is a weekly meeting with the school’s board of directors. It can serve as a status report, but you can also use it as an opportunity to request more funding. If you’re charismatic enough, you can get various parts of the overall budget switched to the gym. “Sorry, kids, no band this year.” Will it be easier to request more money if everything is going well? If you do well, does the game end, or can you continue to oversee the gym over the next few years? Will you be asked to tackle tougher assignments? Your city may be tasked with hosting the summer Olympics, and you may be just the person for the job!

Summary:
Rebuilding your high school’s gym may not sound like much fun in real life, but if you had a large budget and a summer, what would you do? It would be interesting to see what people would put into their school gyms.