HTML5 game development practices-notes

Source: Internet
Author: User

HTML5 game development practices-notes

1. WebSocket is part of the HTML5 standard. Web pages can be used to persistently connect to the socket server. This interface provides an event-driven connection between the browser and the server, which means that the client no longer needs to send a new data request to the server every other time period. When data needs to be updated, the server can directly push data updates to the browser. One of the benefits of this function is that players can interact in real time. When a player does something, it sends data to the server. The server broadcasts an event to all other connected browsers to let them know what the player has done. This makes it possible to create an HTML5 online game.

2. With the native support of modern browsers for HTML5 elements, users no longer need to pre-install third-party plug-ins to play games.

3. Place the JavaScript code in the end tag of the body.Before and after all the content on the page. The following describes how to place the code in this position, instead of the previousThe reason between two labels.

4. Generally, the browser loads and renders content from top to bottom. If JavaScript code is placed in the head part, the JavaScript code has been loaded, and the content of the document may not have been loaded. In fact, if the browser loads JavaScript code in the middle of the page, it will interrupt ongoing rendering and loading. This is why we try to put JavaScript code at the bottom of the page. This method can improve the performance of content loading.

5. jQuery provides us with a method to execute code after page loading is complete, as follows:

JQuery (document). ready (function ()

{

// Here is the code

});

$ (Function ()

{

// Here is the code

});

6. jQuery has the following advantages over JavaScript alone:

You can use jQuery to select and modify DOM nodes with shorter code.

Short code is more conducive to code reading, which is crucial to game development because game development often contains a large amount of code.

Writing short code can speed up development.

Using the jQuery library allows the code to support all mainstream Browsers without any additional adjustments; jQuery encapsulates pure JavaScript code to achieve its own cross-browser capabilities.

7. assign a number to each key on the keyboard. By getting a number, we can find which key is pressed. By listening to The jQuery keydown event listener, the event object will contain the key code when the event is triggered ). You can call the which function of the key event object to obtain the key code.

$ (Document). keydown (function (e)

{

Console. log (e. which );

Switch (e. which)

{

Case 38: // press the up key

}

});

8. In most cases, you can set CSS styles for the left and top attributes of DOM elements in a format like 100px. Specify the unit when setting the attribute, and return the unit value when obtaining the attribute value. For example, when $ ("# paddleA" ).css ("top") is called, the resulting value is 100 PX instead. this will cause problems when performing mathematical operations on this value.

$ ("# PaddleA" ).css ("top") + 5, returns 100px5 instead of the expected result.

9. parseInt (string, radix) the string to be parsed. An optional parameter that uses a number to indicate the hexadecimal system to be used.

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

10. Because global variables are valid throughout the document, the probability of variable name conflict is increased when different JavaScript libraries are integrated into the Web page. A better way is to put the used global variables into an object.

11. Before introducing the back visibility, all elements on the page should only display the front of them. In the past, there was no front or back concept for the element because it had only one choice. Now, after CSS3 introduces the concept of Three-axis rotation, it can perform 3D Rotation on the element so that it has the back.

12. CSS3 references a backface-visibility attribute to define whether the back of an element can be viewed. By default, it is visible.

13. Alignment

$ ("# Cards"). children (). each (function (index)

{

// Align cards in a 4 × 3 Format

$ (This example .css (

{

"Left": ($ (this). width () + 20) * (index % 4 ),

"Top": ($ (this). height () + 20) * Math. floor (index/4)

});

});

"%" Is called the modulus operator in JavaScript. It returns the remainder of the divisor. The remainder is used as the column count. The result of division-quotient can be used as the row count.

Taking index value 3 as an example, 3% 4 is equal to 3, so the card with index value 3 is located in the 4th column. And 3/4 is equal to 0, so it is located in 1st rows.

14. CSS3 elastic box layout module

Display:-webkit-box;

-Webkit-box-pack: center;

-Webkit-box-align: center;

The elastic box module defines the alignment of elements when the element container has extra space. In this way, we can set the element behavior as an elastic box container: set the value of display (A CSS2 attribute) to box (a new CSS3 attribute value ). Box-pack and box-align are two attributes that define how to align horizontally and vertically and use extra space. You can center an element by setting two properties as center.

15. You can save custom data to the DOM element through custom data attributes. We can create a custom property name prefixed with data-and assign values to it.

    <Li data-chapter = "2" data-difficulty = "easy"> Ping-Pong </li>

    <Li data-chapter = "3" data-difficulty = "medium"> Matching Game </li>

This is a new function proposed in the HTML5 standard. According to W3C, custom data attributes are designed to save private custom data of pages or applications. Currently, no other attributes and elements are more suitable for this purpose.

W3C also said that this custom data attribute is a general extension mechanism that is "only used by the website's own scripts rather than public metadata ".

$ (This). attr ("data-pattern", pattern );

For HTML5 custom data attributes, jQuery provides another function to access HTML5 custom attribute attributes, that is, the data function.

The data function is first used to embed custom data into jQuery objects of HTML elements. Later, it was used to access HTML5 custom data attributes.

. Data (key );

. Data (key, value );

<Div id = "target" data-custom-name = "HTML5 Games"> </div> you can call the data function of jQuery to access the data-custom-name attribute.

$ ("# Target"). data ("customName") It returns "HTML5 Games"

16. One of the most important functions of HTML5 is the Canvas Element. We can regard the Canvas element as a dynamic area in which we can draw images and images using scripts.

17. Draw the path in the Canvas.

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

Var ctx = canvas. getContext ("2d ");

Ctx. fillStyle = "red ";

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

Ctx. fill ();

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

Ctx. fillStyle = "green ";

Ctx. fill ();

When the arc function or other path rendering functions are called, the path is not drawn immediately on the Canvas. Instead, add it to a path list. These paths are not drawn before the draw command is executed.

The Canvas API has two execution commands, one for filling the path and the other for drawing the stroke. You can use the fill function to fill the path, or call the stroke function to stroke the path.

The fill and stroke functions fill and draw paths on the Canvas, but they do not clear the path list. In the above example, after filling the circle with red, add another circle and fill it with green. The result is that both circles are filled with green. When calling the 2nd fill command, the path list in the Canvas also contains two circles. Therefore, the fill command uses green to fill the two circles, that is, to refill the red circle.

To solve this problem, you must make sure that beginPath is called every time you draw a new shape. BeginPath clears the path list. Therefore, when the fill and stroke commands are called next time, only all paths after the last beginPath call will be applied. The closePath function draws a straight line from the end of the latest path to the start point of the path, used to close the path.

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

The random function has no parameters. It always returns 0 ~ A floating point number between 1, which is greater than or equal to 0 and less than 1. There are two common methods to use the random function. One is to generate a random number within a given range. The other is to generate a Boolean value of true or false.

Math. floor (Math. random () * B) + A; // The Math. floor () function rounds out the given decimal number. Math. floor (Math. random () * 10) + 5 is 5 ~ An integer between 14;

(Math. random ()> 0.495); // obtain a random Boolean value, which means that 50% returns false and 50% returns true.

19. it is worth noting that the text drawn in the Canvas is considered as bitmap image data, which means that the viewer cannot select the text and the search engine cannot index the text. Similarly, they cannot be searched. For this reason, we should think about whether to plot the text in the Canvas or directly put them in the DOM.

20. Play the sound. You can call the getElementById function to obtain the reference of the audio element. Then, call the play function to play the video.

<Audio id = "buttonactive">

<Source src = "media/button_active.pdf"/>

<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 starts playing audio at the current playback time, which is stored in the currentTime attribute. The default value of currentTime is 0. The above code will start playing the audio from the position of 3.5 seconds. You can also use the pause function to pause playing an audio element.

21. The second parameter of the parseInt function in JavaScript is optional. It defines the base number for parsing numbers. By default, it uses decimal, but when the string starts with zero, parseInt parses the string in octal. For example, parseInt ("010") returns 8 as the result instead of 10.

22. Use local storage technology to save and load data. You can use the setItem function of the localStorage object to save data.

LocalStorage. setItem (key, value); key is the name of the record, which is used to identify the corresponding entity; value is any data that will be stored.

LocalStorage. getItem (key); this function returns the storage value of the given key. If you try to obtain a key that does not exist, it returns null.

23. Local storage size limit. Each domain name uses localStorage to store data. The size limit may vary slightly in different browsers. Generally, the size is limited to 5 MB. When a key-value pair is set to localStorage, if the limit is exceeded, the browser throws a QUOTA_EXCEEDED_ERR exception.

24. Use setItem and getItem

LocalStorage. setItem ("last-elapsed-time", elapsedTime );

Var lastElapsedTime = localStorage. getItem ("last-elapsed-time ");

Access localStorage as an array. The Code is as follows:

LocalStorage ["last-elapsed-time"] = elapsedTime;

Var lastElapsedTime = localStorage ["last-elapsed-time"];

25. Modern Web browsers support JSON native. Using the stringify function, you can easily encode any JavaScript Object into JSON. The Code is as follows: JSON. stringify (anyObject );

26. localStorage. removeItem (key); use this function to delete the record usage of a given key;

27. localStorage. clear (); you can use this function to delete all records.

28. WebSocket allows you to create an event-driven server-client architecture so that all connected browsers can transmit messages to each other in real time.

29. Broadcast messages to all connected browsers. Each time the server triggers a new connection event, the number of connections is updated to all clients. It is very easy to broadcast a message to the client. You only need to call the broadcast Function of the server instance and pass the string-type broadcast message as a parameter to this function.

The following code snippet broadcasts 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 string-type messages, but cannot directly send objects. Therefore, data can be converted to a JSON string before transmission.

31. You can use the following CSS style to remove these Image Tag resource locations from the HTML display range to hide them. We do not use display: none to do this, because the browser cannot obtain the length and height of undisplayed elements. In the physical world, the length and height are required to correctly locate the image:

# Asset

{

Position: absolute;

Top:-99999px;

}

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.