A short article on writing server-side browser-based RPG games

By Boyan Yankov

1. Introduction

This article will focus on the basic techniques and the main technologies used in writing a server-side browser-based RPG game, also known as MMORPG (Mass Multiplayer Online Role Playing Game).

This article may be of interest to you if you intend to write such a game or if you are interested in the technologies, techniques and the process of writing a browser-based game, or you have an interest in learning basic web programming, or if you want to see a practical aspect of web programming before you start learning or if you are just curious. However, if you only need to install a downloaded free browser-based RPG, this article will not explain how to do this and you would better read the game documentation. Not all of the used technologies, programming languages and code will be explained. If you need further information use the corresponding manuals and google. I do not take any responsibility for the consequences of using, not using or misusing the information given here. I do not give any guarantee and do not promise any free support.

I assume that you know basic HTML and the main concepts of the Internet.

The type of game I will consider, known as MMORPG, is played using a web browser and an internet connection. Its interface is a webpage. There are no or almost no visual effects and animations to represent the game action. Instead the player sees text and pictures. The most important elements of such a game are the tactics the player uses to overcome his enemies (humans and/or robots) or quests and to progress in the game. There are many good examples for this type of game on the internet. The one I will give is my game: http://www.IgrataBG.com. Take a look at it – this and more is what you will be able to do if you read this brief article and then learn the technologies used (without the design)

2. Introducing the technologies

In a server-side webgame you need a web server (Apache, ISS, etc.), a server side language (PHP, ASP, PERL/CGI, JSP, etc.) to perform the calculations, to make connections to the database and to dinamically generate HTML code, a RDBMS (relational database management system) to store the game data (MySQL, Postgre SQL, Microsoft SQL Server, Oracle, etc.). Of course for a more serious game you will need a graphics design tools (Adobe Photoshop, GIMP, etc.) and good-looking and functional layout with CSS, but I will not cover these topics here.

For the purposes of this article we will use free and popular technologies: Apache web server, MySQL database management system and PHP server side language. In the next chapters I will examine them in more details. I will not strictly observe the new (X)HTML standards, but will give a simple and functional code.

3. The idea of a game

Before you start writing a game, you should have a clear idea of the final result. The more time you spend thinking before you write the code, the less time you will spend writing. This concerns developing every complex programming project.

My idea is simple: a multiplayer strategy game with battles. The player will control a single character in a small medieval city.

This is not enough to go to the next chapter. You should decide what (and how exactly) will happen in the game. After days spent in thinking I have decided that the player will have the following basic stats: attack, defense, life, vitality and experience (in a real game you will probably need to add columns with their maximum values). A fight between two players or a player and a bot (robot) will consist of calculating and comparing stat points and random numbers. I have invented my own simple formula for battles and for game progress (and if you make a game, you should do so, too).

4. Designing the database

As I said in the previous chapter, every character or robot in the game will have the following stats: attack, defense, life, vitality and experience. In the databases data is held in tables. A table consists of rows and columns. For our game example we will use one simple table. We will represent every stat as a column in a table and every player as a row.

To distinguish one player from another we will give the players unique names. The name will be a separate row in our table. In databases we use columns, which contain unique values, to distinguish the rows (in our case the players) and we call these columns primary keys. We will also add a column to store the player’s password.

For RDBMS (Relational Database Management System) we will use MySQL that implements the SQL language syntax. I suppose that you will install it and run it yourself and also configure it to work together with Apache and PHP (if you do not know how, ask google). First we will create database to store the tables in. We use this SQL command (we only write "create database test_game;"):

mysql> create database test_game;
Query OK, 1 row affected (0.02 sec)

Then we display the databases to ensure the new one is properly created and select the new database:

mysql> show databases;
+------------------------+
| Database               |
+------------------------+
| information_schema     |
| mysql                  |
| test_game              |
+------------------------+
3 rows in set (0.01 sec)
mysql> use test_game;
Database changed

Now we can create our table with the create table command which has the following syntax:

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name (create_definition,...) [table_option ...]

create table players (name varchar(32) not null, pass varchar(255) not null, life int, attack int, defence int, vitality int, experience bigint, primary key (name));

In the create table command as a create definition we write the definitions of the columns. We define a column with its name and type: name varchar(32) – a column with name "name" and type "varchar(32)". You can read about the data type in MySQL in the corresponding manual.

We are ready with our database and now will try to insert some data in it. We will create a player with mysql. We use the SQL command INSERT to insert data:

mysql> insert into players values('test_player','179ad45c6ce2cb97cf1029e212046e81',20,10,10,20,0);
Query OK, 1 row affected (0.01 sec)

The first value "test_player" is the player’s name. The strange string "179ad45c6ce2cb97cf1029e212046e81" is a MD5-coded hash from the player’s password, in our case "testpass". The other values are the player’s stat points.

Now we will read from the table using the SELECT command to ensure the information is recorded correctly in it:

mysql> select * from players;
+-------------+------------------------------------+------+--------+---------+----------+------------+
| name        |pass                                | life | attack |defence  | vitality |experience  |
+-------------+------------------------------------+------+--------+---------+----------+------------+
| test_player | 179ad45c6ce2cb97cf1029e212046e81   | 20   | 10     |     10  |     20   |          0 |
+-------------+------------------------------------+------+--------+---------+----------+------------+
1 row in set (0.01 sec)

Now, after we have created a simple and not very professionally looking database we can move to the next chapter.

5. Programming PHP scripts

The thing you should remember about your PHP files is that they are plain text files, usually with the .php extension. They are interpreted by a program, called the PHP parser and located on the web server. The code in these files may contain html, javascript, php and other languages (but also may not). The php part of the code starts with "<?php" and ends with "?>".

Put these files in the htdocs directory of your Apache server or if you use web hosting in your public_html directory (probably, but not always). To get these files properly interpreted you should always call them from the web server and not right-click them and open them with the web browser. Write the file’s web address (URL) in the web browser. The address should look like this: http://localhost/testfile.php or http://192.168.0.123/testfile.php or http://yoursite.com/testfile.php

Let’s now start creating php scripts. Our first script will display the players in the database ordered by their experience. Create a blank file view_players.php in your web server’s directory and then put this code in it:

<?php

function connectdb()
{
  $conn=mysql_connect("localhost","root","pass") or die("Unable to connect to the database!");
  mysql_select_db("test_game",$conn) or die("The database was not found!");
  return $conn;
}

function disconnectdb($conn)
{
  mysql_close($conn);
}

?>
<html>
<body>
  <table border="1">
    <tr>
      <th>Name</th>
      <th>Experience</th>
    </tr>
<?php
  $sql_command='select name,experience from players order by experience desc;';
  $conn=connectdb();
  $result=mysql_query($sql_command) or die("Unable to extract data from the database!");
  disconnectdb($conn);

  while ($player=mysql_fetch_array($result))
  {
    echo("<tr><td>$player[name]</td><td>$player[experience]</td></tr>");
  }
?>
  </table>
</body>
</html>

In this file on line 4 replace "localhost","root","pass" with the address of the mysql server (probably localhost), the apache user and his password.

I will try to explain this code briefly. You can find details about the used php functions and syntax at http://php.net. The script will generate a HTML page and the browser will display a table with the players' names and experience.

The two functions we declare at lines 2 to 11 are used to make a connection to the database and to disconnect. They use the PHP functions mysql_connect(), mysql_select_db(), mysql_close() which are used to handle connections to a MySQL database.

The second PHP segment (lines 20-30) displays the information in the table. It calls the previously declared functions to handle the connection and the PHP function mysql_query(), used to send SQL commands to the database. I will not explain the SQL commands here, they are almost the same as these used in the previous chapter. The result returned by mysql_query() is not very convenient to use, so we convert it into an array with mysql_fetch_array(). The indexes of the array are the column names and its elements are the data cells. We display the content of the array with the echo command.

Now it is time to test the php script by writing in the browser’s address bar something like http://localhost/view_chars.php, where you may need to replace localhost with the web server’s address. If you see a table with one player you can move to the next chapter.

6. Building a working example

The aim of this chapter is to give you a simple working example that has a text menu with two options implemented: creating heroes and viewing player rankings.

Let’s start from the main page. It will be a simple static HTML page with two links. Create a blank page named index.php and then copy this code in it:

<html>
<body>
  <h1>Test Game</h1>
  <p /><a href="new_player.php">Create a New Hero</a>
  <p /><a href="view_chars.php">Player Rankings</a>
</body>
</html>

If you open the index file now the Player Rankings part will work because of the script we created in the previous chapter. Now let’s write the form for creating players. Our form will contain only two fields: name and password of the player. It is a HTML form which only submits the data to a PHP script.

<html>
<body>
  <h1>Creating a New Hero</h1>
  <form action="new_player-action.php" method="post">
    <p />Name: <input type="text" name="name">
    <p />Pass: <input type="password" name="pass" >
    <p /><input type="submit" value="OK">
  </form>
</body>
</html>

The PHP script used to create a hero has the filename new_player-action.php and uses the query we used in chapter four to insert a player into the table. The database functions are exactly the same as the ones used in view_players.php. The new thing is the way to access the data from the HTML form. We used the post method method to transmit data (get method is also possible) and the received data in our script is recorded in the $_POST[] array. The indexes of the array represent the form field names and the values of the elements are the values from the form fields. Now let’s create the new_player-action.php and copy this code in it:

<?php
function connectdb()
{
  $conn=mysql_connect("localhost","root","secure33") or die("Unable to connect to the database!");
  mysql_select_db("test_game",$conn) or die("The database was not found!");
  return $conn;
}
function disconnectdb($conn)
{
  mysql_close($conn);
}
?>
<html>
<body>
  <h1>Creating a New Hero</h1>
<?php
  $name = $_POST[name];
  $encoded_pass = md5($_POST[pass]);
  $sql_command="insert into players values('$name','$encoded_pass',20,10,10,20,0);";
  $conn=connectdb();
  $result=mysql_query($sql_command) or die("Unable to insert data into the database!");
  disconnectdb($conn);
?>
  <p /><a href="index.php">Back to the Main Page</a>
</body>
</html>

7. Things to be done

This was the very beginning of writing such a game. A real game will need a full login system, a design, a layout, a gameplay, a hacking protection, etc. If you need some friendly help or advice, or just want to talk, you are welcome at the forum: http://forum.IgrataBG.com