Skip to content

thebuzzwright

Your source for code!

For you classic multiplyer fans...

I have recently been making a game with a friend over the Internet called “Galaga Quest” but as part of our development process we both make test projects that will en-corporate techniques we will use in the game.

One of the test projects I made was “Space War”, a small easy to play two-player shooting game where both players compete against each other and collect upgrades as they go.

In game screenshot

Some infomation from the readme.txt:

About

“Space Shooter” is a game that was made as a test project to help the development progress of another game.

In this game “Two Players” will battle to the death in this 2D space shooting game. There are upgrades each player can collect to boost their ships stats.

The objective is to destroy/annihilate/pwn your rival’s ship with great skill and testosterone fuelled logic.

Beware of falling bombs, they can cause some damage!!!

Specifications

  • OS – Windows XP and above (with Microsoft .Net 2)*
  • Monitor – Supports 1440*900 or equivalent resolution
  • DirectX 9
  • 2 GHz minimum CPU (or less depending on the CPU)

 

How to play

Controls player1/player2:

  • W/Up – Move Up
  • S/Down -  Move Down
  • A/Left – Move Left
  • D/Right – Move Right
  • Space/Enter – Shoot
  • Escape – Quit

How to change Screen Resolution

In the folder where “SpaceWars.exe” is there is a text file called “config.txt” which can be opened in notepad/WordPad and other word processing applications.

Line 1 in the file is the screen width in pixels for example “800”.
Line 2 in the file is the screen height in pixels for example “600”.

Line1 and Line2 together would make a screen resolution of “800 * 600”.

By default the screen resolution is “1024*1024” so you can change the “config.txt” file to suit your optimum resolution.

Note: If the text file is not present when the game is run the game will make a new config.txt with default screen resolution.

“Needs XNA 2 to work”

Download

GD Star Rating
loading...
GD Star Rating
loading...

Turtle VS Rabbit ?

To me optimizing code to make it run faster or look cleaner is one of my favourite parts of software engineering. It can be challenging and in many cases can hit two birds in one stone (make a solution for more than one thing).

This article covers some tips and tricks that you could use to optimize c# code!

faster

Tip 1#

Replace divisions of multiples of two:

Division is processor intensive, its performance hit increases the more you use them. If your planning on division for general apps then you could be ok with the normal “/” operator, if you are programming a game this tip could help reduce its performance impact.

Not optimized -

int numerator = 8;

int denominator = 2;

int total = numerator / denominator;

Optimized-

int numerator = 8;

int total = numerator >> 1;

For every power of two just increment the bite-wise shift value for example : 8/2 = 8>>1 and 8/4 = 8>>2.

For non power of two devisions you need to generate a formula instead of simply shifting the value :

Previous algorithm:

int numerator = 27;

int shift = 3;

int total = numerator >> shift;

Console.WriteLine(total);

Console.ReadKey();

The problem with the above algorithm is that the bytes are just shifted three bits to the right, which actually equates to 3.
To bypass this problem you have to think a bit about what your doing, my corrected approach was this:

int denominator = 3;

int numerator = 27;

int shift = 3;

int perDevision = (numerator * denominator) >> shift;

perDevision -= 1;

This now equates to 9 which is the correct answer, fiddling about with these type of divisions shouldn’t get too complicated but you need to experiment with the result to bypass the “/” operator which is why this tip is for multiples of two as it always works.

Tip 2#

Replace the “==” operation:

The equals operator is nearly the same as “.equals()” function, difference being slight optimizations with the function due to the way classes are processed by the compiler. This tip is to improve code readability.

Not optimized-

int a = 10;

int b = 20;

if (a == b) { /*code*/}

Optimized-

int a = 10;

int b = 20;

if (a.Equals(b)) { /*code*/}

Using the “Equals()” function is more readable and just a bit faster than its predecessor.

For string comparisons do not use either, instead use the following:

string a = “C#”;

string b = “C++”;

if (string.Compare(a, b, false).equals(0)) { /*code*/}

Notice the third parameter (bool), if set to true it will ignore upper/lower casing ie G and g will return true, if the parameter is false it will check casing ie G and g thus returning false.

Tip 3#

Replace value type classes (no functionality) with structures.

Lets say you have a class that doesnt need to be inherited and is really just a conveniant place-holder for some data:

class Product

{

string _Name;

int _Quantity;

decimal _Price;

public string Name

{

get { return _Name; }

set { _Name = value; }

}

public int Quantity

{

get { return _Quantity; }

set { _Quantity = value; }

}

public decimal Price

{

get { return _Price; }

set { _Price = value; }

}

}

Simple class that allows other classes to get/set value type data, because their is no real functionality or reference types we should move this to a struct instead.

public struct Product

{

string _Name;

int _Quantity;

decimal _Price;

public string Name

{

get { return _Name; }

set { _Name = value; }

}

public int Quantity

{

get { return _Quantity; }

set { _Quantity = value; }

}

public decimal Price

{

get { return _Price; }

set { _Price = value; }

}

}

All we do is simply change the word “class” to “struct”, a struct is a value type (derived from System.ValueType) which means when any value type is created it is allocated a single memory slot in the main memory, unlike “reference” types such as classes that when created are allocated a memory space as an object and instead of being directly accessed it is pointed by its reference number (slower) however because of this pointing we can create relationships between the classes and thus we can inherit other classes and other OOP stuff. Structs are Log(N) times faster than classes for you computer science readers.

Tip 4#

Understand String-builder vs String.Concatenate

When you assign a string value type a value it performs a processor intensive (compared to many other basic stuff) operation called boxing, what this means is that to overwrite the string value it creates a new string with the new value as an object and has to convert the object in memory into the data-type (string) to replace it, basically creating an extra string value in memory before boxing it back to the value type. If you use the “+=” or “=” operator it will do that automaticly and you cannot prevent it as its how objects can be converted into value types.

For large string operations (more than 40 boxing/un-boxing) use the “StringBuilder” class (from System.Text name space) to handle its assignments. The StringBuilder object allows the assigment to string value types to be added directly to the string without boxing/un-boxing which increases performance.

StringBuilder myString = new StringBuilder();

for (int i = 0; i < 1000; i++)

{

myString.Append(“*-”);

}

Console.WriteLine(myString.ToString());

Tip 5#

Use For loops over For each unless you don’t give a dam about performance.

Its a benchmarked fact that using a “For loop” over a “For each loop” yields two times as fast so stick to it unless your code needs to be slightly more readable!

Tip 6#

Use Generic Collections over Object based structures.

Generics allow you to store data types of a generic type as long as you declare what that type is and it has a method of supporting it.
They also prevent boxing/unboxing as they are value types!

Example:

ArrayList referenceList = new ArrayList();

referenceList.Add(2);

referenceList.Add(“wtf”);

Not only is it reference based but the obvious problem is that the Array List allows mixed data types, that’s allot of boxing/unboxing and that’s without the worry of search/sorting !

To overcome this use a generic collection from the “System.Collections.Generic” such as “List<T>”:

List<int> valueList = new List<int>();

valueList.Add(2);

valueList.Add(8);

This forces us to use a certain datatype (covers the sorting/searching) and as its value type prevents boxing/unboxing performace problems.

If you have a rough idea of how mant items the List can store you can provide it an integer value in its “Capacity” property which will increase performance by over 50%. This is because by default a List.Capacity property is 4 which means when you store more than 4 values it has to re-size in memory to become suffeciant creating performance drop, set the value of how many items you may store before using it.

valueList.Capacity = 100;

Done!

Tip 7#

Handle error catch/throws better!

Yes that exclamation mark at the end of that heading is there for a reason, too many people would rather catch exceptions and ignore them than rather find ways of preventing it  in the first place.

Performance drop from “Try catch” commands is around the 300% > mark so just use validation routines instead if you can.
Many people see “Try catch” as a hack so stop being a noob.

Tip 8#

Don’t use temporary variables…

When declaring a variable you are declaring it for a reason, to store data , by declaring a temp variable you are creating a value object that needs to be boxed/unboxed repeatedly, thus you just created a performance hog!

Getting around this isnt always easy but bypassing creating a new variable that will hog you down is.

Instead of :

int a = 4;

int b = 8;

int temp = a;

a = b;//a = 8

b = temp;//b = 4

Use XOR operation instead:

int a = 4;

int b = 8;

a ^= b;

b ^= a;//b = 4

a ^= b;//a = 8

XOR is much faster than assigning value to value and there is no need to create a temp variable so problem solved.

That covers this article, hopefully it has explained some good optimizations you can implement in your programming.

GD Star Rating
loading...
GD Star Rating
loading...

In a previous brief article here I introduced a powerful “object oriented” feature in C# called “Inheritance”, simply put a “Super Class” or a more appropriate word “Base Class” can have its members used in another class (a derived class).

This tutorial will cover a better view on inheritance and how it can make develeping a program much more extensive!

Firstly make a new Console application called “InheritingProducts” and make a new class called “IProduct”.

1 using System;

2

3 namespace InheritingProducts

4 {

5 class IProduct

6 {

7 }

8 }

Now add the keyword “abstract” before “class”:

1 using System;

2

3 namespace InheritingProducts

4 {

5 abstract class IProduct

6 {

7 }

8 }

The keyword “abstract” means that this class can not be   instantiated as an object i.e.

12 IProduct product = new IProduct();

This will throw a CS0144 error that states this class cannot be instantiated , instead an abstract class allows us to only “derive” from it, in other words this class is like a template for other classes to use.

Ammend the “IProduct” class to look like this:

5 abstract class IProduct

6 {

7 private string _Name;

8 private decimal _Cost;

9

10 public decimal Cost

11 {

12 get { return _Cost; }

13 set { _Cost = value; }

14 }

15

16 public string Name

17 {

18 get { return _Name; }

19 }

20

21 public IProduct()

22 {

23 _Name = GetType().Name;

24 _Cost = 0.0m;

25 }

26

27

28 }

Now other classes can inherit members from this class, when this happens we say “The derived class is a” IProduct.

Before we start deriving classes have a look at this:

flowchart

Because each derived class (“Computer”,Guitar” and “Bike”) have the members from “IProduct”, they are an instance of “IProduct”, IProduct being the “base” or “super” class.

When their is a group of similar object types such as a “Product”, inheritance/generalization should be used.

Add a new class called “Computer”:

6 namespace InheritingProducts

7 {

8 class Computer

9 {

10 }

11 }

Now add the following next to “Computer”

“:IProduct” – without quotes:

8 class Computer:IProduct

The “:Classname” means to inherit the class, what ever the class name is ; in this case “IProduct”.

Add a constructor to this class:

8 class Computer:IProduct

9 {

10 public Computer()

11 {

12 this.Cost = 499.99m;

13 }

14 }

You haven’t declared the variable “Cost” but no error is provided… This is because you have actually declared it, in the “IProduct” class which is now part of this class!

Go to “Program.cs” and implement an object of “Computer”:

5 class Program

6 {

7 static void Main()

8 {

9 Computer product = new Computer();

10

11 Console.WriteLine(“Product Name {0}”, product.Name);

12 Console.WriteLine(“Product Cost {0:c}”, product.Cost);

13 Console.ReadKey();

14 }

15 }

Debug the program and you should see the following:

output

We have successfully inherited, derived and implemented an inherited concept!

If we take a look at “Program.cs” source you will see two “Console.WriteLine()” methods being used to display details from this class, as a keen developer you should know that abstracting code is valuable and that this can be ridden of, make a new class called “ProductFunctionality” and add the following code to it:

8 static class ProductFunctionality

9 {

10 static private IProduct _Product;

11

12 static public void Display(IProduct product)

13 {

14

15 if (product != null)

16 {

17 _Product = product;

18

19 Console.WriteLine(“Product Name {0}”, product.Name);

20 Console.WriteLine(“Product Cost {0:c}”, product.Cost);

21 }

22 }

23 }

This class acts as an operator of every derived class from “IProduct”, what this means is that we will use this class to access methods in relation to a product for example, the “Display()” method will display the products details. The class has been made static as I felt there was no need to make an initalization for this class as its part of this programs engine.

Ammend “Program.cs” to this:

7 static void Main()

8 {

9 Computer computer = new Computer();

10 ProductFunctionality.Display(computer);

11 Console.ReadKey();

12 }

Thats one way if you prefer a more readable code (as so far our products dont have much to go on) try this :

7 static void Main()

8 {

9 ProductFunctionality.Display(new Computer());

10 Console.ReadKey();

11 }

The problem with this version is that you cant manipulate the “Computer()” instantiation as its out of  scope within “Display()”.

Add Two other class one called “Guitar” and another called “Bike” and derive from  IProduct (like we did with “Computer.cs”), give them a unique price as well.

ClassDiagram2

Click to enlarge

As you may see, its now very easy to add more implementation of a product !

I hope you enjoyed this tutorial!

GD Star Rating
loading...
GD Star Rating
loading...