Flash combines with Java servlet to achieve online gaming

Source: Internet
Author: User
Tags array
Servlet

  Author Contact method: QQ:4077130 e-mail:xiake1860@ncepubj.edu.cn

Flash produced in the game online there are many, but few can support the game between the network. To achieve online war, you must have the support of the backend server. This article is based on a simple example

To explore how to use Flash and the Java servlet combination to achieve the network between the station. It should be noted that this article readers need to have some knowledge of Flash and Java servlet programming.

  The game running screen is as follows:

Click here to download the source file

Fill in the "servlet address" with your SERVLETR mapping address, then "Enter name" to fill in a name (must), click "Start" to run.

You can use the arrow keys to control the name of the car (instance named "Cars") in the stage movement, if there are many people landing, you can see other cars in the movement.

Analysis:

For the control of their own car can be realized through the flash foreground, to see other people on the stage of the car movement, you need to download from the background servlet other car related data (Name,xpos,ypos). In order for others to see my car, I also have to send the data of the car to the servlet for others to read. We send the relevant data to the server through the Loadvars object, the server writes all the information to an XML document, we load some documents into the XML object, through parsing it, obtains all the trolley information, then draws the car on the stage according to this information. The XML document that we get is the following form:

<players>

<player name= "Bbyy" xpos= "309.95" ypos= "214.95"/>

<player name= "Bitao" xpos= "200.0" ypos= "100.0"/>

</players>

Realize:

1. Create a new flash document, create a new movie clip, named "Car", that is, we want to control the trolley, in the inside draw a car map (for his simple I drew a circle). When you're done, open the movie library, find the clip, right-click its name, select "Link", Fill in "Car" in "identifier", and tick "Export for action script" and "Export in first frame".

2. From the palette, drag two textinput components to the stage, naming the instance "Nameinput", "Urlinput", to lose the name and server address, respectively. Drag a button component to the stage, named "Submitbt", to start the game. From the film library, drag a "car" to the center of the stage, named "Cars", we want to control the trolley.

3. Open the Action panel, we first to achieve the control of the car. (Here the code is only for explanation, see source file specifically)

To monitor a keyboard, you need to build a listener object, var listenerkey:object=new object ();

Then, add a listener event

Listenerkey.onkeydown=function () {
if (_root.started) {//_root.started is a global variable, initially false, set to True when clicking "SUBMITBT", that is, the game begins
var M:movieclip=_root.car;
var speed=3; Speed of car movement
if (Key.isdown (Key.left)) {
M._x-=speed;
}
if (Key.isdown (key.right)) {
M._x+=speed;
}
if (Key.isdown (key.up)) {
M._y-=speed;
}
if (Key.isdown (Key.down)) {
M._y+=speed;
}
}
}

To add a listener to a key:

Key.addeventlistener (Listenerkey);

Run the movie, the car will move with the button.

4. to be able to interact with the server, you need to create two objects.

var send_lv:loadvars=new loadvars ();//used to send data to the server

var get_lv:xml=new loadvars ()//used to load data from the server, load type as XML document

5. to refresh the server continuously, enter the following statement:

_root.onenterframe=function () {
if (_root.started) {
if (_root.get_lv.loaded) {//If the last data was loaded successfully
_root.send_lv.xpos=_root.car._x;
_root.send_lv.ypos=_root.car._y; Pay the coordinates of the car to the sending object
_root.send_lv.sendandload (URL_SERVICE,_ROOT.GET_LV, "get"); Send data to the server and accept return data with "GET_LV"
}
}
}

6. when the "GET_LV" load succeeds, we need to parse it and draw all the cars on the platform based on the data we get.

get_lv.onload=function (Ok:boolean) {
if (ok) {
var nodes=get_lv.firstchild.childnodes;//" Nodes "stores information about all the cars obtained from the server
Var len_nodes:number=nodes.length;
var len_players:number=_root.players.length;//"_root.players" is an array that stores all the car names that have been drawn on the stage
Trace (len_nodes);

Var i=j=0;
for (i=0;i<len_nodes;i++) {
var addnew:boolean=false;
for (j=0;j<len_players;j++) {
if (_root.players[j]==nodes[i].attributes.name) {
j=len_players+1;
}
if (j== (len_players-1)) addnew=true; The
}
if (addNew) {///above code is used to determine if a new trolley is added; If so, we will draw it out according to its name
_root.players.push (nodes[i].attributes.name) //Add the name of the new car to the array
_root.attachmovie ("Car", nodes[i].attributes.name,_root.getnexthighestdepth ());//To draw the new trolley
_ root[nodes[i].attributes.name].name.text=nodes[i].attributes.name;//Set the trolley name
}
_root[nodes[i]. Attributes.name]._x=nodes[i].attributes.xpos;
_root[nodes[i].attributes.name]._y=nodes[i].attributes.ypos;//Refreshes the position of the car on the stage by name.

}

}

7. Add action for "SUBMINTBT":

Listenerbt.click=function () {

if (!) ( _root.nameinput.text== "")) {

_root.started=true;
_root.send_lv.xpos=_root.car._x;
_root.send_lv.ypos=_root.car._y;
_root.send_lv.name=_root.nameinput.text;

if (_root.urlinput.text!= "") {
_root.url_service=_root.urlinput.text;
}

_root.players.push (_root.nameinput.text);
_root.car.name.text=_root.nameinput.text;
}

}
Submitbt.addeventlistener ("click", LISTENERBT);

OK, the front desk is ready! Let's look at how to write a servlet.

8. We need a POS class to describe the location of the car, a player class to represent the car, a service class to receive requests and output XML documents. The first two classes are not covered, so let's just look at how the service accepts the request and draws the XML document. The code is as follows:

Import java.io.*;
Import java.util.*;
Import javax.servlet.*;
Import javax.servlet.http.*;

public class Service extends httpservlet{

public void doget (HttpServletRequest request,
HttpServletResponse response)
throws ioexception,servletexception{

PrintWriter out = Response.getwriter () ;


//Create a global object to store all information
Hashtable players= (Hashtable) (This.getservletcontext (). getattribute ("Players") );
try{

if (players==null) {
Players=new Hashtable ();
This.getservletcontext (). setattribute ("Players", players);
}

}catch (Exception e) {
Out.println (e.tostring ());
}

String player_name=request.getparameter ("name");
String x=request.getparameter ("xpos");
String y=request.getparameter ("YPos");//Get Data from requestor
Pos newpos=new pos (double.parsedouble (x), Double.parsedouble (y));
if (Players.containskey (player_name)) {//If it is not a new requester, add its POS; otherwise create a new request object
Player player= (player) (Players.get ( Player_name));
Player.addpos (Newpos);
if (Player.getpath (). Size () >100) {Player.getpath (). Remove (0);
}else{
Player newplayer=new player (player_name);

Newplayer.addpos (Newpos);
Players.put (Player_name,newplayer);
}
Vector allplayers=new vector (players.values ());


Output the latest location of all requesters as XML
Response.setcontenttype ("Text/xml");
Out.print ("<players>");
for (int i=0;i<allplayers.size (); i++) {
Player p= (player) (Allplayers.get (i));
Out.print ("<player");
Out.print ("Name=\" "+p.getname () +" ");
Out.print ("Xpos=\" "+p.getcurrentpos (). GetX () +" \ ");
Out.print ("Ypos=\" "+p.getcurrentpos (). GetY () +" > ");
Out.print ("</player>");
}
Out.print ("</players>");

}
}

9. compile all. java files into a. class file, configure it on your server, and enter a mapping for "Service", which is the URL address you want to add when you run it. Run your. swf file, ok!



Related Article

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.