Post date: Jul 4, 2011 4:36:48 PM
Với tư tưởng hướng đối tượng, trong bước này, ta sẽ thiết kế những lớp cần thiết cho việc quản lý game.
Đối tượng đầu tiên ta thấy chính là game: lớp CGame
Về cơ bản, ta lớp CGame cần có các phương thức:
Và một số thuộc tính:
CGame.h
#ifndef __CGAME_H__ #define __CGAME_H__ namespace GameTutor { class CGame { public: CGame(); virtual ~CGame() {} virtual void Run(); virtual void Exit(); virtual void Pause(); virtual void Resume(); bool IsAlive() {return m_isAlived;} bool IsPause() {return m_isPaused;} protected: virtual void Init() = 0; virtual void Destroy() = 0; protected: bool m_isAlived; bool m_isPaused; }; } #endif
CGame.cpp
#include "CGame.h" #include "stdio.h" #include "windows.h" namespace GameTutor { CGame::CGame(): m_isPaused(false), m_isAlived(true){} void CGame::Pause() { m_isPaused = true; } void CGame::Resume() { m_isPaused = false; } void CGame::Exit() { m_isAlived = false; } void CGame::Run() { this->Init(); while (m_isAlived) { if (m_isPaused) { printf("paused\n"); } else { printf("running\n"); } Sleep(80); } Destroy(); } }
Trong ví dụ trên, ta thấy lớp CGame được thiết kế với 2 hàm thuần ảo. Điều này có nghĩa là ta không thể khởi tạo trực tiếp lớp CGame. Để sử dụng lớp CGame, ta cần tạo một lớp thừa kế từ CGame. Điều này đảm bảo cho sự tách biệt giữa lớp thư viện (CGame) và ứng dụng. Vì sao cần có sự tách biệt này?
Khi này, ta thiết kế 1 lớp mới có tên là CExample, thừa kế từ CGame:
CExample.h
#ifndef __CEXAMPLE_H__ #define __CEXAMPLE_H__
#include "CGame.h" using namespace GameTutor; class CExample:public CGame { public: CExample(): CGame() {} virtual ~CExample() {} protected: void Init(); void Destroy(); }; #endif
CExample.cpp
#include "CExample.h" #include "stdio.h" void CExample::Init() { printf("Init\n"); } void CExample::Destroy() { printf("Destroy\n"); }
Khi này, hàm main được thiết kế đơn giản như sau:
main.cpp
#include "CExample.h" int main() { (new CExample())->Run(); }