Introduction to PHP Web game development Tutorial One (webgame+design) _php Example

Source: Internet
Author: User
Tags map class square root time interval

a simple procedural framework.
Webgame Program Composition:
Three parts.
The first is the data flow. The second is the procedure. The third is art.
Among them, the data flow includes the function. The data flow can only be reflected in the function.
The data flow is quite troublesome and is discussed later.
such as the simplest selling and buying products.
To implement this feature.
Then you need a product base table, product detail table, store table, backpack table. If the scalability is more strong, the corresponding double table is not the least.
The questions on the table are simple. The key is what is the use of this item. This source of goods, a lot of data, the direction of goods, is a lot of data.
Finally, these data have to be circled in a circle.
It's a difficult thing to circle around. Especially when there are more features and props. The difficulty is 2 N Times Square.

Before you circle, if you are more proficient in design mode. Then the process can be simplified. The difficulty is changed from 2 N to 1.
Only need to have controller, event factory, abstract prop factory these three virtual classes; plus timer, Task Editor, these two generic classes. To build a robust, highly scalable webgame.
In Webgame, the controller can almost equate to a page. Easy to use a template technology is very convenient to deal with.
An event factory is an abstract class in which all events, such as working, fighting, and moving, are produced by the event factory. And the interface is the same, convenient controller control. Factory mode.
Abstract props Factory is an abstract class, all props, such as cities, maps, equipment, etc., are produced by the abstract props factory. And the interface is the same, Factory mode, the combination of events and props is a bridging mode.

Art:
Ui. It's always good to have a nice, neat interface. Small icons. Props, maps, equipment. A class of at least 10, right? In general, hundred is needed.
The program is divided into 5 parts:
Server timer. (c language or set your own server) to periodically loop through a piece of code. And this code is mainly based on the data of the database to update. This can find a C language programmer to do. For C-language programmers, this function is quite simple. Of course, the specific processing data of the judgment and operation of the database, you need to write yourself. Let the C-language programmer give you a piece of standard code on the line. Full support for SQL statements.
PHP, you can configure the corn implementation. However, regardless of the operating system, the minimum configuration time is 1 minutes. So if you want to deal with 1 seconds to refresh the situation. You also need a special timer program to handle, or a timed execution of PHP needs to include sleep (). Of course, even with instant interaction, you can ignore the server side. A client that handles only the sides of the interaction. JS and Ajax implementations.
function page, function function. The main is data access, judgment, data trend.
It's easier to use abstract classes. But the explosion of the subclass is indispensable.
Ajax functions. (optional) Some features that require pseudo instant functionality are used.
To make the game look cool. Use it.
JavaScript functions. Optionally, simulate the client's data calculations. That is, Webgame's time-related data. is divided into two parts. Part of the real data is computed by the server-side timer. The other part is only the initial value, which the client displays. No immediate sync required, just simulate synchronization.
It also includes some nice UI effects. It's a game, after all.
Database. A large pile of basic data tables and detailed data tables. Base data table: For example, the property initial value of a user of level 1 to level 100. Detail data table: specific attributes for each user.
database, optimize as much as possible. The 1-byte structure can be used with 2 bytes.

second a detailed example.
Simply discussing the data flow is a painful thing to do.
It is also more painful to discuss a program without giving it to code.
This is a php+mysql. At the same time, this example does not use the class. At the end of this year, I will provide a simple webgame code with instant interaction and a core class to illustrate the benefits of using design patterns.
Let's talk about it in a very simple, webgame way. With the appropriate code. Should be of some help. The shortage of places also please point out that to me personally is also helpful.
We do not consider the game's gameplay, numerical balance and so on. Let's consider the implementation of a simple example first.
So what is the basic content of a webgame need?
Database: Players, maps, cities, buildings, weapons, soldiers.
Functions: Landing, upgrading, personal fighting, fighting between soldiers, fighting with the city, building buildings, building weapons, buying and selling props.
(Note: Each function must correspond to 1 or more data tables.) The database listed above is just the foundation of the Foundation. )
The first is the map, the city, the architecture.
It is believed that the map can have more than one, the city on the map, the building in the city.
Ground chart
map:map_id, x-coordinate, y-coordinate, city_id (city ID), description.
Where map_id refers to the ID of the map. not automatically numbered. A map is a map_id and can be repeated.
City tables
city:city_id, city name, city owner, city rank, city resources, description.
Building table
build:id,city_id, building name, building grade, building function.
Among them, the map table to determine the location of the city, the city table to determine the relevant data and all the people, building a number of information in the table belong to a certain city.
After the table is built, it is displayed.
A For loop. Take the whole chart out and just OK.
It's not much different from the news list on a regular website. The difference is that you need to get the x and y coordinates positioned. You can use Tabel or div.


Code

Copy Code code as follows:

Class map//Map Classes
{
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 very simple map class. The code may not be correct, meaning it is correct. Based on the coordinates in the map table, a set of div layers and CSS for this group of layers are generated.
You can change to table. You can also put the coordinates in a field, and take the form of an array.
When used, use the

New map;
Map (N);
where n is the map table map_id.
The buildings in the city are similar. If you want to show it.
On the map, the way I use it is simpler. Use the coordinates to determine which graphs are needed and then display them directly. Of course there is no collision or anything, for the time being does not need. As for the characters walking around what is not covered in this article.
With the map and the city after. The problem involved is the generation of resources in the city.
At this point, the city table needs to have the time and quantity to judge the field.
For example: The amount of money to generate funds, the time spent to generate funds Action_time, the last time to generate funds Money_time.
The values of these two fields should appear in the City_base table. (That is, the urban base table, different grades, different types of cities of the corresponding values.) This is to plan to fill in the data used, after building a table to wait for planning to headache bar. If you have a number of jobs ... )
How do you automatically generate resources?
We can write a time when all the city changes. Or write a time when the city is initialized.

$Now _time=date (' y-m-d h:i:s ');
(Note: $ begins with the meaning of a variable.) PHP has the Ritter. If it is ASP words can be written. Now_time=now ())
Write the $now_time into the money_time.

Update ("Update city SET money_time= ' $Now _time WHERE city_id= ' $City _id ' LIMIT 1;");
$City _id is your own definition. Refers to a city. such as: $City _id=1;
We assume that the current city generates a capital amount of 100. That is $money=100 (the specific value, should be taken out by the City_base table.) )
Assuming that the interval is $action_time, we assume that it is executed once per hour. That is $action_time=3600 (the exact value is obtained from your initialization table). can also be obtained according to the city level or the user level. Anyway, whatever you want to set it. )
At this point, there is a basic time. There is a basic capital production. There's a time interval. Let it loop and execute it.
As mentioned above, the server uses the C language timer. The client uses JavaScript.
Server, the resource timer is set to execute once in 5 minutes. So our error is 5 minutes. For web games, it's acceptable. (The timer for the fight is 1 minutes.) Of course, the server is enough cattle, a few seconds can be. )
Of course, you can write completely PHP, and then configure the PHP corn. Now I am doing the program is directly written in PHP. Includes any length of time timer classes, specifically for the control of abstract events. C's timer is useless for the time being.
What code does it execute every time?
The first step is to create a new Timer task table. The goal is to let the timer know what programs and data updates are needed. Table content such as: Urban resource update. Of course, this watch is not to be used. The advantage of the establishment is that it facilitates the handling of issues such as protection without resource generation.


Service-Side programs:
Gets the current server time.
Get the current need to update the city.
Determine the time difference between the server and the $money_time. (Time stamp, specific time stamp online information is full.) )
Determine whether the time difference is greater than $action_time.
is greater than, the resource is updated. Update $money_time at the same time.
is less than, there is no action.

Client program:
Gets the current server time.
Get the $money of the current city, $Money _time, $Action _time.
Use JavaScript to display the countdown to the rest of the time, and the increased amount of resources.

Client Special case TRIGGER:
Because the resource situation displayed by the client is pseudo synchronization, when the client uses the resource. The service side needs to update the current actual resources, and the time that belongs to the timer processing needs to be updated.
That is, the current resource is updated immediately when the client triggers a resource-related situation. Also update the $money_time that will be used in the timer. This will not cause, see the resources are not used, or the timer repeatedly generate resources.

Generally speaking. This part of the program is very simple. Difficulties in the production of C language timer, as well as the Javascipt countdown to the front desk.
C language Timer, find a C language programmer, super simple, the front of the Javascipt, the Internet has a lot of countdown code, find a change can be used.

Code
Copy Code code as follows:

<script language= "JavaScript" >
var maxtime = Here is your time difference///one hours, calculate by the second, own adjustment!
function Countdown () {
if (maxtime>=0) {
minutes = Math.floor (MAXTIME/60);
seconds = Math.floor (maxtime%60);
msg = "Your text description" +minutes+ "minutes" +seconds+ "seconds";//animate the remaining time.
document.all["Timer"].INNERHTML=MSG;
if (MaxTime = 3) document.all["timer"].innerhtml= ' only 3 seconds left! ';
--maxtime;
}
else{
Clearinterval (timer);
document.all["Timer"].innerhtml= ' time to ';
}
}
Timer = SetInterval ("Countdown ()", 1000);
</SCRIPT>

<div id=timer></div>

This is the code found on the Internet. It can be used for a slight modification. Here just shows the countdown. The increase in resources can also be shown instead.

C language Operation MySQL database.

Code
Copy Code code 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";//all display or value classes use this paragraph. The middle SQL statement can be constructed itself.
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 '";//all additions, deletions, updates are used, and the middle SQL statements can be constructed themselves.

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);/Ms. Timer refresh time.
}
}

Of course. The C code here cannot be used directly. Just part of it.
The new approach is to use the PHP timer class to take responsibility for the foreground and time to invoke Ajax execution completion. Backstage through the regular execution of the PHP timer class special processing functions, handling the front drop line, the front desk is not properly implemented and so on.

If our new game can be online by the end of this year. I can expose this class, no technical content, but very clever.

The map, the city, basically has.
Then there are the buildings in the city.
The above mentioned resources increase, in fact, positioning in the construction of more accurate. But the classification and numerical value of the building will be much more complicated. That's a matter of planning.
Building, only to talk about the construction of a front desk effect.
Of course, this effect is optional. You can just give a display of similar news listings and add a countdown.
The effect of the display is that after the point is built. Do not refresh the page and transfer an animated picture. and automatically converted to other pictures after the time.


Code
Copy Code code as follows:

<script language= ' JavaScript ' >
function Xiujian ()
{
Top.abc.document.getElementById (' The ID of the picture at the front building location '). src= ' The image address of the building after construction ';
Shows the construction pictures after construction. Can add background time to judge. Where ABC is the ID of the building's floor,
}
function Xiujian1 ()
{
SetTimeout (' Xiujian () ', 5000);//Animation time 5 seconds. Time judgment can also be added here. When the time is not finished, continue to invoke the animation.
}
function Donghua ()
{
Top.abc.document.getElementById (' The ID of the picture in the location of the foreground building '). src= ' The address of the building animation ';//show the build animation.
}
Donghua ();
Xiujian1 ();
</script>

Incidentally. If you want to consider multiple browser compatibility, then use Prototype.js. If you only need FF and IE. Then use and jqury.js
or write as much as you could. Because the 120k prototype.js is not small.
The background section, the time to add resources to the code, to time to, add or update the building on the line. Add n tables again.
The new method is to add an event subclass.

Building base table: output, type, picture, etc...
Building Detail table: which city it belongs to, can be associated in the city tables. Different ways of associating can have a big impact on the program. All associations are OK, but once the association is determined, it is best not to change it.
And now there's the building. With a similar timing, working, recruiting, etc. can be achieved.
Fight
The parameters of the soldiers: arms, quantity, attack, defense and so on.
Combat temporary table: Who's the soldier, hit who, departure time, combat time, combat results.
Here's a few words to be simple. The actual table is a bit more complicated.
In Webgame, the battle process is divided into two kinds, one is to give the parameters of both sides, the time, according to the formula to calculate the results. One is a half-instant or instant battle that can be played with the skill of a drug-sipping side.

The first process.
Point to send troops. At this point, the soldier's parameters, departure time, arrival time, are recorded in the Combat temporary table.
In the timer, deal with the part of the battle and judge whether the time is up. At the time of the fight, the parameters of the soldiers of the attacking party are obtained. The results are then calculated through several formulas. Deal with the results, such as whose soldiers hang how much, the battlefield dropped how much money, the city was robbed by WHO. A whole bunch of judgments and updata. (The timer processing here is similar to the timer processing for obtaining resources.) )
Finally, the results were sent to both parties. (It also involves a short message system.) )

The second process.
Point attack. The data will be processed at once. Play NPC well. Players can also treat the attacked player as NPC.
Two or more people fighting in real time. Need to use Ajax. At present technically and theoretically is no problem, not actually write code, so it is difficult to say.

Now, the technology has been determined to be a good implementation.
Very simple formula, both battles can be used:

Intval (sqrt ($User _b_ap)-sqrt ($User _a_dp));
Under the root of the radical attack-the square root defense = injury.
Specific writing, the formula will certainly be a lot more complicated, but this headache, or to the planning to do it.
The specific parameters of the battle are actually not considered by the program.
The program only needs to consider obtaining data from datasheet A and depositing it in temp table B. Then when the time comes (through the timer), and then from datasheet c to obtain data, through the formula calculation, finally delete temporary table B or save temporary table B to another place backup.
The idea here is actually the timer class.
What are the data? Find a plan to. How many tables are there? Find a plan to. Combat formula? Find a plan to.
There are maps, cities, buildings, soldiers, fighting, the appearance of props is necessary.
Why, then?
What can you do with a city? Generate resources, generate money, generate soldiers.
What do you do with a soldier? Can Rob Resources, Rob Money.
What do resources and money do? Buy props.
What do you buy props for? Better rob the resources and rob the money.
(At the same time, Rob Resources, Rob Money, resources will be consumed)
This is a very simple loop. is to make a circle, although this circle is very small. Part of the plan to think very well, is not around the circle, that does not make any sense.

First, you need a base table for props. Automatic ID, prop type, prop properties, description. In the handling of props, can add more fields in the Player table, props follow the player. You can also build a detailed table of props individually. In a backpack-like fashion.
There are two kinds of backpack, one is to use array storage, and the other is to store with horizontal table. It's all very troublesome. But from the movement of props and trading considerations. It is worthwhile to use a backpack. The next feature.
Store. Auction houses. Basically is similar to the General website application. But the product becomes the game props. Money is a game currency.

Third, summary
The small example above, the idea is basically perfect, no problem. Only a small part of the program code gives a real understanding of this small part. Other parts of the program should not be a problem.
Webgame important is the flow of data around the circle, as well as the gameplay.
Now it's about: the robustness of the program and the clarity of the data flow.
The above function, really make, is not enough to play. There is nothing to play, and it makes no sense to make it.
But it is still a difficult thing to do just that.
There are too many things involved in the game. Even a very simple game, even if the webgame looks very simple, even the actual is very simple, it is very difficult to do it.
No one has developed webgame experience to plan webgame or to develop webgame. Will feel very simple. The big function is actually so few. The idea is also easy to circle.
The reality is that a very simple function, when it needs to circle the time, when it needs to interact. This function is no longer simple, but complex, rather complex.
This is when you don't quite understand design patterns, and if you are proficient in design patterns, then the functionality will be simple.

In particular, you want to make a good enough to play, market-oriented products, even if the initial thinking is very simple, the function is very simple. But when you actually plan, the actual programming time. A lot of data, numbers need you to deal with, a lot of interaction needs you to deal with. At this point, the simplicity of the beginning has become complicated. Although from a procedural point of view, the technical content is not high.
More accurately speaking, is tedious, very cumbersome.

Good planning is the data table can be listed, the data to a clear list, placed in front of you. This is not a lot of planning.
Of course, he is not necessarily accurate, but the 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.