Search…

Áp Dụng Kỹ Thuật OOP trong Quá Trình Xây Dựng Framework Dựa trên Thư Viện SDL

02/11/20202 min read
Áp dụng kỹ thuật lập trình - OOP trong quá trình xây dựng Engine Game bằng thư viện SDL (Simple DirectMedia Layer).

Để khởi tạo của sổ bằng thư viện SDL cần có những yếu tố sau:

  • Kích thước của cửa sổ.
  • Tên tiêu đề của cửa sổ.
  • Một con trỏ kiểu SDL_Window để quản lý cửa sổ.

Cách hiện thực

Đầu tiên, khởi tạo một class để chứa các thông tin của cửa sổ, đặt tên class đó là MyWindow.

Trong phần khai báo class:

#ifndef __MY_WINDOW_H__
#define __MY_WINDOW_H__

#include "SDL.h"

class MyWindow
{
public:
	MyWindow();
	MyWindow(const char* name, const int& width, const int& height);

	~MyWindow();

private:
	int		m_ScreenWidth;
	int		m_ScreenHeight;
	char*		m_pTitle;
	SDL_Window*	m_pWindow;
};


#endif // !__MY_WINDOW_H__

Class MyWindow, gồm các thuộc tính sau:

  • m_ScreenWidth là chiều dài của cửa sổ màn hình.
  • m_ScreenHeight là chiều cao của cửa sổ màn hình.
  • m_pTitle là tên của cửa sổ màn hình.
  • m_pWindow là con trỏ quản lý cửa sổ màn hình.

Trong phần định nghĩa class:

MyWindow::MyWindow(const char* name, const int& width, const int& height)
{
	m_pTitle	= new char[SDL_strlen(name) + 1];
	SDL_strlcpy(m_pTitle, name, SDL_strlen(name) + 1);
	m_ScreenWidth	= width;
	m_ScreenHeight	= height;

	//Initializes the subsystems
	if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
	{
		SDL_Log("Unable to initialize SDL %s\n", SDL_GetError());
		return;
	}

	// Create window
	m_pWindow = SDL_CreateWindow(m_pTitle,
		SDL_WINDOWPOS_UNDEFINED,
		SDL_WINDOWPOS_UNDEFINED,
		m_ScreenWidth,
		m_ScreenHeight,
		SDL_WINDOW_OPENGL);

	if (m_pWindow == nullptr)
	{
		SDL_Log("Could not create windows: %s \n", SDL_GetError());
		return;
	}

	// Delays 10 seconds
	SDL_Delay(10000);
	//Destroy a window
	SDL_DestroyWindow(m_pWindow);
	//This function cleans up all initialized subsystems
	SDL_Quit();
}

Kiểm tra và kết quả

Để kiểm tra class System có hoạt động đúng hay không, tạo file main.cpp với đoạn code như sau để kiểm tra:

#include <Windows.h>
#include "MyWindow.h"

int WINAPI WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int nCmdShow)
{
	MyWindow*	window = new MyWindow("STDIO - MY WINDOW", 400, 320);
	delete window;
}

Tiến hành chạy chương trình, thu được kết quả như sau:

ss_1

* Nếu chạy chương trình mà xuất hiện lỗi như bên dưới, copy SDL2.dll trong thư mục SDL2/lib/x86 vào thư mục Debug của chương trình và chạy lại.

ss_2

Code demo

STDIO_Example_V2013

IO Stream

IO Stream Co., Ltd

30 Trinh Dinh Thao, Hoa Thanh ward, Tan Phu district, Ho Chi Minh city, Vietnam
+84 28 22 00 11 12
developer@iostream.co

383/1 Quang Trung, ward 10, Go Vap district, Ho Chi Minh city
Business license number: 0311563559 issued by the Department of Planning and Investment of Ho Chi Minh City on February 23, 2012

©IO Stream, 2013 - 2024