Web game development introductory tutorial three (simple program application)_PHP tutorial

WBOY
Release: 2016-07-21 15:42:37
Original
888 people have browsed it

Introduction to Web Game Development Tutorial 2 (Game Mode + System)
http://www.jb51.net/article/20724.htm

1. Choose a development language
Backend: java .net php
Frontend: flex javascript ajax
Database: mysql mssql
It really doesn’t matter which combination you use. . What matters is time and cost. The complexity lies in the interaction and perfection of data, not in the implementation of technology or effects. Often encounter some problems. For example, how to compile a map? How to implement character movement? In fact, these problems are relatively easy to implement technically. The difficulty lies in how the data interacts after implementation. Without solving the problem of data interaction, it is of little significance to implement these technical points. I use php+javascript+mysql.
Reason: Simple and quick to use. Products can be produced relatively quickly.
2. The program is simple to apply.
, template
to facilitate UI modification. So use templates. smart template is quite convenient. Very simple. Code can also be nested within templates. The only problem is that if the artist doesn’t know how to program, modifying the template will require programming. It's not scientific.
Smart template tutorials are available online. Just say a little. You can use to nest any code in the template (.html file). Get the passed value. Use $_obj[‘xxx’] or $_stack[0][‘’] to nest with code written in {xxx}. It is the same as the .php file, there is no difference.
, Map
Because the game type is not ogame mode, the map is not automatically generated. Instead, it is all called from the database. The idea is simple. The map is a big picture. Cut into multiple small pieces. The absolute coordinates of each small tile corresponding to the large image are recorded in the database. When displayed, call the small tile in the corresponding coordinate area.
The code is similar:
$sql="select * from map where mapx between $xxx and $xxx and mapy between $ yyy and $yyy ";
It means to get the abscissa xx from the map table to xx. All small tiles with vertical coordinates xx to xx. For example, 20. Suppose we write a function showMap(x,y) to display all the obtained data. Maps can have many layers.
Each small tile is a div. Just use css for specific control. Small tiles can be used as the background of divs. It can also be used as an image in a div. Just control the left and top of the div. (left and top are the absolute coordinates of the small tile relative to the large tile) showMap(x,y) is placed in the lower two layers.
One layer handles the map size:


One layer handles dragging:

Copy code The code is as follows:


//JS code to handle dragging. (Copied from the Internet. Thanks to this guy.)
<script> <br>function fDragging(obj, e, limit){ <br>if(!e) e=window.event; <br>var x=parseInt(obj.style.left); <br>var y=parseInt(obj.style.top); <br>var x_=e.clientX-x; <br>var y_=e.clientY-y; <br>if(document.addEventListener){ <br>document.addEventListener('mousemove', inFmove, true); <br>document.addEventListener('mouseup', inFup, true); <br>document.body.style .cursor="move"; <br>} else if(document.attachEvent){ <br>document.attachEvent('onmousemove', inFmove); <br>document.attachEvent('onmouseup', inFup); <br> document.body.style.cursor="move"; <br>} <br>inFstop(e); <br>inFabort(e) <br>function inFmove(e){ <br>var evt; <br>if (!e)e=window.event; <br>if(limit){ <br>var op=obj.parentNode; <br>var opX=parseInt(op.style.left); <br>var opY=parseInt (op.style.top); <br>if((e.clientX-x_)<0) return false; <BR>else if((e.clientX-x_+obj.offsetWidth+opX)>(opX +op.offsetWidth)) return false; <br>if(e.clientY-y_<0) return false; <BR>else if((e.clientY-y_+obj.offsetHeight+opY)>(opY+op .offsetHeight)) return false; <br>//status=e.clientY-y_; <br>} <br>obj.style.left=e.clientX-x_+'px'; <br>obj.style. top=e.clientY-y_+'px'; <br>inFstop(e); <br>} // shawl.qiu script <br>function inFup(e){ <br>var evt; <br>if( !e)e=window.event; <br>if(document.removeEventListener){ <br>document.removeEventListener('mousemove', inFmove, true); <br>document.removeEventListener('mouseup', inFup, true) ; <br>} else if(document.detachEvent){ <br>document.detachEvent('onmousemove', inFmove); <br>document.detachEvent('onmouseup', inFup); <br>} <br>inFstop( e); <br>document.body.style.cursor="auto"; <br>//Achieve a dragging effect similar to Google Maps. <br>ajaxRead('map.php?mapx='+(e.clientX-x_)+'&mapy='+(e.clientY-y_)+'','2'); <br>} // shawl .qiu script <br>function inFstop(e){ <br>if(e.stopPropagation) return e.stopPropagation(); <br>else return e.cancelBubble=true; <br>} // shawl.qiu script <br>function inFabort(e){ <br>if(e.preventDefault) return e.preventDefault(); <br>else return e.returnValue=false; <br>} // shawl.qiu script <br>} <br>//]]> <br></script>

Pay attention to the following code:
ajaxRead('map.php?mapx='+(e.clientX-x_)+'&mapy='+(e.clientY-y_)+'','2' );
The location of this code is triggered when the mouse is released after dragging the layer. You can use alert("The map was dragged here"); instead. Test the effect. The meaning of this code is to drag the coordinates according to the current map. Call an ajax. That is to obtain map information from the database again. AjaxRead() is an ajax calling function. You can write it all yourself. It can also be written using a framework such as prototype.js.
//Ajax processing code. (I copied it from the Internet, with slight changes... Oh, why do I keep copying it... Mainly to save development time... Another point is that my JavaScript is very rubbish (*^__^*) Hehe)
Copy code The code is as follows:

function ajaxRead(file,action)
{
var xmlObj = null;
if(window.XMLHttpRequest)
{
xmlObj = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlObj = new ActiveXObject(" Microsoft.XMLHTTP");
}
else
{
return;
}
function ajaxDo(action)
{
switch(action)
{
case "2":
document.getElementById('display').innerHTML = xmlObj.responseText;//The display here is your id in the upper layer of the page. The above map code needs to be placed in this layer. For example,
writes id and name to facilitate the compatibility between Firefox and IE.
break;
}
}
xmlObj.onreadystatechange = function()
{
/*
if(xmlObj.readyState == 1)//loading state.
{
document.getElementById('xianshi2').innerHTML = "Loading";
}
*/
if(xmlObj.readyState == 4)//When completed .
{
ajaxDo(action);
}
}
xmlObj.open ('GET', file, true);
//xmlObj.reload('GET', file , true);
xmlObj.send (null);
//xmlObj.abort ('');
}

The meaning of the entire code is:
When After dragging the map and releasing the mouse, the display layer regains data. No refresh is displayed. The pictures in the map all use png32 transparent images. Both Ie7 and ff3 are fine. If you encounter ie6. . Use gif instead. map.php function. Display the corresponding small tile according to the obtained x and y. This function is actually the showMap(x,y) mentioned above, which is very similar to dragging on Google Maps. But it’s much simpler. Simple and effective. 2. Character 2. Character attributes
because of the set requirements. The character needs to have equipment bonuses and status bonuses (buff, debuff). At this time, put all the required bonuses into the character class. is a very good method.
Probably like this:
Copy code The code is as follows:

class role
{
// Get character data.
getRloe()
{
Get character information from the database.
}
//Get equipment bonus.
getEquip()
{
Get equipment bonus information.
}
//Get status bonus
getState()
{
Get status bonus information.
}
//Add, subtract, or adjust the information obtained above.
//Return character data.
Return xxx
}

Specially bring this up. It's because the bonus is not put into the character object. Every time I have to fight or do something. After obtaining the character data, a lot of code processing bonuses must be added. Too much repetition. Once you put the code in front of you, the world becomes peaceful. . .
, props
Props are special. Because there are many types and many ways to use them, there may be multiple storage locations and there may be unique props. One day I looked at the code of web World of Warcraft. It was discovered that his only prop was a watch. There is a field to handle the location of props, such as (1, auction house, 2, backpack, 3, warehouse, 4, store). This method is quite good. However, if the complexity of the props increases. For example, different warehouses, different auction houses, need to be synthesized, etc. Or only the sub-table.
Basic item table:
id
itemname name
itemprice price
itemimage picture
itemtype type
uptype add type
uppoint add points
addtype add type ( Permanent)
addpoint Increase points (permanent)
cleardebuff Clear debuff
addbuff Add buff
Start from uptype. All can be written in the form xx|yy|zz. It’s best to correspond one to one. You can choose the delimiter yourself.
When calling and processing data, you can use a method similar to the following:
Copy code The code is as follows:

$ uptype = explode("|", $iteminfo['uptype']);
$uppoint = explode("|", $iteminfo['uppoint']);
for ($j=0;$j< ;count($uptype);$j++)
{
echo $uptype[$j];
echo $uppoint[$j];
}

Warehouse, auction house, shop, backpack and more. A place to hold props. As long as there is an id field to store the prop id. As for whether it is a horizontal table or a vertical table, you can choose according to actual needs. So far, the props look to be in good hands. At this time, the planner said. The props need to be unique and can be enchanted. OK, then fill in all the combinations in the prop table. The synthesis is just a+b=c. . One calculation. For example, 40 things that may be enchanted. 200 enchantable items. 40*200=8000. Obviously, the planner would not agree. Then the headache is the program. How to deal with it. Add a table.
Unique prop table:
id unique prop id (cannot be duplicated with ordinary prop id. Convenient for backpack calls, etc.)
temp_id temporary id (default 0. May be used when synthesizing props.)
itemid original prop id (get the initial value of the prop)
fumo_id enchantment id. (Default 0, i.e. no enchantment)
Enchanting table: (i.e. added attributes)
id
uptype increase type
uppoint increase points
cleardebuff clear debuff
addbuff increase buff
Now look at the function modifications
The first is the prop class:
class Item
{
getItem()
{
//In the past, it was ok to get the prop information directly based on the id.
//Enchanting is now added
//First determine whether the item ID is a unique item. (For example, ordinary props range from 1 to 10000. Unique prop IDs start from 10001. If you think this is not good, add a field to the basic prop table to determine whether the prop is unique)
if (the prop is unique)
{
//Get the original prop id and enchantment id from the unique prop table
//According to the original prop id, or the basic information of the prop.
//According to the enchantment ID, obtain the enchantment bonus information.
//Add the values ​​on both sides.
Return prop information.
}
else
{
Get item information directly.
}
}
}
Enchanting function:
Item A. (Basic props) + prop B. (Basic props) = Props C. (The only prop)
That is, the only prop is generated when the enchanting function is executed. Take a backpack as an example. Before enchantment.
Item A in the backpack. id is 1.
Item B in the backpack. id is 2.
After executing the enchantment function. The IDs of props A and B are set to 0 (horizontal table), or deleted (vertical table). Generate a unique number. temp_id. (Just generate md5.) Generate a unique prop. At this time, according to temp_id, A's backpack once again obtains the id of the unique prop. Props, relatively complete solution.
The following parts all involve some business issues, so I can only give ideas and very little code.
-------------------------------------------------- ----------------------------------
, timer
will be executed after waiting for xx time xx question. PHP comes with a sleep() function. Waiting time can also be controlled.
But obviously, both in terms of application and efficiency. Neither is enough to support game timing. The idea is simple. All parameters of the event that need to be counted down, as well as the start time and end time. All stored in a table. The front desk uses javascript to count down, and when the time is up, the handler after the time is called through ajax. The background automatically executes a processing program after the calling time expires at certain intervals.
At least three php pages are required.
A content used to write access timing.
When a processing foreground time expires, the operation ends.
A processing background is refreshed regularly, and the execution ends when the judgment time is up. No processing is performed before the time is up.
miracle: Are different timers corresponding to different events, or can the same timer be called for multiple events? If a player calls a timer to time the construction of a building, how long does it take to build a building? This timer is called to time the construction time of another building. Is this okay? Will there be a conflict?
Soot on the keyboard:
Multiple events correspond to one timer.
You can add a field to the timer. For example, it is called actiontype (event type)
Each user can handle multiple things at the same time. It's just that everything has a fixed number.
For example, your user is allowed to do 5 things at the same time. Then the direct number in actiontype is 1-5. When calling the timer, based on the different numbers, you will know that this is the user's first "thread".
miracle
If different users call the same timer, there will be no conflict, right?
Soot on the keyboard:
Of course not. You see. userid can be used to identify a user. actiontype can be used to determine which thread it is.
, event control
combined with timer, processing start(), process(), end()
Copy code The code is as follows:

interface Action
{
function doAction();
function beginAction();
function processAction();
function endAction();
}
//Simple event factory
class ActionFactory
{
public function getAction($what)
{
$ActionName = $what;
return new $ActionName;
}
}
//For example, move
class Move implements Action
{
function doAction()
{
Specific execution function
When should this process be performed? . All judged here.
}
function beginAction()
{
Executed when the event starts.
Here you can save data to the timer. In the future, the data will be fetched from the timer.
}
function processAction()
{
Get data from the timer.
The process of event execution. For example, when the user refreshes the page. If still counting down. Then this is where to call.
}
function endAction()
{
Get data from the timer.
The process of ending the event.
After the timer expires, complete the event.
}
}
//When called for the first time.
$Action = new ActionFactory();
$InstanceAction = $Action->getAction("Move");
$InstanceAction->set ($parameter);
$InstanceAction-> ;doAction();
//When called later.
$Action = new ActionFactory();
$InstanceAction = $Action->getAction("Move");
//At this time, the parameters or data of the event are obtained from the timer.
$InstanceAction->doAction();

, Combat
Real-time and semi-real-time turn-based combat (real-time turn-based combat between two or more people) is relatively cumbersome.
At least include:
Front desk:
Automatically receive invitation information. Ajax
Display the battle process. Ajax
Round countdown time. javascript
Backend:
Send invitation, accept, reject, timeout. a table. Combat data. a table. Save the data of both parties or multiple parties, including round time, which round, etc.
Combat controls. A series of functions. Process the player's operations and save the operations in the combat data table. Perform the operation after the time is up.
After sending troops, return to the battle report directly.
Just write it in the event.
function endAction()
{
Get data from the timer.
Generate rounds and generate battle reports.
}
Note: Due to my work reasons, this series may have to be suspended for a period of time before updating. I hope you will forgive me. . .

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/320886.htmlTechArticleIntroduction to Web Game Development Tutorial 2 (Game Mode + System) http://www.jb51.net/article/ 20724.htm 1. Select development language Backend: java .net php Frontend: flex javascript ajax database...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template