Click here to Skip to main content
15,885,435 members
Articles / Multimedia / GDI+

MELHARFI-2D-Game-Engine

Rate me:
Please Sign up or sign in to vote.
4.73/5 (5 votes)
8 Feb 2021MIT14 min read 7K   4  
2D Game Engine + Network Library + Path finding + Windows GUI + Mouse Event handler "ALL-IN-ONE"
In this article, you will see an all in one (Game engine + Pathfinding + Encrypt & decrypt + Network lib) Windows 2D Game Engine.

Image 1

Description

MELHARFI is a standalone DLL to create 2D games easily or to add some animation into your application's forms. Don't worry about many details in the usual way or adding some complex third party applications, only to make some dynamic graphics in your form.

It's commonly useful for beginners and for advanced people, as I’ll show you my own game that I build with it (at the end of that topic).

The library is built in C# so you can use it in any .NET language such as VB.NET using .NET Framework 4.0 or higher and Visual Studio 2015 or higher (some lambda expression not handled by VS 2013 or older).

Tutorial

See complete tutorials 24 sections here.

Features

  • GDI+ with double buffering
  • Encapsulating existing code to make it really easy
  • Animation method: You can create animation, with parameters, with timer, a number of shapes, reversed or not, movement or stable...
  • Draw text, image, rectangle, Shapes (Polygone), animation

handle events: MouseDoubleClic, MouseClic, MouseDown, MouseUp, MouseMove, MouseOut, MouseOver,

AStar algorithm to find the way path between point A to point B in a Map with obstacles to make a movement of a player.

  • Network library to create an awesome Client / Server application for networking games

Its LidgrenNetwork library inside my library, all thanks go to him.

https://github.com/lidgren/lidgren-network-gen3

  • Use encrypted assets to prevent from stooling your artwork from other people. There is a tool to encrypt and decrypt your assets

The library is divided into three pieces:

  • MELHARFI: for all gaming/graphic representation stuff you need
  • MELHARFI.AStar: for pathfinding
  • MELHARFI.LidgrenNetwork: for networking

Question 1

What is 2D Game Engine?

Response 1

The 2D game engine is a library you can integrate into your existing project and lets you build games or graphics representations. The engine already handles many details about initializing game parameters, screens, and events. You won't have to get bored with the gritty details and then create a game in some few lines of code.

Question 2

Why another 2D game engine while there are dozens of them?

Response 2

In reality, I have a passion for creating games it was some couple of years. I just wanted to create a game like you right now.

My favorite games were always 2D especially RPG/MMORPGs. You'll soon see that there's not a lot of 2D MMORPG games (good ones), nor 2D games engines, maybe some old ones, but they are no longer supported, like SDL or XNA (reported to MONO by now). You'll soon get stuck and no one can help you as I already try them and documentation is poor. On the other hand, I was only familiar with C# language and the .NET technology, so most of the engines were in C++.

Question 3

What distinguishes it from the others 2D Game Engines?

Response 3

Creating a game is not that hard using any library/engine you want with some piece of code given to help you to start, BUT the big problem I found is when I need to create some GUI (Graphic User Interface "controls") to interact with user, as a Chat Box, Text Input, Buttons, copy/paste / click ... I didn't find any clue.

So you have to create all of them programmatically and design them and I know that creating a game is easier than creating a controls itself because it needs to handle some advanced Windows events like click/Keyboard on the shape and so many other stuff ... you know it's really complicated.

In fact, there are some GUI Engines but I found them ugly as far as I know, or not in the same language (C++) or it needs special configuration, working only with DirectX or not free ... oh my god.

I just wanted to use the same controls that we all know, those of Windows, pretty good and perfect. I soon get frustrated by that obstacle, and I found NO game engine that integrates some GUI inside.

All the engines use the DirectX technology to create games, and if you've done some try in programming with that technology, you should know how it's hard to interact with the DirectX, so complicated FOR ME, so I wanted something simple.

Another problem was the interaction between object drawn and mouse handling Event because you should program it yourself and I didn't find it already supported in any engines. Another problem was to integrate a network library to make my game multiplayer. I looked on the internet and I found LidgrenNetwork and I just wondered if there's an engine with all those features. After some search, I found NOTHING that I can appreciate, so here is the deal.

  • I need a 2D game engine written in .NET technology.
  • I need it to be simple, not in DirectX because it's so hard for me.
  • I need the ability to add the controls (GUI).
  • I need a network library for my multiplayer game.
  • I need an algorithm of path finding between point A until point B in a Map with obstacles.
  • I need to crypt my assets to prevent other people from stealing it or modifying it.

Searching Google ...> nothing dud lol

What a good challenge if I write it myself and include all that in ALL-In-One and be Standlone !! and job done for you, don't worry anymore ^^

Question 4

Why GDI+? DirectX is more powerful than GDI+.

Response 4

Windows use GDI+ to draw some stuff on the Forms of its applications, it was not created for gaming purposes, it's not even supposed to support so much stuff on the same form, BUT nothing stops you from using it.

In fact, GDI+ is slower because it was not designed for such thing BUT only in the really old and slow computers like Pentium 3 or earlier with the old Windows version, all of us use minimum a Core processor that is sufficient to handle it.

DirectX uses many technologies that let it pretty fast but if you are not a master of programming, you can't achieve what you want.

Another thing is, that lib is not only made for gaming purpose, it's a way to animate your application or a representation. Showing a tutorial in the first starting of your application for example, or a lot of stuff you can do like graphic representation ...

Question 5

Does this library need me to know programming?

Response 5

Yes, the library only cares about creating a context of gaming, parameters of the screen, double buffering and encapsulation of methods that let you draw things on the screen instead of the original methods not obvious.

There is a code to help you use the engine with all its modules (Network, Pathfinding, Graphics, Mouse Events ...). I could add other stuff but my engine was created in the context of what my game need so far, (well, I had stopped to continue my game because of less time I have and other personal stuff), but I still continue make it more advanced.

Yes, you need to know how to code with Net technology to achieve what you want but I am sure that it's not really hard.

Question 6

What is the disadvantage of MELHARFI 2D Game Engine?

Response 6

No special effect in animation like particle animation unless you add another library. No rotation of image unless you create many instances of images in different situations and use it like animation by showing them one by one (purpose of Anim class).

How To

There is 23 chapters in the wiki https://github.com/melharfi/MELHARFI-2D-Game-Engine/wiki but I will post a start example:

01. Initializing MELHARFI Engine

Assuming you start a Winform application and added a reference to MELHARFI-2D-Game-Engine using nuget:

Install-Package MELHARFI -Version 1.6.0

or using github release.

Initialization

Surface to Draw In

Our representation will be drawn in a Windows Control, meaning that all controls given by your IDE as Form, Panel, even inside a button or picture as long as it's a control object.

But for our case, we are going to use the form itself as placeholder for our drawing shapes, but before we need to explain some details.

What is Manager Object?

It's a class that you should instantiate to handle your game/app content, you can create more than 1 instance, each one has its own layers (background, objects, top, control) and are completely isolated.

How Many Manager Instances of the MELHARFI Game Engine Do I Need?

Now you have to decide WHERE SHOULD I DRAW ?

  1. Consider that all the surface of the screen is for the game, in that case, you can choose the main form itself as a placeholder for your game, and you only need to create 1 instance.
  2. Consider you will use a special surface to draw your game content (First instance of the Manager) maybe a panel inside your form that covers majority of the form or the whole form itself, and another small area "panel" for your hud in foot section of your form (Second instance of your game engine), and another area "panel or whatever" for another purpose like a menu in the left side (Third instance of your game engine)
So What Makes the Difference Between Both Ways?

All depend on your game logic and how its complexity, if it's a simple game, only one instance of your game engine is sufficient as you just need to know how to deal with the different sections.

If your game is a bit mature or needs advanced architecture, you need more than one instance of the Manager instance.

  • one instance to draw your game content Non-Static (meaning content is changing all the time when player move or map is changed ...).
  • second instance for your hud content Static (the hud usually doesn't change apart some lifepoint could be changed but most of the time, it's considered as a second portion of your game), it's useful when you want to clear, modify or remove your screen game (player has changed map) so in this case you don't want to remove your hud, menu and other stuff not considered as a part of your game content, so in this case, you don't have to worry about that because hud, menu ... are handled by the other instance of your game engine.
Choose a Resolution of Form

Considering that your main form is suited to your game drawing land.

First, you have to choose a resolution suited for you, for example, let's make it 800x600 (800 pixel for width, 600 pixel for height), we also want it to be fixed, not resizable "FormBorderSyle = FixedSingle", you can manage other stuff like rename the label of the game, the engine does not allow to resize the screen, it only draws item to a control with the original size.

Initializing the Game and Applying a Background Color

The next step is to create an instance of our game engine "Manager" and for that, go to the code section, right click on your main form and chose "View Code" or click F7 shortcut.

You need to add reference of MELHARFI library to your class:

C#
using MELHARFI;
using MELHARFI.Manager;

Image 2

Assuming your game is basic and needs only one instance of your game engine, add this line in the Form1 class constuctor:

C#
Manager manager = new Manager(this, "name_of_Instance_like_CORE_ENGINE");

Image 3

The name given to the constructor gives a meaning of the current instance, we'll cover its uility later.

By default, the background color is black, so if you compile your project, you'll see a black window.

To change the background color, just add this line:

C#
manager.Background = Color.Blue;

Image 4

And just run your code to see a beautiful window:

Image 5

If you experience some kind of Flickering of screen, it's an issue in GDI+ that you can resolve by adding that piece of code at the top of your main form code just after InitializeComponent();.

C#
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | 
              ControlStyles.DoubleBuffer, true);
this.Invalidate();

Image 6

02. Superposition and ZIndex

Superposition of layers:

Image 7

For any 2D game, you should notice that there is a background, content and top layer:

  • BackgroundLayer is the color or a background picture, it could be many assets as the first layer and it stands in the back (layer 1).
  • ObjectLayer like players, monsters... that come front of background (layer 2).
  • TopLayer, like Hud, Chat box, Buttons... (front of content layer 3)

The same thing is handled by this engine.

FixedObjectLayer: I add that layer to reference some object that I don't want them to be removed especially when cleaning screen, useful when I want to redraw my screen or change it without touching some objects like hud which is static, that mean it's not a layer to draw objects but reference some object already drawn and not considered as a drawing layer, therefore not superposed to the previous layers.

ControlLayer: In this layer, we reference all Windows controls used like buttons, radio, checkbox, panel... it's necessary to reference them in case we want to hide a menu that those controls and we must keep a reference of them to ControlLayer to hide them or remove them, keep in mind that those controls area always drawn in top even over TopLayer but excluded from superposition of other layers cause it stores only Windows Controls, not shapes.

Those layers are displayed in superposition, the BackgroundLayer comes first, and ObjectLayer came over the background, and TopLayer is always displayed on the Top.

Image 8

On each layer, you can add many item (image, shape) as you want. For background layer, maybe you have a color background, cloud, building... For content layer, you have your plane, and enemy planes that shoot you some missiles... And finally, you have TopLayer to draw everything on the top like some messages, chat, hud ...

Z-Index

Another arranging step is the Z-Index.

To do that, you have to use what we call a Z-INDEX parameter, it's the depth of the object inside the layer itself, like the 3rd coordinate "3D" but we are doing this in 2D gaming, some call that 2.5 D LOL.

In each Layer as Background or Object or Top could have many objects inside, so you need a way to arrange them to make some superposed over the others, like building over cloud. To achieve this, let's say you have three background objects.

  • Background_Color
  • cloud
  • building

To order them with z-index, you should make:

  • Background_Color z-index = 0;
  • Cloud z-index = 1;
  • Building z-index = 2;

And you increment each time you want an object to be over another object.

In coding, those layers are only a List of objects, background layer is represented as BackgroundLayer (Graphics Background List). Object layer is represented as ObjectLayer (Graphics Object List). Top layer is represented as TopLayer (Graphics Top List). Other extra layers has been added for some issues that we are going to see later called like:

  • FixedObjectLayer
  • ControlLayer

And Z-index is coded like this:

C#
label1.zindex = 1;

While the zindex is higher, more it's on the top.

When creating an object without attributing a value to its zindex, it's automatically attributed as the higher value to make it in the very top on the screen.

So you don't need to affect the Z-index to an object each time as it's automatically incremented when a new object is created, UNLESS if you want to make an object created at last be behind another object created from the beginning, so in that case you should initialize the z-index of the last object to be less than the first one like:

C#
Bmp building = new (@"c:\building.jpg", new Point(0, 0), manager);
Bmp cloud = new (@"c:\cloud.jpg", new Point(0, 0), manager);
cloud.Zindex = building.Zndex - 1;

03. Drawing Classes

  • Bitmap, it shows a picture in different format, like Bmp, Jpg, Pnj ...
  • Rectangles, drawing a square box colored or not
  • Animation, showing a successive pictures
  • Text, drawing text with font and color ...
  • FillPolygon, to draw shapes as a polygon

Preference Visual Studio 2017 or above, I am using 2019 fresh version for this tutorial.

These classes will be explained in the next chapters.

Remember that you have to add this line:

04. Bmp (Bitmap)

Bmp Class

To draw a picture "Bitmap", you should create an instance of Bmp class. This class has 20 overloads depending on what the parameters you want to initialize. The easy one is:

C#
Bmp cloudPicture = new Bmp("cloud.png", new Point(0,0), manager);

And here is a complete code:

C#
using System.Drawing;
using System.Windows.Forms;
using MELHARFI.Manager;
using MELHARFI.Manager.Gfx;

namespace _2dProject
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Manager manager = new Manager(this, "CORE_ENGINE");
            manager.Background = Color.Blue;
            Bmp cloudPicture = new Bmp("cloud.png", new Point(0,0), manager);
            manager.BackgroundLayer.Add(cloudPicture);
        }
    }
}

https://melharfi.github.io/repos/MELHARFI-2D-Game-Engine/assets/ch3-cloud.PNG

Obviously, you can change the Position as you want.

ObjectLayer is the common asset like players, monsters... that come in front of background (layer 2).

C#
Bmp superMario = new Bmp("supermario.png", new Point(100, 100), manager);
manager.ObjectLayer.Add(superMario);

Image 10

05. Rec (Rectangle)

Rec Class

Sometimes, you just need to draw a rectangle filled with a color inside, it's pretty useful to show a message, or for any reason and believe me, you'll need it a lot of time.

Let's take a look to the constructors. There’s two overloads, an empty one, and another one with six parameters:

  1. Brush is the color of the rectangle
  2. Point
  3. Size
  4. Name
  5. TypeGfx
  6. Visible: to identify object as its type if it is a background or Object or Top
C#
Rec box1 = new Rec(Brushes.Red, new Point(100, 100), new Size(80, 80), 
           "box1", Manager.TypeGfx.Background, true, manager);
manager.BackgroundLayer.Add(box1);

Image 11

You can add a border of the rectangle.

C#
Rec box1 = new Rec(Brushes.Red, new Point(100, 100), new Size(80, 80), 
           "box1", Manager.TypeGfx.Background, true, manager);
box1.BorderColor = Color.Black;
box1.BorderWidth = 2;
manager.BackgroundLayer.Add(box1);

Image 12

Unfortunately, I can't pass all the wiki here because there are 24 chapters and I deleted some details to make the article as short as possible "but I didn't succeed :-s"

Check the wiki for complete and detailed examples:

Nova 2g RPG project "abandoned just to test this library":

Feel free to contact me for any purpose or issue you find by leaving a comment below.

This article was originally posted at https://github.com/melharfi/MELHARFI-2D-Game-Engine

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer (Junior)
Morocco Morocco
I am someone fascinated by gaming, new technologies and programming.
My goal is to advance in programming skills.

Comments and Discussions

 
-- There are no messages in this forum --