Creating a Game Class in SFML / C#

In this post, we will organize our game code first. To do this, we will use some OOP techniques.  Finally, we will be able to organize our game easily

We ran the project successfully in the previous post. But it's not a good implementation for game development. Normally, the main function should contain very few lines of code. Also, a compelling factor in terms of code management. Therefore, we are going to create a separate class called Game. Let's create it Game.cs file in shmup console application:

Let's write the Game class like in the code below:

using SFML.Graphics;
using SFML.Window;

namespace shmup {
    class Game
    {
        private const int WIDTH = 640;
        private const int HEIGHT = 480;
        private const string TITLE = "SHMUP";
        private RenderWindow window;
        private VideoMode mode = new VideoMode(WIDTH, HEIGHT);
        
        public Game()
        {
            this.window = new RenderWindow(this.mode, TITLE);
            
            this.window.SetVerticalSyncEnabled(true);
            this.window.Closed += (sender, args) => {
                this.window.Close(); 
            };
        }

        public void run() 
        {
            while(this.window.IsOpen)
            {
                // handle events
                // update the game
                // draw the game              
            }
        }
    }
}
I haven't written any other methods yet, but we will. Sol let's write them:
...
        public void run() 
        {
            while(this.window.IsOpen)
            {
                this.handleEvents();
                this.update();
                this.draw();            
            }
        }

        private void handleEvents()
        {
            this.window.DispatchEvents();
        }
        private void update() {}

        private void draw() 
        {
            this.window.Clear(Color.Blue);
            this.window.Display();
        }
    }
}
Finally, we can use our Game class in the main function. So let's do it:
namespace shmup
{
    class Program
    {

        static void Main(string[] args)
        {
            Game game = new Game();
            game.run();        
        }
    }
}
If we run this project that should be running a window full color as blue.

No comments:

Post a Comment