Learning c# by programming games pdf




















Order Microwave Egg Cooker Now. Huge Discounts Available! Your email address will not be published. Save my name, email, and website in this browser for the next time I comment. How to Visualize Data with D3 [Video]. How to Visualize Data with R [Video]. Computeractive 27 January Using tools such as Visual Studio, you can type these instructions into the source files of a project, following the rules of the chosen programming language such as C.

If all is well, the compiler will create the intermediate code and then an executable file, which is our program in machine code. If the code does not follow these rules, then the compiler produces errors and it will not create an executable file. Thus, you will most certainly encounter these errors yourself as well. After a few iterations of resolving these minor errors, the compiler will have generated the intermediate code and the executable file.

When the code has successfully compiled, you can execute or run the program to check if your code is also semantically correct. Of course, you made an effort to correctly express what you wanted the program to do, but conceptual mistakes are easily made. When the program does not work correctly, you go back to the editor and the process starts over: you change the source code, you try to compile it until it is valid, and you run the program again to see if the problem is solved.

Welcome to your life as a programmer! Before you start implementing i. First, you will have to design the game. What type of game are you building? Who is the intended audience of your game?

Is it a 2D game or a 3D game? What kind of gameplay would you like to model? What kinds of characters are in the game, and what are their capabilities? This phase is actually one of the most difficult tasks of game development. Once it is clear what the game should do, the next step is to provide a global structure of the program.

This is called the specification phase. Do you remember that the object-oriented programming 22 2 What Is Programming? In the specification phase, an overview is made of the classes that are needed for the game and the methods that are in these classes.

At this stage, you only need to describe what a method will do and not yet how that is done. However, keep in mind that you should not expect impossible things from your methods: they have to be implemented later on.

Once all that is finished, you can let other people play your game. In many cases you will realize that some ideas in the game design do not really work out that well. So, you start again with changing the design, followed by changing the specification and finally a new implementation. You let other people play your game again, and then, well, you get the idea. Programmers would spend weeks on software specifications before writing a single line of code.

Nowadays, it is common to make cycles as short as possible and to integrate it directly with user testing. This is also called an agile software engineering approach, since it allows for more flexibility and control during the development process. Syntax and Semantics What is the difference between the syntax and the semantics of a program?

Programming Paradigms: Overview Some programming paradigms are subsets of other paradigms. For example, every procedural language is also imperative. Draw a diagram that shows how the programming paradigms from Sect. Include the following paradigms: declarative, functional, imperative, logical, object-oriented, and procedural. Where in this overview do famous programming languages belong? Programming Paradigms: Statements Indicate whether the following statements are true or not and explain why : a.

All imperative languages are also object-oriented. All object-oriented languages are also procedural. Procedural languages have to be compiled.

Thus, a compiler itself is also a program. But if a compiler is a program, then someone must have compiled it at some point: a. Can a compiler itself be written in a programming language? And if so, can that language be the same as the language that the compiler compiles? Can a compiler compile itself? What language do you think has been used to write the first compiler ever?

Chapter 3 Game Programming Basics This chapter covers the basic elements of programming games. It provides a starting point for the chapters that follow. First, you will learn about the basic elements of every C program. You will then learn to identify all these elements in a simple MonoGame application.

Overall, a program consists of instructions, which are grouped in methods, and these methods are in turn grouped in classes. We will go a bit deeper into these concepts now. This means that it uses instructions to define the actual tasks that a program needs to do. Instructions are executed one after the other, and each instruction changes the memory or shows something on the screen.

In Chap. CornflowerBlue ; to GraphicsDevice. Chocolate ;. This line was an instruction—and indeed, by changing it, you made the program do something different. So, in short: instructions are the parts of a program that do the actual work.

In C , an instruction always ends with a semicolon the; symbol. By typing a semicolon, you tell the compiler that an instruction ends and that a new instruction or some other new part of the code will begin. Every instruction in a program belongs to a method. The group of instructions inside a method is called the body of the method.

As a programmer, you can choose any name for your methods. For example, if you create a platform game and you write a list of instructions that let your game character jump, it makes sense to group these instructions in a method with the name Jump.

Such a line is a method call, and in this case it will make sure that your character actually jumps. By contrast, the method Jump only defines what should happen when the method is called.

So: a method is a list of instructions that your program can perform. These instructions are performed as soon as you call the method. CornflowerBlue ; that you changed was also a method call. More precisely, it was a call to a method named Clear, which is defined somewhere in the MonoGame engine.

When you changed Color. CornflowerBlue to Color. In this case, the detail you changed was the exact color that you asked the method to draw. Formally, you changed a parameter of the Clear method.

Instead, it allows you to choose your own color and give it to the Clear method as a parameter. This is a very nice concept because it lets you use the same Clear method to draw any color. In C , when you call a method, you write the parameter values between brackets.

If a method has no parameters, you simply write a pair of brackets with nothing in between. Do we need to know which instructions are grouped together in the Clear method in order to use it? This is one of the nice things of grouping instructions in methods. You or other programmers can use the method without having to know how it works. By smartly grouping instructions in methods, and methods in classes, it is possible to write reusable pieces of program that can be used in many different contexts.

The Clear method is a good example of this. The only thing you need to know is that it takes a color as a parameter. For now, just remember that a method is a group of instructions, that these instructions are executed when you call the method, and that methods often have parameters.

Very roughly speaking, a class is a group of methods that describes what a certain part of your program can do. Just like how instructions must be part of a method, methods must be part of a class. And just like 3. You can give classes any name that you want. In game programming, we often use a class to describe a particular object that moves in the game.

In your hypothetical platform game, it probably makes sense to create a class Character that describes all the things that your game character can do. Later in Chap. For now, just remember the overall structure as shown in Fig. An object that you create with a class is called an instance of that class. This also means that you can reuse the same blueprint for multiple objects!

For instance, if there are multiple controllable characters in your game, you use the same Character class to describe what all of these characters can do. The multiple characters are different objects of the game and different instances of the Character class. But in general, their behavior is described by a single class in code. This is pretty much the smallest C program that someone can write. These curly braces are always nicely nested, because methods are always contained inside classes and methods are always detached pieces of code.

In this program, line 1 class HelloWorld is a class header: it says that the program contains a class with the name HelloWorld. Line 3 static void Main is a method header: it says that the class HelloWorld contains a method with the name Main you can ignore the words static void for now. Can you guess what these lines are? Indeed, they are instructions, the lines of the program that actually do something. Both of these lines are method calls.

The call to System. WriteLine has a single parameter, which indicates the exact text that you want to write. Read has no parameters: it always does the same job when you call it. In short, HelloWorld is a program with a single class called HelloWorld , which contains a single method called Main , which contains two instructions or more specifically method calls that do something with the console. The Main Method — We said before that you can give your own methods any name you want.

However, every program needs exactly one special method that will be called when the program starts, to get the program up and running. By default, every new Visual Studio application already contains a start-up method with the following header: static void Main. You can see this in the HelloWorld example as well. The project settings in Visual Studio already store the fact that Main is the start-up method. So, Main is the very first method that gets called when the program starts.

When Main gets called, the memory for your program is still completely empty: not a single object exists yet.

In very simple console applications, such as our HelloWorld example, you may not need any other methods than Main. As soon as your program becomes larger, it makes sense to introduce more methods, classes, and so on—but Main will always be somewhere in your program.

As an exercise, open this program in Visual Studio, try to change a few things about it, and then compile and run the program by pressing F5. The only difference is that the class now has a different name. This is because you have changed the parameter of the WriteLine function. The only remaining instruction is the one that waits for the user to press a key.

You will then receive error messages because your program is no longer syntactically correct; in other words, you are no longer following the strict rules of the C language.

This section talks about the two main building blocks of a game program: the game world in which the game takes place and the game loop that continuously updates this game world and draws it on the screen.

These building blocks are always part of a game, no matter what programming language is used. This imaginary realm in which you play the game is called the game world.

Game worlds can range from very simple domains such as the rectangular grid in Tetris to very complex virtual worlds such as in games like Grand Theft Auto and World of Warcraft. When a game is running, the computer maintains an internal representation of the game world. Fortunately, the program also knows how to create a visually pleasing representation of this world to display on the screen. Players never see the internal representation of the game world, but game developers do.

When 1 We lied about HelloWorld being the smallest possible program. If you remove lines 5 and 6, you will still have a valid C program that you can compile and run. And part of the fun of programming your own games is that you have complete control over this. Furthermore, the player influences how the game world changes, for example, by pressing buttons on a controller. In addition, the updated game world should be displayed on the screen, so that the player can see what has changed.

To ensure a smooth experience for the player, this process of updating and showing the game world needs to be repeated constantly. This repeating process is called the game loop. The game loop is responsible for two categories of tasks: updating and maintaining the game world and displaying the game world to the player. The game loop continuously performs these two methods, one after the other: update, draw, update, draw, update, draw, and so on.

At any point in time, Pac-Man is located somewhere in this labyrinth and is moving in a certain direction. In the Update method, the game should check whether the player is pressing an arrow key. If so, the position of Pac-Man should be updated according to the direction the player is requesting. This move can have many consequences. If this dot is a power-up, the game should make sure that all ghosts are going to behave differently.

Also, if this dot was the last remaining dot in the labyrinth, the game should recognize that the player has finished the level. Many other things should happen as well: the game should update the positions of the ghosts, it needs to check whether Pac-Man collides with any of the ghosts, and so on. You can see that even in a simple game like Pac-Man, the Update phase is already quite complex! In the Draw method, the game should of course draw the game world: the labyrinth, all characters at their freshly updated positions, and all dots that have not yet been picked up.

Next to this, the game should show other information that is important for the player to know, such as the score, the remaining number of lives, and so on. This extra information can be displayed in different areas of the game screen, such as at the top or the bottom.

This part of the display is sometimes also called the heads-up display HUD. Modern 3D games have a much more complicated set of drawing tasks.

These games need to deal with lighting and shadows, reflections, culling, visual effects like explosions, and much more. However, the main idea remains the same as in our Pac-Man example: the game loop should in some way keep displaying the game world in its most recent state. A single round of the game loop is often called a frame. Many game engines try to run their game loop at a consistent speed, for example, 60 frames per second. This kind of game loop is called a fixedtimestep loop.

The alternative option is that the game engine tries to execute the loop as often as 3. The MonoGame engine tries to run a fixed-timestep loop of 60 frames per second.

When you move the mouse around, the balloon moves along with it. You could implement this as follows. In the Update method, you write an instruction that retrieves the current position of the mouse pointer and that stores it in memory.

In the Draw method, you write an instruction that displays a balloon image at the stored position. Still, for the player, it looks like something is moving smoothly. This is the power of the game loop: by showing different images at a high framerate such as 60 times per second , it lures the player into thinking that everything moves smoothly. You also know that games have a game loop: a pair of methods Update and Draw that are being called over and over again, to give the player the illusion of smooth movement.

The code of this program is shown in Listing 3. You can find it as an example project of this chapter as well. Listing 3. Framework; using Microsoft. There is also a method named Main. After all, BasicGame is still a C program, and all C programs require a start-up method which is usually called Main. You also see that the word Main is followed by two brackets with nothing in between, while the words Update and Draw are followed by the phrase GameTime gameTime.

Comparable to the HelloWorld example, this means that the Update and Draw methods have a parameter while the Main method does not. In this case, gameTime is the name of this parameter chosen by the programmer , and GameTime is the type of this parameter. The type of a parameter indicates what kind of information the parameter contains, such as a number, a color, or in this case information about how much time has passed since the last frame. Furthermore, all methods are grouped in a class called BasicGame line 5.

But this time, line 5 contains more than just the name of our class. By saying that BasicGame is a special version of Game, we get a lot of MonoGame functionality for free, including the game loop. Because a method is basically a group of instructions, every time the Update method is called, the instructions inside that method are executed.

The same goes for the Draw method. In our program, the Update method does not contain any instructions yet, so nothing concrete will happen when Update is called. The Draw method currently contains only one instruction that fills the game window with a particular color. So although nothing interesting seems to be going on, there really is a game loop running in the background when you play the game.

Wait a second—this might seem weird. We said earlier that a method is not executed unless you call it somewhere else in your program. How is that possible? Well, this is one of the things that the MonoGame engine already does for you. By saying on line 5 that our own class BasicGame is a special type of Game, we get all methods from the Game class for free. The only thing you have to do yourself is add instructions to these methods. So the line class BasicGame: Game is quite important for letting the game do what it does!

We will not dive deeper into inheritance until Chap. Next to Update and Draw, MonoGame incorporates a few other useful methods that you automatically get by inheriting from the Game class. Two of these methods are related to starting the game, and the difference between these two methods is a bit complicated. The Initialize method is executed once, when the game begins.

This is the place where you can do initialization tasks, such as changing the width and height of the game window, setting up an input device, or opening a network connection. The Initialize method is added automatically in every new project that you create. The LoadContent method is also executed once: after the Initialize method but before the game loop starts. In this method, MonoGame has set up a ContentManager object, which is in charge of managing game assets such as sprites, sounds, or other files that the game needs.

Therefore, LoadContent is the first place where you can load sprites and sounds. If we wanted to, we could also load our assets directly in the Update or Draw method. However, this would significantly affect the performance of our game, since we would then reload these files 60 times per second.

Because the Initialize and LoadContent methods are executed shortly after each other, you could also leave out Initialize and just use LoadContent for everything. This is what we have done in the BasicGame example, and we will keep doing it throughout this book. The only thing to watch out for is that some things such as loading game assets cannot be done in Initialize yet.

Finally, the LoadContent method also has a counterpart called UnloadContent, and you might already guess what its purpose is. UnloadContent is called after the game loop ends which happens when the player quits the game. In this method, you can clean up any memory that was allocated for game assets. We will not use the UnloadContent method in this book. In our examples, quitting the game always means closing the application, and the memory will be cleaned up automatically when the application is closed.

However, UnloadContent can be useful in a more complicated application where players can exit the game without immediately closing the application. If the player quits one of these games and returns to the hub, it makes sense to clean up the assets of the game that has just been closed.

The Initialize and UnloadContent methods will be ignored in this book In summary, these are the basic methods in every MonoGame application: 1. Initialize for initialization tasks such as opening a network connection or setting up an input device; 2. LoadContent for loading sprites, sounds, or other assets needed for the game; 3. Update for continuously updating the game world according to the time passed and to what the player is doing; 4. Draw for drawing the game world onto the screen; 5.

UnloadContent for unloading game assets just before the game closes. This method is not part of the MonoGame engine. Figure 3. Every game that you are going to create in this book follows this basic structure or a simplified version of it. In this book, you will see lots of ways to fill these methods with the tasks that you need to perform in your game.

Before we can draw anything, we need to initialize the so-called graphics device. Initializing the graphics device is something that you need to do once, before the actual game starts. Otherwise, you cannot draw anything on the screen. This initialization step is always done in the constructor method which is called BasicGame in this case.

You can see this happening on line 31, in the Draw method: GraphicsDevice. Olive ; Clear is a method of the GraphicsDevice class. To call it, you need an instance of the GraphicsDevice class to work with. Therefore, the code GraphicsDevice. Clear will call the Clear method for that instance. Olive is a parameter of the Clear method.

The BasicGame example is already a bit bigger, mostly because it uses the MonoGame engine in the background. Namespaces are a way to group related classes, just like how classes are a way to group related methods.

As usual, a namespace has a header the word namespace followed by a name of your choice and a body enclosed by braces. Namespaces are useful for grouping classes that are strongly related to each other. For example, you could create a namespace called Graphics that contains all classes that have something to do with displaying things on the screen. However, if you want to use your class somewhere within the same namespace, you can just write Drawer because then the compiler understands where you are.

If your class is called MyClass, you should refer to it as MyNamespace. If you are inside the same namespace, you can simply write MyClass. Namespaces can also be grouped into each other. Instead, these lines indicate that the program may use classes or methods from three libraries : Microsoft.

Framework, Microsoft. Graphics, and System. A library is a set of classes usually created by someone else that you can reuse in your own program. The Microsoft. Framework library defines the Game class that our game inherits from. We would then have to write Microsoft. Game everywhere instead of Game, to indicate where the class comes from.

Thus, by writing using Microsoft. Framework; at the top of your file, you can make the rest of your code easier to read. Similarly, Microsoft. Graphics defines the GraphicsDevice class that is used at a few points in the program, and System is a library that is often used in Windows programs. Quick Reference: Libraries and using If you want to use classes or namespaces that are defined somewhere else such as in an external library , write the following line at the beginning of a file: using LibraryName; where LibraryName should be replaced by the name of the class or namespace you want to use.

For example, the line using Microsoft. Framework; includes the MonoGame library, which allows you to use the Game class among other things. This is also valid C , but it makes your code longer and usually harder to read. Libraries are very useful, because they allow you to reuse methods and classes written by other people.

In BasicGame, we use the Clear method on line 32 to clear the window and give it a color. This method is not written by us, but we can still use it because we indicated in the beginning of our program that we need things from the Microsoft. Graphics library. Dealing with Errors — If you ever forget to include a certain library that your code needs, the compiler will show errors.

For example, if you forget to include Microsoft. Framework, the compiler will not know what you mean by the word Game. Luckily, if this happens, Visual Studio is smart and nice enough to help you out. It can suggest what you probably need to change in your program to resolve the error. In this same example, if you hover your cursor over the word Game, you will see an option called Show continued 3.

In this case, you have at least two options: replace Game by Microsoft. Game or include the Microsoft. Framework library at the top of your file. Actually, every time your code contains an error or a warning , you can use this trick to see how Visual Studio can help you out. For a very large part, programming consists of re writing code step by step.

In other words, try to imagine compiler errors as hints for what you still need to do. That way, dealing with errors becomes less intimidating. A text file containing C code is called a compilation unit. In the BasicGame example, there is only one compilation unit, and it contains a single class. A compilation unit consists of optionally a number of using instructions, followed by a number of namespaces or classes.

Luckily, most programming languages including C allow you to write comments that can help clarify what your program does. This allows you to write multiple lines of comments in a single block. Keep in mind that comments are meant to clarify the code: you can assume that readers of your code are familiar with C , but you can still help them understand why you chose to write your code in a particular way.

Olive to the Clear method of the GraphicsDevice object. Olive ; Clearly, the first comment is helpful because it explains our intentions. Comments are also an easy way to temporarily remove instructions from the program. Otherwise, others may be confused about why the unused code is still there.

Lines There are no strict rules about how to distribute the text of a C program over the lines in a text file. Usually, you write every instruction on a separate line. The opposite is also possible. If a single instruction is very long e. You will see this happening later on in this book as well.

In short, adding and removing newlines is OK according to the C language. There is an empty line between each method, as well as spaces between an equals sign and the expressions on either side of it. Just like the use of newlines, spacing can help to clarify the code for the programmer, but it has no meaning for the compiler. In text that is interpreted literally, spaces are also taken literally. Visual Studio often helps you a bit by automatically performing the indentation.

Also, the editor automatically places whitespace at certain spots in your code to improve readability. Instructions, Methods, Classes What is an instruction, a method, and a class? And how are these concepts related to each other?

Comments What are the two ways to write comments in a C program? And what are the most important reasons to use comments? The Game Loop Below are some questions about the game loop, the basis of every game program. What two actions are the main elements of the game loop? What is the use of these actions? What methods does MonoGame add to this? What is the use of these methods? What is the difference between a fixed-timestep game loop and a variable-timestep game loop?

Can you think of an advantage and a disadvantage of both types? The Update and Draw methods are always executed in sequence.

Technically, we could move all the code from the Update method into the Draw method, and leave out the Update method altogether. Why is it still useful to have different methods? If you take this to the extreme, what is the shortest C program that you can possibly write?

Hint: the shortest program we could come up with is a console application of 26 characters long that does absolutely nothing. Chapter 4 Creating a Game World This chapter shows you how to create a game world by storing information in memory. It introduces variables, types, and expressions, and it shows how you can use them in C to store or change information. You have seen how to execute a simple instruction like GraphicsDevice. Olive ; to clear the window and set its background color.

You will do this by computing a new color in the Update method in each frame of the game loop and storing it in a so-called member variable. Afterwards, the Draw method will use this member variable to draw the actual color.

Programs in C are full of variables, and the core business of game programming is to set these variables to the correct values in the Update method so that the Draw method can show the game world correctly. For instance, the GraphicsDevice. Methods only work with certain types of information. Clear gameTime. The GraphicsDevice. Clear method expects a color to draw and not information about the game time! Try replacing Color. There are many types in the C language.

Some of these types represent numbers, such as int used for whole numbers and double used for numbers with a fractional part. An example is string, a data type used for pieces of text. Next to the types that always exist in C , the MonoGame engine adds more types that are especially useful for games. This is the name by which the variable can be recognized, so that you can use it throughout your program to store and modify information.

As a programmer, you can choose the name of a variable yourself. A variable declaration is an instruction in your code that introduces a new variable with a name and type. After this declaration, the computer has reserved a place in memory that can store an int, and you refer to this place by the name red.

Kanetkar Yashavant: Let Us C. Learn the hand-crafted notes on C programming Key Featuresa- Strengthens the foundations, as a detailed explanation of programming language concepts are givena- Lucid explanation of the concepta- ….

Learn advanced techniques and best practices of Angular programming for building enterprise web applications Key Features? Get familiar with the core concepts of Angular.? Discover best practices, …. Learn to harness the power of the Apex language to build Salesforce applications Key Features a- Learn how to work with the Apex language a- Learn how to develop Apex Triggers a- Learn how to use ….

Learn advanced techniques and best practices of Angular programming for building enterprise web applications Key Featuresa- Get familiar with the core concepts of Angular. Raghu Korrapati: 9 Winning Habits of Successful. It is often said that salespeople would rather sell than spend a day learning how to do it. They think time is money and every hour spent in training is money lost and time wasted.



0コメント

  • 1000 / 1000