Here I decided to write a text MMORPG C++
So, I lured you here, BUT I will repeat right away, this is not a guide to creating an MMORPG in C++. It’s kind of like my diary, where I’ll dump the development process (Yes, the project is not finished, not even close, more like it’s just started…). Why did I even create this article then? Well, when you’re a cool true programmer, I’d appreciate advice, criticism, help, likes, basically anything that can help me improve this. On the other hand, if you wanted to create something similar yourself, you might be able to avoid all the difficulties I encountered. For both the first and second goals (and in order to make it look like some work has been done), I will try to chew everything I do as accessible as possible, so let’s get started!
Contents
beginning
Where does any project begin? From the idea and the plan, of course! I will probably explain the idea in the course of the presentation, in any case it will change… I drew the plan in the form of a diagram:
Are you scared? Do your eyes hurt? Do you wish me luck (or burn in hell) and leave this article? Your reaction is justified, but I still do not have the conscience to explain what is here and how.
DB is a database that will store all the information about the project, we will return to it, but we will not stop for a long time.
Admin is a kind of world control panel, on it new objects will be created and placed in the world, as well as the necessary scripts will be written.
The world server is a server that will manage automatic changes in the world, for example (just an example, it is far from a fact that this will happen): a fire burns and later, neighboring cells start to catch fire, these are exactly the same processes that will be managed by the world server (not ready, but already started).
The client manager (or client manager) will be responsible for working with the players, through him the players will both be authorized and receive the information the client needs.
The chat will be built into the client manager (therefore in the green circle), chat moderation will also be through it.
Clients are already applications through which, in theory, users will play, the only thing left to their fate is how to interpret the information received from the manager.
DB
Database? DB! But DB? DB, DB, DB!! Oh, ok. DBMS = MySQL, why?
-
A lot of documentation.
-
Ease of installation and configuration
-
No license issues!
How to install MySQL on Windows: Timeweb Cloud step-by-step guide
Once you’ve downloaded and installed VS (or whatever you’re writing on), there shouldn’t be any problems installing and configuring MySQL. The only thing I will point out is that I have now chosen a local server, because there is only one!
Still, I’m new to MySQL, and I’m having trouble connecting it to my C++ project. However, not so much, because the documentation decides for any taste and color). And I started with VS, but it seemed to me too scary to dig into its settings, so I decided to transfer the whole process of composition to CMake (and in general, I switched to VS Code for a reason), and-and-and this is what I got:
In the MySQL Server 8.0 folder (by default it is installed in the path: “C:\Program Files\MySQL\MySQL Server 8.0”) I found the include and lib folders. I copied the include folder to the project folder, and copied libmysql.lib and libmysql.dll from the lib folder there. as a result, they are exactly in the server folder). Then I write CMakeLists.txt:
cmake_minimum_required (VERSION 3.8)#установил минимальную версию(шаблон)
project (AdminPanel)#Да начал я с админки
add_executable(AdminPanel "main.cpp")#добавил cpp файл
target_include_directories(AdminPanel PRIVATE "include")
#дабы использовать либы из include
find_library(LIBMYSQL NAMES libmysql.lib PATHS ${PROJECT_SOURCE_DIR})
#найти либу libmysql.lib и записать её абсолютный путь в LIBMYSQL
if(LIBMYSQL)#коли либа есть, то линкуем её!
target_link_libraries(AdminPanel PRIVATE "${LIBMYSQL}")
else()#коли нет - код=death;
message(FATAL_ERROR "libmysql.lib not found\n")
endif()
find_file(DLLMYSQL NAMES "libmysql.dll" PATHS $<TARGET_FILE_DIR:AdminPanel>)
#найти libmysql.dll в папке с exe файлом
if(NOT DLLMYSQL)#коли нет её там
find_file(DLLMYSQL NAMES "libmysql.dll" PATHS ${PROJECT_SOURCE_DIR})
#то ищем в корневом каталоге!
if(DLLMYSQL)#коли нашли, то копируем к exe!
add_custom_command(TARGET AdminPanel POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"${DLLMYSQL}"
$<TARGET_FILE_DIR:AdminPanel>)
else()#иначе смерть.
message(FATAL_ERROR "\nlibmysql.dll not found\n")
endif()
endif()
unset(DLLMYSQL CACHE)#удаляем переменную из кэша(надо, без этого работать не будет)
unset(LIBMYSQL CACHE)#удаляем переменную из кэшаX2
Yes, find’s are clearly superfluous here, but what’s done is done, they don’t interfere!
Admin
And I’ll start with a small MySQL performance test(or the illegitimate son of documentation and my laziness):
#include <iostream>
#include <mysql.h>
#include <string>
#include <cstdlib>
#pragma comment(lib, "libmysql.lib")
MYSQL *conn;
void exiting()//Закрыли прогу преждевременно? Не беда!
{
mysql_close(conn);
}
int main()
{
// Получаем дескриптор соединения
conn = mysql_init(NULL);
if (conn == NULL)
{
// Если дескриптор не получен – выводим сообщение об ошибке
fprintf(stderr, "Error: can'tcreate MySQL-descriptor\n");
}
// Подключаемся к серверу
if (!mysql_real_connect(conn, "localhost", "Spidery", "1322213222Mz", "World", NULL, NULL, 0))
{
// Если нет возможности установить соединение с сервером
// базы данных выводим сообщение об ошибке
fprintf(stderr, "Error: can't connect to database %s\n", mysql_error(conn));
}
else
{
std::string S = "";//В ней храним введённый запрос
while (S != "cls" && S != "close")//сам знаю, что перед закрытием
//код ещё один цикл сделает, но это тест мне плевать
{
getline(std::cin, S);//Вводим строку
if (mysql_query(conn, S.c_str()))//Отправляем запрос на сервер
{
fprintf(stderr, "Error with query\nYour input: //не вышло если
std::cout << S << '\n';//Что с запросом не так.
}
else // Если запрос успешно отправлен
{
MYSQL_RES *result = mysql_store_result(conn);
if (result) // забрать весь результат
{
MYSQL_ROW row;
while (row = mysql_fetch_row(result))//выводим каждую строку отдельно
{
std::cout << *row << '\n';
}
// пока есть строки результата(Вот такая вот матрёшка)
}
else if (mysql_field_count(conn) != 0) // коли нет результата, то и бог с ним, но вот если ошибка!!!
{
mysql_free_result(result);
fprintf(stderr, "Error: %s\n", mysql_error(conn));
}
mysql_free_result(result);
}
}
}
system("cls");//работаю в терминале VSCode, потому и очищаю его
return 0;
}
*That’s all for now, wait, believe, hope, but it’s better to write a comment and move on*