Sexy Code
962
5
Advertisement
I absolutely love the way C# is progressing as a language. Whenever I get the chance to use some of the cooler features in a real life project, I can't help but feel proud and happy. Maybe it's just me. Does anybody else feel the same way?
During work on Asteroids, I came across the need for two age-old game data types: triggers and interpolators. While they are fairly mundane and boring in C++, they can be quite interesting when used together with a few high level language features. The following real-world example demonstrates the use of events, delegates, anonymous delegates, and lambdas, all at once.
I'm quite happy with how easily that situation was expressed using these two data structures. The current implementations for the trigger and interpolator classes can be found in the SlimDX repository, under the Asteroids game. I'm thinking of cleaning them up and adding them to the Sample Framework. Good idea or bad idea?
During work on Asteroids, I came across the need for two age-old game data types: triggers and interpolators. While they are fairly mundane and boring in C++, they can be quite interesting when used together with a few high level language features. The following real-world example demonstrates the use of events, delegates, anonymous delegates, and lambdas, all at once.
// check to see if all the asteroids are goneif (Asteroid.AsteroidCount == 0 && levelText == null){ // set the level text currentLevel++; levelText = "LEVEL " + currentLevel.ToString(CultureInfo.CurrentCulture); // rig up a trigger to start the new level Trigger trigger = new Trigger(LevelInterval); trigger.Activated += delegate { // start the new level when the alpha of the text reaches 0 levelTextInterpolator = new Interpolator(a => (a - 0.01f), 1.0f, a => (a <= 0.0f)); levelTextInterpolator.Finished += NewLevel; interpolators.Add(levelTextInterpolator); }; Triggers.Add(trigger);}void NewLevel(object sender, EventArgs e){ // clear out the level text for now levelText = null; // spawn some asteroids for the player to deal with for (int i = 0; i < currentLevel; i++) Entities.Add(new Asteroid(this, AsteroidSize.Huge));}I'm quite happy with how easily that situation was expressed using these two data structures. The current implementations for the trigger and interpolator classes can be found in the SlimDX repository, under the Asteroids game. I'm thinking of cleaning them up and adding them to the Sample Framework. Good idea or bad idea?
Advertisement
Advertisement
Advertisement
Discussion