HTML5 game development Combat--beware

Source: Internet
Author: User
Tags jquery library

1.WebSocket It is part of the HTML5 standard. Web pages can be used to connect to persistent socketserver in. This interface provides a browser and server-to-event-driven connection. This means that the client no longer sends a new data request to the server each time it needs it.

When there is a need to update the data, the server can directly push the data to update to the browser. One of the benefits of this feature is the ability to interact in real time between players.

When a player does something, it sends the data to the server, and the server broadcasts an event to all the other connected browsers. Let them know what the player has done. This makes it possible to make HTML5 online games.

2. With the native support for HTML5 elements in modern browsers, it is no longer necessary for users to pre-install third-party plugins to play the game.

3. We place the JavaScript code before the body end tag </body> and after the entire content of the page.

The following describes the reason for putting the code in this position, rather than the one that used to be between

4. Browsers typically load and render content from top to bottom. Suppose the JavaScript code is placed in the head section. Causes the JavaScript code to be loaded and the contents of the document may not have been loaded.

In fact. Assuming the browser loads JavaScript code in the middle of the page, it interrupts the rendering and loading in progress. That's why it's possible to put JavaScript code at the bottom of the page. Through such a way. To improve the performance of loading content.

5.jQuery gives us a way to run the code after the page is loaded, such as the following:

JQuery (document). Ready (function ()

{

Here is the code

});

$ (function ()

{

Here is the code

});

6. There are several advantages to using jquery than simply using javascript:

Using jquery, you can select and change DOM nodes in shorter code.

Short code is more conducive to code reading, which is important for game development, as game development often involves a lot of code.

Writing short code can speed up development.

Using the jquery library allows the code to support all major browsers without additional adjustments. jquery wraps Pure JavaScript code to achieve its own ability to implement cross-browser.

7. Assign a number to each key on the keyboard, and by getting the number, we can find out which key is being pressed. By listening to the KeyDown event listener of jquery, the event object will include the key code when it is triggered. The key code can be obtained by invoking the which function of the key event object.

$ (document). KeyDown (function (e)

{

Console.log (E.which);

Switch (E.which)

{

Case 38://Press the UP key to handle

}

});

8. In most cases, CSS styles can be set to the left and top properties of DOM elements through formats like 100px.

Specifies the unit when the property is set. When you get the value of a property, the value returned is also a unit of the band. Example. When you call $ ("#paddleA"). CSS ("top"), the resulting value is 100px instead of 100. This will cause problems when you run mathematical operations on this value.

$ ("#paddleA"). CSS ("top") + 5, the return will be 100px5. Rather than the results we want.

9.parseInt (String, radix) The string that needs to be parsed. Optionally, use a number to indicate what binary system is required.

Parse ("5cm") returns 5; Parse ("FF", 16) returns 255

10. Because global variables are valid throughout the document, the probability of variable name collisions is added when different JavaScript libraries are integrated into a Web page. A better approach would be to put the global variables used in an object.

11. Before the presentation of the back visibility. All the elements on the page should only be presented in front of them. Once, elements have no concept of front or back. Because it has only one choice. Now. When the CSS3 introduces a three-axis rotation concept, the element can be rotated 3D. So it has a back side.

12.CSS3 refers to a property called backface-visibility (back visibility). Used to define whether you can see the back of an element.

By default, it is visible.

13. Align

$ ("#cards"). Children (). each (function (index)

{

Align the cards in the form of 4x3

$ (this). CSS (

{

' Left ': ($ (this). Width () +) * (index% 4),

"Top": ($ (this). Height () +) * Math.floor (INDEX/4)

});

});

"%" is called a modulo operator in JavaScript. It returns the remainder of the dividend. The remainder is used as a count of columns; The result of division--quotient, can be used as a count of rows.

Take the index value 3 for example. 3%4 equals 3. So a card with an index value of 3 is in column 4th. and 3/4 equals 0, so it's on line 1th.

14.CSS3 Flexible Box Layout module

Display:-webkit-box;

-webkit-box-pack:center;

-webkit-box-align:center;

The Elastic box module defines the alignment of elements when there is extra space in the container of the element. We are able to set the behavior of the element as a flexible box container: Set the value of display (a CSS2 property) to Box (a CSS3 new property value). Box-pack and Box-align are two properties. Used to define how to align and use additional free space in the horizontal and vertical directions.

You can center an element by setting two properties for center.

15. You can save your own definition data into DOM elements by defining your own data attributes.

We are able to create a self-defined property name prefixed by data-and assign it a value.

<ul>

< li Data-chapter = "2" data-difficulty = "Easy" > Ping-Pong </li >

< li Data-chapter = "3" data-difficulty = "Medium" > Matching Game </li >

</ul>

This is a new feature proposed in the HTML5 standard.

According to the web site, the purpose of defining data attributes is to save the page or application's own defined data, and for now, no other attributes and elements are more appropriate for this purpose.

The website also says that this self-defined data property is "a generic extension mechanism for use by the site's own scripts instead of common metadata."

$ (this). attr ("Data-pattern", pattern);

For HTML5, you define the data properties. jquery provides a function to access the HTML5 to define its own attribute properties, which is the data function.

The data function is first used to embed its own definition of the HTML element's jquery object. Later used to interview HTML5 to define the data properties.

. data (key);

. Data (key, value);

< div ID = "target" data-custom-name = "HTML5 Games" > </div > Ability to call the data function of jquery to access data-custom-name properties

$ ("#target"). Data ("Customname") it will return "HTML5 games"

One of the most important features of 16.HTML5 is the canvas element. We can think of the canvas element as a dynamic area where we can draw images and graphics in a script.

17. Working with path drawing in the canvas

var canvas = document.getElementById ("game");

var ctx = Canvas.getcontext ("2d");

Ctx.fillstyle = "Red";

Ctx.arc (0, Math.PI * 2, true);

Ctx.fill ();

Ctx.arc (0, Math.PI * 2, true);

Ctx.fillstyle = "green";

Ctx.fill ();

When the ARC function or other path drawing function is called. does not draw a path on the canvas. Instead, simply add it to a list of paths. These paths are not drawn until you run the draw command.

There are two drawing run commands in the canvas's API, and a command to populate the path. There is also a line for drawing strokes. You can fill the path with the fill function, and you can stroke the path by calling the stroke function.

The fill and stroke functions are responsible for populating and drawing paths on the canvas, but it is not responsible for clearing the list of paths.

The above example, after filling the circle with red, joins a circle and fills it with green, and the result is two circles filled with green. Since the 2nd Fill command is called, the list of paths in the canvas also includes two circles. So. The fill command fills the two circles with green, which is once again filled with a red circle.

To solve the problem, you need to make sure that you call Beginpath every time you draw a new shape. Beginpath clears the list of paths, and when the fill and stroke commands are called, it will only apply the entire path after the last call to Beginpath. The Closepath function draws a straight line from the end of the latest path to the beginning of the path, which is used to close the path.

18. In JavaScript, you can use the Math.random () function to generate random numbers.

The random function does not have a number of parameters. It always returns a floating-point number between 0~1. This number is greater than or equal to 0 and less than 1.

There are two common ways to use the random function. One is to generate random numbers within a given range.

There is also a Boolean value that generates true or false.

Math.floor (Math.random () * B) + A; The Math.floor () function gives away the decimal number of a given digit.

Math.floor (Math.random () * 10) + 5 is an integer between 5~14;

(Math.random () > 0.495); Gets a random Boolean value that means that there will be 50% return false and 50% returns TRUE.

19. It is worth noting that the text drawn in the canvas is treated as bitmap image data, which means that the browser cannot select the text, and the search engine cannot index the text at the same time; For this reason. We should consider carefully whether the text is drawn in a canvas or placed directly in the DOM.

20. Play the sound.

The ability to get a reference to the audio element by calling the getElementById function. Next, call the play function to play it.

< Audio id = "Buttonactive" >

< source src = "Media/button_active.mp3"/>

< source src = "Media/button_active.ogg"/>

</audio >

< script >

document.getElementById ("Buttonactive"). CurrentTime = 3.5;

document.getElementById ("Buttonactive"). Play ();

document.getElementById ("Buttonactive"). Pause ();

</script >

The play function will start playing audio from the current playback time, which is stored in the CurrentTime property.

The default value for CurrentTime is 0. The above code will start playing audio from 3.5 seconds, and you can pause the playback of an audio element by using the pause function.

The second parameter of the parseint function of 21.JavaScript is optional.

It defines the cardinality of the parsed number. By default, it uses decimal, but when the string starts at 0. Parseint will parse the string in octal. Example. parseint ("010") returns 8 as a result instead of 10.

22. Save and load data via local storage technology. You can use the SetItem function of the Localstorage object to hold the data.

Localstorage.setitem (key, value); The key is the name of the record, used to identify the corresponding entity, and the value is whatever data will be saved.

Localstorage.getitem (key); the function returns the stored value of the given key.

When you try to get a nonexistent key, it returns NULL.

23. The limit size of the local storage. Each domain name is limited in size when it stores data through Localstorage.

This size limit may be slightly different in different browsers. Typically, the limit size is 5MB. When setting a key-value pair into Localstorage, the browser throws a Quota_exceeded_err exception if the limit is exceeded.

24. Using SetItem and GetItem

Localstorage.setitem ("Last-elapsed-time", elapsedtime);

var lastelapsedtime = Localstorage.getitem ("Last-elapsed-time");

Interview Localstorage as an array. The code is as follows:

localstorage["last-elapsed-time"] = ElapsedTime;

var lastelapsedtime = localstorage["Last-elapsed-time"];

25. Modern Web browsers natively support JSON. Using the Stringify function makes it very easy to encode any JavaScript object into JSON, such as the following code: Json.stringify (Anyobject);

26.localstorage.removeitem (key); Use this function to remove the use of records for a given key;

27.localstorage.clear (); Use this function to delete all records.

28.WebSocket agreed to create an event-driven server-client architecture. Allow all connected browsers to deliver messages in real time to each other.

29. Broadcast messages to all connected browsers.

Whenever a new connection event is triggered by the server, the number of connections to the client is updated. It's easy to broadcast a message to the client, just call the broadcast function of the server instance and pass the string type of broadcast message to the function as a parameter.

The following code snippet is used to broadcast a server message to all connected browsers:

var message = "A message from server";

Server.broadcast (message);

30. Messages sent and received between the server and the client can only be of type string. You cannot send an object directly.

Therefore, it is possible to convert the data into a JSON-formatted string before transferring it.

31. You can use CSS styles such as the following to move these image label resource locations out of the HTML display to achieve the purpose of hiding them.

We do not use Display:none to do this thing. Because the browser cannot get the length and height of the element that is not displayed. And in the physical world. It requires length and height to correctly position the image:

#asset

{

Position:absolute;

top:-99999px;

}

Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

HTML5 game development Combat--beware

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.