SDL game tutorial Lesson 1 Basics

Source: Internet
Author: User
Translation statement:
This series of tutorials comes from Dev hub and all the right to interpretation belongs to the original author. I translated this series of tutorials only from my hobbies. Because I am also a beginner and have a limited level of English, it is inevitable to make mistakes.

Address: http://www.sdltutorials.com/sdl-tutorial-basics/

These courses are intended for those who have certain C ++ experience or other programming languages. If you cannot keep up with the Code itself, rather than conceptual issues (game-related), I suggest you read our course on interpreting the C ++ programming language first. Although it is not necessary to grasp all c ++, it will be helpful in the future.

In this series of tutorials, we will use codeblocks as our IDE, GCC and mingw as the compiler. If you want to use other IDES and compilers, you can do whatever you want, but if you have no experience with the connected library, it may not be very good. If you want to download codeblocks, you can get the http://www.codeblocks.org for free (download the one containing the mingw package ). It is strongly recommended that you use the stable version unless you want to spend more time and day-and-night modifications.

This series of tutorials will closely focus on SDL (Simple DirectMedia Layer), a 2D cross-platform graphics library. This library allows us to draw fantastic images and all interesting things on the screen to create our game. You need to download this library to the http://www.libsdl.org, be sure to download the mingw32 tar file under the "Development Library" and the "Win32" compressed package under the "Runtime Library. If you are using Visual Studio, you can download the corresponding version to replace the minw32 file. Once the download is complete, we recommend that you put the. dll in the compressed package into your system32 directory. This is required to run an SDL application.

Open the tar file (that is, the one listed under "Development Library") and decompress it to a directory (for example, C:/SDL ). Now, to open codeblocks, you need to change some settings. Click "Settings" on the menu bar, and then click the "Find directory" option page. You need to add C:/SDL/include to the "compiler" option page, and add C:/SDL/lib to the "connector" option page (set C: /SDL to the directory where the extracted file is located ). Click okay.

Start a new blank project. Save to a certain place. Click "project", and then click "properties" to bring up a dialog box. Click "project creation options..." in the lower right corner. Click "connector Settings" to add the following content to the list under "Link Library:

Mingw32
Sdlmain
SDL

The order is very important. We must keep the above Order. If you do not understand what we are doing, we are just connecting the Code together, or, in other words, we are integrating the SDL code into our own code. Use the include file for compilation and the Lib file for connection. Once completed, your code will form a whole to generate an application.

Click OK twice to complete all settings!

Let's create two new files, namely, Capp. h and CAPP. cpp, which serve as the core part of our program. First, open the CAPP. h and add the following code. From then on, our course will actually start:

Now, open Capp. h and add the following code:

  1. # Include "Capp. H"
  2. Capp: CAPP (){
  3. }
  4. Int CAPP: onexecute (){
  5. Return 0;
  6. }
  7. Int main (INT argc, char * argv []) {
  8. Capp theapp;
  9. Return theapp. onexecute ();
  10. }

This CAPP class lays the foundation for our entire program. Let's first take a look at how a game performs typical settings. Almost all games are composed of five functions that process the game. These processes are similar to the following:

Initialization
Processing all data loads can be texture maps, maps, or NPCs.

Message
Processes all input messages, from the mouse, keyboard, game pole, or any other device.

Loop
Process all data updates, such as moving the NPC, removing your blood records, or anything else.

Rendering
Processing all Scene Rendering does not operate on data, because it should be completed by the cyclic function.

Clear
Simply clear all loaded resources and declare that a game exits correctly.

Understanding about games is a huge loop, which is important. In this loop, we find the message, update the data, and then render the image. Therefore, the basic structure is similar to the following:

Initialize ();

While (true ){
Events ();
Loop ();
Render ();
}

Cleanup ();

At each cycle interval, we modify some data and then perform corresponding rendering. Messages are appended, but they are only a way for users to operate on data. In a sense, a message is not necessary to make a game, but it is needed when we want users to operate data (such as moving an NPC to the left.

For example, it will be clearer. For example, we have a knight, the hero of the game. What we want to do is to let him go round. If I press left, he will go to the left. We need to solve how to implement it in a loop. First, we know that we want to check messages (keyboard messages ). Because a message is a means to operate data, we also know that some types of variables need to be modified. Therefore, we can use these variables to render our server guard at the right position on the screen. We need:

If (Key = left) x -;
If (Key = right) x ++;
If (Key = up) Y -;
If (Key = down) y ++ ;//... Somewhere else in our Code...

Renderimage (knightimage, x, y );

It can run because the key is left, right, and so on are checked in every loop. If so, we increase or decrease a variable. So if our game runs at 30 frames per second and we press left, this guy will move 30 pixels to the left every second. If you don't understand what the game loop is, you will understand it later. Games require them to run correctly.

Back to our conceptual code (those five functions), we can add some additional files to our project:

Capp_oninit.cpp
Capp_onevent.cpp
Capp_onloop.cpp
Capp_onrender.cpp
Capp_oncleanup.cpp

Return to CAPP. h and add the following functions and variables:

  1. # Ifndef _ capp_h _
  2. # DEFINE _ capp_h _
  3. # Include <SDL. h>
  4. Class CAPP {
  5. PRIVATE:
  6. Bool running;
  7. Public:
  8. CAPP ();
  9. Int onexecute ();
  10. Public:
  11. Bool oninit ();
  12. Void onevent (sdl_event * event );
  13. Void onloop ();
  14. Void onrender ();
  15. Void oncleanup ();
  16. };
  17. # Endif

Create their own functions and complete each file they just created:

  1. # Include "Capp. H"
  2. Bool CAPP: oninit (){
  3. Return true;
  4. }
  5. # Include "Capp. H"
  6. Void CAPP: onevent (sdl_event * event ){
  7. }
  8. # Include "Capp. H"
  9. Void CAPP: onloop (){
  10. }
  11. # Include "Capp. H"
  12. Void CAPP: onrender (){
  13. }
  14. # Include "Capp. H"
  15. Void CAPP: oncleanup (){
  16. }

Now let's go back to our Capp. CPP Code and link all these functions together:

  1. # Include "Capp. H"
  2. Capp: CAPP (){
  3. Running = true;
  4. }
  5. Int CAPP: onexecute (){
  6. If (oninit () = false ){
  7. Return-1;
  8. }
  9. Sdl_event event;
  10. While (running ){
  11. While (sdl_pollevent (& event )){
  12. Onevent (& event );
  13. }
  14. Onloop ();
  15. Onrender ();
  16. }
  17. Oncleanup ();
  18. Return 0;
  19. }
  20. Int main (INT argc, char * argv []) {
  21. Capp theapp;
  22. Return theapp. onexecute ();
  23. }

You will find some new variables. However, let's see what happened first. First, we tried to initialize our game. If it fails, we returned-1 (an error code), so we closed the game. If everything works, continue our game loop. In the game loop, we use sdl_pollevent () to check messages and pass them one by one to onevent (). Once the message is completed, we go to onloop () to operate the data and then render our game. We repeat it endlessly. If the user leaves the game, we will go to oncleanup () to clear all the resources. That's simple.

Now let's take a look at sdl_event and sdl_pollevent (). The first is a struct containing message information. The second is a function that captures arbitrary messages waiting in the queue. There are a lot of messages in this queue, which is why we need to traverse them cyclically. For example, if the user presses a During the onrender () function execution and moves the mouse. SDL detects the message and places two messages in the queue. One is the button and the other is the mouse. We can use sdl_pollevent () to capture a message from the queue and pass it to onevent () for corresponding processing. Once no messages are in the queue, sdl_pollevent () returns false and then exits the Message Queue loop.

Another added variable, running, is private. Indicates whether or not we quit the game loop. If it is set to false, the program ends and then exits. For example, if you press the Escape key, set it to false and exit the game.

At present, your compilation should be smooth, but you may notice that you still cannot exit. You may also get the task manager to terminate the program.

Now everything is done, we will start to create a window to draw the game.
Jump to the CAPP. h and add an SDL surface variable to the Code:

  1. # Ifndef _ capp_h _
  2. # DEFINE _ capp_h _
  3. # Include <SDL. h>
  4. Class CAPP {
  5. PRIVATE:
  6. Bool running;
  7. Sdl_surface * surf_display;
  8. Public:
  9. CAPP ();
  10. Int onexecute ();
  11. Public:
  12. Bool oninit ();
  13. Void onevent (sdl_event * event );
  14. Void onloop ();
  15. Void onrender ();
  16. Void oncleanup ();
  17. };
  18. # Endif

I think it's time to explain what an SDL is. An SDL surface is anything you can draw on it. Suppose we have a blank sheet of paper, a pencil, and some stickers. This paper can be called our display "surface" and we can draw something on it, put the sticker on it or something else. Our Paster is also a surface; we can paint it on it and then paste it on another Paster. Surf_display is our "White Paper ". We need to draw everything on it.

Now let's go back to capp_oninit to create this surface:

  1. # Include "Capp. H"
  2. Bool CAPP: oninit (){
  3. If (sdl_init (sdl_init_everything) <0 ){
  4. Return false;
  5. }
  6. If (surf_display = sdl_setvideomode (640,480, 32, sdl_hwsurface | sdl_doublebuf) = NULL ){
  7. Return false;
  8. }
  9. Return true;
  10. }

The first thing we need to do is to start the SDL itself before we can access its functions. We told SDL to initialize everything about it. Other parameters can be passed, but it is not important to understand them now. The next function is sdl_setvideomode (). He is the guy who creates our windows and surfaces. It has four parameters: window width, window height, window bit depth (16 or 32 recommended), and then the display flag. There are quite a few display marks, but the one shown above is exactly the same now. The First Flag tells SDL to use hardware memory to store our images, and the second tells SDL to use dual cache (this is important if you don't want to flash the screen ). There is also a flag that you may be interested in, that is, sdl_fullscreen, which enables full screen display of your window.

Now we have finished our display, but we have done some cleanup to ensure smooth work. Open capp_oncleanup.cpp and add the following:

  1. # Include "Capp. H"
  2. Void CAPP: oncleanup (){
  3. Sdl_freesurface (surf_display );
  4. Sdl_quit ();
  5. }

The first thing we need to do is release the display surface, basically releasing some memory space. Then, we quit SDL. Note that this is where you release other surfaces (maybe before surf_display ). This ensures that all your code is concentrated on its functional implementation.

To keep the surf_display pointer clean, we also set the surf_display pointer to null in the constructor.
Open the CAPP. cpp and add the following:

  1. Capp: CAPP (){
  2. Surf_display = NULL;
  3. Running = true;
  4. }

Compile your code to see if it can be run. You will get an empty pop-up window.
You will find that you still have to go to the "excuse me" task manager.

Now we have fixed a window, and we have to find a way to close it.
Open the capp_onevent.cpp file and add the following:

  1. # Include "Capp. H"
  2. Void CAPP: onevent (sdl_event * event ){
  3. If (Event-> type = sdl_quit ){
  4. Running = false;
  5. }
  6. }

The SDL message structure is removed to types. These types can include buttons and mouse movement. We only need to check the message type here. The type we found above is required to close the window (for example, when the user clicks the X button ). If that message occurs, set running to false and terminate the program. That's simple. We will repeat the news in subsequent courses.

Now everything is done, and it is an excellent structure that can be reused in the future. It may be a good idea to transform this project into an "SDL template" in codeblock. I don't want to go back, just Google it.

If you want to know what happened to the code we mentioned here, skip to the next lesson to learn more about SDL.

SDL course basics-tutorial files:
Win32: Zip, rar
Linux: Tar (thanks to gaten)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.