Php Web Game Development tutorial 1 (webgame + design)

Source: Internet
Author: User
Tags add time map class

1. Simple Program Framework.
Webgame program composition:
Three major parts.
The first is the data process. The second is the program. The third is art.
The data flow includes functions. Data flows can only be reflected in functions.
The data process is quite troublesome and will be discussed later.
For example, the simplest product to sell.
To implement this function.
The basic table of the product, detailed table of the product, store table, and catalog table are required. If the scalability is higher, the corresponding dual tables cannot be less.
Table problems are all simple. The key is how to use this item. In this way, the source of an item, a lot of data, the trend of the item, and a lot of data.
Finally, the data must be circled.
Circle is a difficult task. Especially when there are more functions and items. The difficulty is the Npower of 2.

If you are familiar with the design mode before bypassing the circle. This process can be simplified. The difficulty is changed from the Npower of 2 to 1.
You only need to have three virtual classes: controller, event factory, and abstract prop factory. With the addition of timer and task Editor, these two general classes are used. You can build a robust and highly scalable webgame.
In webgame, controllers are almost equivalent to pages. It is convenient to use a template technology.
The event factory is an abstract class. All events, such as working, fighting, and moving, are produced by the event factory. The interfaces are the same to facilitate the controller control. Factory mode.
Abstract item factory is an abstract class. All items, such as cities, maps, and equipment, are produced by abstract item factory. In addition, the interface is the same, the factory mode, and the combination of events and items is a bridge mode.

Art:
UI. Simple and beautiful interfaces will always benefit. Small icon. Item, map, and equipment. Should there be at least 10 in a category? Generally, hundreds of requests are required.
The program consists of five parts:
Server timer. (C language or self-configured server) Periodically executes a piece of code. This code is mainly updated based on the database data. This can be done by a C-language programmer. For C programmers, this function is quite simple. Of course, you need to write your own data processing judgment and database operations. Let the C language programmers give you standard code. Fully supports SQL statements.
You can configure the corn implementation for php. However, no matter what operating system, the minimum configuration time is 1 minute. Therefore, if you want to refresh once every second. You also need a dedicated Timer Program for processing, or the regularly executed php needs to contain sleep (). Of course, even if there is instant interaction, you can ignore the server side. Only clients on both sides of the interaction are processed. Js and ajax implementations.
Function page and function. It mainly refers to data access, judgment, and data trend.
It is easier to use abstract classes. However, subclass explosion is indispensable.
Ajax functions. Optional. Some functions that require pseudo-instant processing are required.
To make the game look cool. Use it.
Javascript Functions. (Optional) simulate data computing on the client. That is, time-related data of webgame. It is divided into two parts. Some of them are real data and are calculated by the server timer. The other part is only the initial value, which is displayed on the client. Instant synchronization is not required. You only need to simulate synchronization.
Some nice UI effects are also included. After all, it is a game.
Database. A large number of basic data tables and detailed data tables. Basic data table: for example, the initial attribute values of users from grade 1 to grade 100. Detailed data table: the specific attributes of each user.
Optimize the database as much as possible. If the structure can use 1 byte, do not use 2 bytes.

2. A detailed example.
Simply discussing the data process is a pain point.
Discussing programs without code is also a pain point.
Php + mysql is used here. Classes are not used in this example. If you have enough time, at the end of this year, I will provide a simple webgame code and core class with instant interaction to illustrate the benefits of using the design pattern.
We will discuss it in a simple webgame method. With appropriate code. It should be helpful. Please note that it is also helpful to me.
We don't consider the game playability, numerical balance, and so on. We will first consider the implementation of a simple example.
So what is the basic content of a webgame?
Database: players, maps, cities, buildings, weapons, soldiers.
Features: Login, upgrade, personal combat, fighting between soldiers, fighting with the city, building, creating weapons, and buying and selling items.
(Note: each function must correspond to one or more data tables. What is listed in the above database is only the basis of the Basic .)
First, maps, cities, and buildings.
It is believed that there can be multiple maps. The city is on the map and the building is in the city.
GEO chart
Map: Map_ID, X, Y, City_ID (city ID), description.
Map_ID indicates the id of the map. It is not an automatic number. A map is a Map_ID, which can be repeated.
City table
City: City_ID, City name, City owner, City level, City resource, description.
Building table
Build: ID, City_ID, Building Name, building grade, building function.
The GEO chart determines the location of the city, the city table determines the relevant data of the city and the owner, and multiple pieces of information in the building table belong to a city.
After the table is created, it is displayed.
A for loop. It is OK to retrieve the whole geo chart.
It is not much different from the news list of a common website. The difference is that you need to obtain the X and Y coordinates for positioning. You can use tabel or div.

Code

Copy codeThe Code is as follows: class Map // Map class
{
Var $ Map_ID;
Function Map_bg_css ($ Map_ID ){

$ This-> Map_ID = $ Map_ID;

Mysql_select_db ($ db_name, $ link );
$ SQL = "select * from map where Map_ID = '". $ this-> Map_ID. "'limit 1 ";
$ Result = mysql_query ($ SQL, $ link );
Echo "<style type =". "text". "/". "css> ";
$ Rs = mysql_fetch_array ($ result );

Echo "# map {";
Echo "position: absolute ;";
Echo "width:". $ rs [X coordinate]. "px ;";
Echo "height:". $ rs [Y coordinate]. "px ;";
Echo "z-index: 0 ;";
Echo "left: 0px; top: 0px ;}";

}

Function Map_bg ($ Map_ID ){

$ This-> Map_ID = $ Map_ID;

$ SQL = "select * from map where Map_ID = '". $ this-> Map_ID ."'";
$ Result = mysql_query ($ SQL, $ link );
While ($ rs = mysql_fetch_array ($ result ))
{
Echo "<div id = Layer_bg _". $ rs [X coordinate]. "_". $ rs [Y coordinate]. "> ";
Echo " </div> ";

}

}
}

The above is a simple map class. The code may be incorrect, which means it is correct. A group of div layers and css of these layers are generated based on the coordinates in the map table.
You can change it to table. You can also place coordinates in a field and take them as arrays.
Use

New map;
Map (N );
Where N is the map Map_ID in the map table.
Buildings in the city are similar. If you want to display it.
Now I am using a simpler map. Use coordinates to determine which graphs are needed and then display them directly. Of course there is no collision, because it is not required for the moment. As for what people move around, this article does not discuss the scope.
With maps and cities. The problem involved is the generation of resources in cities.
At this time, the City table must have fields that can be used to determine the time and quantity.
For example, when the amount of Money is generated, Action_Time is used to generate the amount of Money, and Money_time is used to generate the amount of Money.
The values of these two fields should appear in the City_base table. (That is, the city base table, corresponding values of different levels and different types of cities. This is used to fill in data for planning. After creating a table, wait for planning to have a headache. If you have multiple roles ...)
How to automatically generate resources?
We can write a time when everyone in the city changes. Or write a time when the city is initialized.

$ Now_Time = date ('Y-m-d H: I: s ');
(Description: $ starts with a variable. Php. It can be written as asp. Now_Time = Now ())
Write $ Now_Time into Money_time.

Update ("UPDATE City SET Money_time = '$ Now_Time WHERE City_ID =' $ City_ID 'LIMIT 1 ;");
$ City_ID is defined by yourself. A city. For example, $ City_ID = 1;
We assume that the amount of capital generated in the current city is 100. That is, $ Money = 100; (the specific value should be obtained from the City_base table .)
Assume that the interval is $ Action_Time, and we assume that the interval is executed every hour. That is, $ Action_Time = 3600; (the specific value is obtained based on your initialization table. It can also be obtained based on the city level or user level. You can set it on your own .)
At this time, there is a basic time. There is a basic capital output. There is an interval. Let it be executed cyclically.
As mentioned above, the server uses the C language timer. The client uses javascript.
Server. The resource timer is set to run once every 5 minutes. The error is 5 minutes. This is acceptable for web games. (The combat timer takes one minute. Of course, if the server is good enough, it can take a few seconds .)
Of course, it can be completely written in php and then configured with php corn. Now the program I am working on is directly written in php. Including any long-time Timer class, dedicated to controlling abstract events. The timer of C is useless for the moment.
What code is executed every time?
First, create a new table for the timer task. The purpose is to let the timer know which programs and data updates need to be executed. Table content, for example, city resource update. Of course, this table is optional. The advantage of the establishment is that it is convenient to deal with problems such as protection status without generating resources.

Server program:
Obtain the current server time.
Obtain the target city.
Determine the time difference between the server time and $ Money_time. (Timestamp. The specific timestamp contains a large amount of online data .)
Determine whether the time difference is greater than $ Action_Time.
If the value is greater than, the resource is updated. Update $ Money_time at the same time.
If the value is smaller than, no operation is performed.

Client Program:
Obtain the current server time.
Get $ Money, $ Money_time, $ Action_Time of the current city.
Use javascript to display the remaining time countdown and increase the amount of resources.

Triggered in special cases on the client:
The resources displayed on the client are pseudo-synchronous, so when the client uses this resource. The server needs to update the current actual resource, and the timer processing time also needs to be updated.
That is, when the client triggers a resource-related situation, the current resource is updated immediately. At the same time, the $ Money_time used in the timer is updated. In this way, resources cannot be used, or the timer repeatedly generates resources.

In general. This part of the program is very simple. The difficulty lies in the preparation of the C language timer and the preparation of the countdown to the front-end technical cipt.
C language timer, find a C language programmer, It is super simple; the front-end javascipt, there are a lot of Countdown code on the internet, find a change can be used.

CodeCopy codeThe Code is as follows: <script language = "JavaScript">
Var maxtime = here is your time difference // one hour, calculated in seconds and adjusted by yourself!
Function CountDown (){
If (maxtime> = 0 ){
Minutes = Math. floor (maxtime/60 );
Seconds = Math. floor (maxtime % 60 );
Msg = "your text description" + minutes + "Minute" + seconds + "second"; // dynamically display the remaining time.
Document. all ["timer"]. innerHTML = msg;
// If (maxtime = 3) document. all ["timer"]. innerHTML = '3 seconds left! ';
-- Maxtime;
}
Else {
ClearInterval (timer );
Document. all ["timer"]. innerHTML = 'time ';
}
}
Timer = setInterval ("CountDown ()", 1000 );
</SCRIPT>

<Div id = timer> </div>

This is the code found online. You can use it with a slight modification. The countdown is displayed. You can also display the resource increase information.

Operate the mysql database in C language.

CodeCopy codeThe code is as follows: // TODO: Add your control notification handler code here
Bool bRes = m_dbConn.Connect ("database IP Address", 3306, "username", "password", "Database Name ");
If (! BRes)
{
AfxMessageBox ("connect fail ");
Return;
}

String strSql = "select * from city limit 1"; // This section is used for all display or value classes. The SQL statements in the middle can be constructed by yourself.
ResultSet * rs = m_dbConn.ExecuteQuery (strSql );
While (rs-> Next ())
{
String str = rs-> GetString ("username ");
AfxMessageBox (str. c_str ());
}
/*
StrSql = "update city set money = money + 100 where City_ID = 'xxx'"; // use this section for all additions, deletions, and updates. The SQL statements in the middle can be constructed by yourself.

BRes = m_dbConn.ExecuteUpdate (strSql );
If (! BRes)
{
AfxMessageBox ("ExecuteUpdate fail ");
}
*/
M_dbConn.Close ();

The main function of the timer.
Void CBeiLiDlg: Go ()
{
While (true)
{
// AfxMessageBox ("go ");

Sleep (5*1000); // millisecond. Timer refresh time.
}
}

Of course. The C code here cannot be used directly. Only part.
The new method is to use the php Timer class to take charge of the front-end, after the time arrives, call ajax to complete the execution. The background regularly executes the php timer-type special processing function to handle situations such as front-end disconnection and abnormal execution at front-end.

If our new game is available at the end of this year. I can publish this class without technical knowledge, but it is clever.

Map, city, basically have.
Next is the building in the city.
The increase in resources mentioned above is actually more accurate in construction. However, the classification and numerical values of buildings are much more complex. That is the question of planning.
On the building, we only talk about the construction effect of one front-end.
Of course, this effect is dispensable. You can display a news list directly, and add a countdown.
The result is that after the point is built. Call an animated image without refreshing the page. After the time is reached, the system automatically converts the image to another image.

CodeCopy codeThe Code is as follows: <script language = 'javascript '>
Function xiujian ()
{
Top.abc.doc ument. getElementById ('Id of the image where the front-end building is located '). src = 'address of the constructed building image ';
// Display the building image after construction. You can add the background time to judge. Abc indicates the id of the layer where the building is located,
}
Function xiujian1 ()
{
SetTimeout ('xiujian () ', 5000); // The animation time is 5 seconds. You can also add time judgment here. When the animation is not completed in time, call the animation again.
}
Function donghua ()
{
Top.abc.doc ument. getElementById ('Id of the image where the front-end building is located '). src = 'address of the building animation'; // The building animation is displayed.
}
Donghua ();
Xiujian1 ();
</Script>

For more information, see. If you want to consider compatibility with multiple browsers, use prototype. js. If you only need ff and ie. Therefore, jqury. js
Or try to write it by yourself. Because K prototype. js is not small.
In the background, change the time to and add the resource code to time to add or update the building. Add N tables ..
The new method is to add an event subclass.

Basic Architecture table: outputs, types, images, and so on ..
Building detail table: the city in which the building belongs. It can be associated in the city table. Different association methods have a great impact on the program. All join methods are supported, but once the join method is determined, it is best not to change it.
Now there is a building. Similar timing methods can be used to work, recruit, and so on.
Battle,
Parameters of a soldier: Soldier, quantity, attack, defense, and so on.
Temporary combat table: Who's soldiers, who hits, departure time, combat time, and combat results.
The words here are simple. The actual table is more complex.
In webgame, the combat process is divided into two types. One is to provide parameters for both sides. When the time is reached, the calculation result is based on the formula. One is semi-real-time or instant combat, which can be used while taking medicine.

The first process.
Click to send troops. At this time, the parameters, departure time, and arrival time of the troops are recorded in the combat temporary table.
In the timer, process the combat part and determine whether the time is reached. When the start time is reached, the parameters of the attacked troops are obtained. Then, the results are calculated using several formulas. Processing results, such as who is down, how much is down on the battlefield, and who is in the city. A lot of judgments and updata. (The timer processing here is similar to the timer processing for obtaining resources .)
Finally, the results are sent to both parties. (A short message system is involved .)

The second process.
Point attack. Process the data immediately. It is easy to do this by hitting the npc. Players can fight against each other and treat the attacked players as npc players.
Two or more people fought in real time. Ajax is required. Currently, there is no technical or theoretical problem, and there is no actual code to write, so it is hard to say.

Now, we are technically sure that this can be implemented well.
A simple formula can be used for both battles:

Intval (sqrt ($ User_ B _AP)-sqrt ($ User_A_DP ));
Under the root number, attack-under the root number, defense = damage.
The formula will certainly be a lot more complicated when I write it, but it's a headache. Let's do it with planning.
The specific combat parameters are not considered by the program.
The program only needs to consider getting data from data table A and saving it to temporary table B. Then, when the time is reached (implemented by timer), data is obtained from data table C, calculated by formula, and temporary table B is deleted or saved to another place for backup.
The idea here is actually the Timer class.
What are the data? Seek for planning. How many tables are there? Seek for planning. Combat formula? Seek for planning.
There are maps, cities, buildings, soldiers, after the battle, the emergence of props is necessary.
Why?
What can a city do? Generate resources, generate money, and generate troops.
What do soldiers do? You can grab resources and money.
What do resources and money do? Buy items.
What do I do when I buy a prop? It is better to grab resources and money.
(At the same time, the resources will be consumed when the resources are snatched)
This is a simple loop. It is a circle, although this circle is very small. Some of them think very well, that is, they cannot be circled, and that makes no sense.

First, a basic table of items is required. Automatic ID, item type, item property, description. In terms of item processing, you can add more fields in the player table to follow the player. You can also create a detailed table for each item. It is implemented in a similar way as a backpack.
Two methods are available: Array Storage and horizontal table Storage. All of them are quite troublesome. However, we should consider the circulation and sale of items. It is worthwhile to use a backpack. The following functions.
Store. Auction House. Basically, it is similar to General website applications. But the product becomes a prop in the game. Currency is game currency.

Iii. Summary
In the small example above, the train of thought is basically perfect and there is no problem. Only a small part of the program code can be truly understood. Other programs should not be a problem.
What is important about webgame is that data streams are circled and playability.
Now we will talk about the robustness of the program and the clarity of the data stream.
The above functions are not enough to be used. That is, there is no playability, and it makes no sense to do it.
However, it is still difficult to do it.
There are too many things involved in the game. Even a very simple game, even webgame looks very simple, or even actually very simple; it is very difficult to make it.
People who have no experience in webgame development come to plan webgame or develop webgame. It is easy. There are actually a few major features. The idea is also easily circled.
It is actually a very simple function, when it needs to be circled; when it needs to interact. This function is not simple, but complex and quite complex.
This is when you do not quite understand the design model, if you are proficient in the design model, then the function will be simple.

In particular, if you want to create a product with sufficient playability and market-oriented capabilities, the initial thinking is very simple and the functions are simple. But when you actually plan, when actually programming. A large amount of data and values need to be processed, and a large amount of interaction needs to be processed. At this time, the beginning is simple and complicated. Although from the procedural perspective, the technical content is not high.
To be more accurate, it is complicated and cumbersome.

A good plan is to list data tables and clearly list data in front of you. There are not many such plans.
Of course, he is not necessarily accurate, but a programmer can understand his meaning more accurately.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.