Beginning CSharp Game Programming (2005) [eng]
.pdf
290 Appendix A Answers to Review Questions
2.13. When this code is completed, what is the value of x? int x = 0;
while( x < 10 ) x++;
x is 10 after this code completes.
2.14. For each loop, does the value of x increase before FunctionA executes, or after? for( int x = 0; x < 10; x++ )
{
FunctionA();
}
The value of x executes after the function is called. The third part of a for loop is always executed after the actual code.
2.15. Rewrite the code in question 2.14 using a while loop instead.
Your answer should look somewhat like this:
int x = 0; while( x < 10 )
{
FunctionA();
x++;
}
2.16. How many times is FunctionA executed? int x = 0;
do
{
FunctionA(); } while( x == 1 );
FunctionA is executed exactly once, because the loop executes the code before it checks the condition (x == 1). Once the condition is checked, the loop sees that the condition is false, and exits.
2.17. What is the value of x after this code is done? int x = 0;
for( int y = 0; y < 10; y += 2 )
{
if( y == 4 ) break;
x++;
}
Chapter 3: A Brief Introduction to Classes |
291 |
The value of x is 2 because the loop exits after two iterations.
2.18. What is the value of x after this code is done? int x = 0;
for( int y = 0; y < 10; y += 2 )
{
if( y == 4 ) continue;
x++;
}
The value of x is 4. When y is 4, the loop skips back to the beginning without incrementing x.
2.19. Is this code valid? (Assume FunctionA exists.) for( int y = 0; y < 10; y++ )
{
FunctionA();
}
y = 0;
No, this code is not valid. The variable y is only in scope inside of the for loop, not outside of it.
Chapter 3: A Brief Introduction to Classes
3.1. Are basic types created as values or as references?
Basic types (int, float, char, etc.) are always created as values. Creating them as references takes too much overhead and would make your programs much slower.
3.2. Are classes created as values or references?
Classes are always created as references.
3.3. Are structures created as values or references?
Structures are always created as values; this allows you to create efficient programs when you don’t want to deal with the memory allocation issues of using references.
3.4. What is the value of x after this code is executed?
int x = 10; int y = x; y = 20;
The value of x is 10 because there are no references involved here. The variable y exists completely independent of x in memory.
292 Appendix A Answers to Review Questions
3.5. Is the data in x and y the same after this code is executed? (Assume class Foo exists and has a function named change which changes data.)
Foo x = new Foo(); Foo y = new Foo(); y = x;
y.change();
Yes. After the code y = x; is executed, both y and x point to the very same object (the original y is discarded).
3.6. Where does the old data of y go when you execute this line of code?
Foo x = new Foo(); Foo y = new Foo(); y = x;
The old data of y is kept around in memory for an undetermined amount of time. When the garbage collector notices that nothing points to the old y any more, it frees up the memory for something else.
3.7. What parts of this function definition are “the signature?” int function1( int x, int y )
The name and the two parameters.
3.8. Can a class have these two functions at the same time? int function1( int x, int y )
float function1( int x, int y )
No, it cannot. These functions have the same signatures and only differ by return type, and the compiler cannot tell what function to use based on the return type.
3.9. Why is it a good idea to create constructors?
Constructors allow you to automatically set values of a class object, so that you can make sure no objects with invalid data exist.
3.10. Are destructors really needed in C#? Why or why not?
Generally, destructors aren’t needed. The garbage collector does most of the work that destructors were needed for in older languages.
3.11. When a class contains data, it is called a has-a relationship—a class has a float, and so on. When a class inherits from another class, what is the relationship called?
The is-a relationship. When class A inherits from class B, A is-a B.
Chapter 3: A Brief Introduction to Classes |
293 |
3.12. What is the primary reason for using inheritance?
The primary reason for inheritance is code-reuse—inheritance allows you to use the same code in many different classes without having to rewrite it all.
3.13. Why would you want to hide your data?
Hiding your data protects it. When you hide data, you make sure it can only be accessed in ways that you control.
3.14. What can access x from the following class?
class foo { public int x;
}
Everything can access x.
3.15. What can access x from the following class?
class foo { protected int x;
}
The only things that can access x is the class foo and classes that inherit from foo.
3.16. What can access x from the following class?
class foo { private int x;
}
The only thing that can access x is the class foo.
3.17. When you don’t specify an access level (protected, private, or public), what is the default level?
The default protection level is private.
3.18. Why are accessors and properties a good thing?
Accessors and properties allow you to control access to your variables without allowing the whole world to mess with your data in ways that you don’t like.
3.19. How do enumerations make your code cleaner?
Enumerations allow your code to look cleaner by replacing numeric values with labels that make your code more readable. See Question 2.6 for a similar problem.
294 Appendix A Answers to Review Questions
Chapter 4: Advanced C#
4.1. Are namespaces a vital part of modern computer programming?
Yes. Modern programs are huge, and contain dozens of libraries, some of which may contain classes that have identical names. Namespaces allow you to specify extra levels of organization.
4.2. What can you do to make accessing namespaces like Microsoft.DirectX.Direct3D easier?
You can use the using keyword:
using D3D = Microsoft.DirectX.Direct3D;
And then you can use D3D as an alias for Microsoft.DirectX.Direct3D.
4.3. Polymorphism literally means what?
Polymorphism means “Many forms.”
4.4. How does polymorphism make your programs more flexible?
Polymorphism allows you to use different classes with the same code, if the classes all have the same capabilities. You can have a function that works on Spaceships, and it will work on any spaceship that you define from now until eternity.
Questions 4.5 through 4.8 use the following code for reference: abstract class Spaceship
{
abstract public void MissileHit();
};
class CargoShip : Spaceship
{
override public void MissileHit()
{
// some code here
}
};
class CombatShip : Spaceship
{
public void MissileHit()
{
// some code here
}
};
Chapter 4: Advanced C# |
295 |
4.5. Can you create instances of Spaceship?
No, it is an abstract class and cannot be created.
4.6. Will the CombatShip class compile? Why or why not?
No it will not compile. The MissileHit function needs to be declared as virtual. Otherwise, the compiler thinks that you have not implemented Spaceship.MissileHit (because you actually haven’t!).
4.7. Is this code legal?
Spaceship s = new CargoShip();
Yes it is. Because of polymorphism, you can store CargoShips inside of a SpaceShip reference.
4.8. Is this code legal?
CargoShip s = new CombatShip();
No it is not, because a CombatShip is not a CargoShip, even though they share a common base.
4.9. How would you declare a 4-index integer array containing all 5s?
int[] array = new int[4] { 5, 5, 5, 5 };
Or alternatively:
int[] array = new int[] { 5, 5, 5, 5 };
4.10. What’s the easiest way to create a 5×5 2D array?
int[,] array = new int[5,5];
4.11. Why would you ever use the array-of-arrays method to create multidimensional arrays?
You would use this method if you ever needed to create a multi-dimensional array wherein each index in each dimension isn’t neccessarily the same size.
4.12. When you create an array designed to hold 10 Spaceships, all 10 ships are automatically created for you (assume Spaceship is a class, not a struct). (True/False)
False. The array will hold null references to spaceships, which you need to fill in yourself.
4.13. Is this code legal? If not, why? int[] array = new int[5];
foreach( int i in array )
{
i = 20;
}
No it is not. You cannot modify the physical contents of an array in a foreach loop.
296 Appendix A Answers to Review Questions
4.14. Which lines of the following code are illegal?
1.string str = “HELLO”;
2.char c = str[0];
3.str[1] = ‘e’;
4.str = str + “ HOW ARE YOU?”;
Line 3 is illegal, the rest are legal. Line 3 is invalid because you cannot modify characters in a string—you must create a new string instead.
Chapter 5: One More C# Chapter
5.1. Can an interface hold function declarations?
Yes, it can.
5.2. Can an interface hold function definitions?
No, it cannot. Interfaces cannot hold any function code whatsoever, only declarations.
5.3. Can an interface hold variables?
No, it cannot.
5.4. Are interface functions virtual by default?
No, they are not—you must declare them to be virtual explicitly.
5.5. Fill in the blank: Interfaces are C#’s way of supporting a limited form of _______
inheritance.
Interfaces are C#’s way of supporting a limited form of multiple inheritance.
5.6. How does using exceptions make your code cleaner?
Using exceptions allows you to separate special-case error-handling code away from your important processing code.
5.7. Which lines of code will not be executed?
1:public void Foo()
2:{
3:try
4:{
5:int[] array = new int[3];
6:array[3] = 10;
7:array[2] = 5;
8:}
9:catch
Chapter 5: One More C# Chapter 297
10:{
11:System.Console.WriteLine( “EXCEPTION!” );
12:}
13:finally
14:{
15:System.Console.WriteLine( “Process Completed” );
16:}
17:}
Line 7 is not executed because it is skipped over when an exception is thrown on line 6. Everything else is executed.
5.8. Using the code from Question 5.7, which lines of code will always be executed?
Line 15 will always be executed, no matter what exceptions are thrown.
5.9. How do you rethrow an exception without modifying it?
You rethrow an exception simply by using throw;.
5.10. A delegate can point to any public function, static or non-static, as long as the signatures are the same. (True/False)
True. This is why delegates are extremely powerful and flexible tools.
Use this code for questions 5.11 and 5.12: class Foo
{
static public int DoubleMe( int p )
{
return p * 2;
}
static public int TripleMe( int p )
{
return p * 3;
}
public delegate int MyDelegate( int p );
}
5.11. Assume the following code is run. What is the value of i?
Foo.MyDelegate d = new Foo.MyDelegate( Foo.DoubleMe ); int i = d( 10 );
The value of i is 20.
298 Appendix A Answers to Review Questions
5.12. Assume the following code is run. What is the value of i?
Foo.MyDelegate d = new Foo.MyDelegate( Foo.DoubleMe ); d += new Foo.MyDelegate( Foo.TripleMe );
int i = d( 10 );
The value of i is 60.
5.13. What is the primary difference between an array and an arraylist?
An array cannot be resized and an arraylist can.
5.14. Why is it considered an expensive operation to insert or remove items in the middle of an arraylist?
It is expensive because an insertion or deletion in the middle of an arraylist must move everything past the insertion/deletion point up or down an index.
5.15. Fill in the blanks: Hash tables store ____/____ pairs.
Hash tables store key/value pairs.
5.16. Text files are good for storing data that you want people to easily read, but name one reason why you would prefer a binary file instead.
Binary files are typically smaller than text files because they pack data better.
5.17. Are the numbers generated by System.Random truly random numbers?
No, they are not. An algorithm is used to generate them, and therefore they are not truly random. They just seem like it to our simple minds.
5.18. If you give two generators the same seed and then get a number from each of them, will they be the same?
Yes, generators with the same seed will always generate the same sequence of “random” numbers.
5.19. Name one reason why the ability to set your own random seed is a good thing.
The ability to set your own random seed allows you to re-create certain circumstances in a game, which allows you to track down intermittent bugs or create game-replays easily.
Chapter 6: Setting Up a Framework
6.1. Why is it a good idea to use a project wizard to start your projects?
Project wizards take care of a lot of the so-called “grunt work” and allow you to start coding the important stuff without worrying about the silly little details.
Chapter 7: Direct3D |
299 |
6.2. All windowed programs must have a class that inherits from System.Window. (True/False)
False. All windowed programs must have a class that inherits from System.Windows. Forms.Form. There is no System.Window class.
6.3. Default Form event handlers do nothing, so you don’t ever have to call the base version of the functions. (True/False)
False. Some of the event handlers (most notably OnKeyPress) take care of extra details for you, so you cannot simply override them without any consequences.
6.4. Why is it a better idea to use the AdvancedFramework.Timer class instead of the DXUtil.Timer function?
It’s better because the advanced framework’s timer class is object-oriented, and it allows you to create multiple timer instances rather than keeping one global timer.
6.5. What does System.Threading.Thread.Sleep() do?
This function causes the operating system to put your program to sleep for a limited duration and focus on more important tasks before coming back.
Chapter 7: Direct3D
7.1. What’s the difference between a hardware device and a software device?
A hardware device is a special piece of dedicated hardware in your computer that performs tasks such as coloring and vertex transformation. A software device is simply a fancy term for saying that your CPU is going to be doing the calculations.
7.2. Why would you prefer to use a hardware device over a software device?
A hardware device is typically preferred because it frees up the CPU for more other tasks, such as artificial intelligence or network processing.
7.3. Why are back buffers used?
Back buffers prevent flickering effects when drawing.
7.4. Why is 32-bit color preferred to 16-bit color?
32-bit color is very close to the full visible spectrum of colors, and it does not have colorbanding effects that 16-bit color has. Even though a 32-bit color is two times as large as a 16-bit color, it can store 256 times more colors.
7.5. What is alpha information?
Alpha information is simply defined as any extra information that is stored along with a color value. It is typically used for translucency effects.
