Hundreds of lines of HTML5 code implement four types of Dual-player games

Source: Internet
Author: User

Introduction: This article is a very challenging programming. With 100 lines of code and about 10000 characters, it will implement four types of Dual-player games: Go, wuziqi, siziqi, and replaying. Please note that these four NLP games are not the exercises of beginners, but a complete pair of NLP games with checkerboard, three-dimensional chess pieces, events, playing rules, and winning or losing judgments, in addition, the game can be stored offline on iPad and Android tablets. If you download the game to a tablet, you can perform a round-robin on trains, tourist attractions, and other places without signals, is it a pleasure to extend the functionality of a tablet. Moreover, the key is that this app does not have images and does not need to go to the App Store for paid downloads. It is only 100 lines of code written using HTML5 technology. It is definitely the most fascinating source code for double-player games. (Editor's note: due to the limited width of the webpage code, the author's source code has undergone some line breaks .)
Target
To create a complete dual-player game, at least do the following: Draw a board. Different board games require dynamic processing. Step 2: Draw a piece. It should be noted that these chess pieces, such as go and wuziqi, are round. Please do not worry about pictures. In the HTML5 era, we can use code to implement three-dimensional circular chess pieces. Step 3: identifies a child event. Of course, you need to locate the click position of your fingers. Some of these four games fall into the box, while others fall into the crossboard cross line, which requires dynamic processing. Step 4: determine the Sub-rule. There are rules for playing chess. Do not drop the rules because there are few codes. Otherwise, the program will become a child's toy if it is not mature. Step 5: Determine whether to win or lose. Finally, we need to determine whether to win or lose. That is to say, it must be done by a program, because playing chess requires a referee. Step 6: In the tablet era, we must implement offline applications. This is too important. Otherwise, if the game connected to the root network cable on a desktop computer is already used everywhere, what is your use? There is a market only when there is no signal for mobile phones. Now there are so many tablets and smart phones. Where there is no network signal, we can pull out mobile devices to play games, it is a very good thing.
Draw a board
As mentioned above, go, wuziqi, siziqi, And go are different from those on the board. Go is a game of 18 levels, while the other three are of 8 levels. Therefore, parameters are required to draw a board. This is a small problem. The big question is, how can I draw a board?
In the HTML5 framework, there are at least three methods: first, draw a line using Canvas; second, add row and column attributes using DIV and CSS3; and third, use table labels.
Which one is the fastest and has less code? The answer is: the third type. Somewhat disappointed. HTML5 is not omnipotent. The Code is as follows:
 
This. board = function (name, width, height, rowBak, colBak) {/* draw a board */
NameBak = name;
If ("turnover" = name) {row = 8; col = 8;} else if ("gogame" = name) {row = 18; col = 18 ;}
Var aW = Math. floor (width/(col + 2), aH = Math. floor (height/(row + 2 ));
MinL = (aW> aH? AH: aW)-4; // This Subtraction is very important; otherwise, the table is extended during the filling.
Var array = new Array ("<div style = \" margin: "+ minL +" px; \ ">" +
"<Table border = 1 cellspacing = 0 width = \" "+ (aW * col) + "\"
Height = \ "" + (aH * row) + "\"> ");
For (var I = 0; I <row; I ++ ){
Array. push ("<tr> ");
For (var j = 0; j <col; j ++) {array. push ("<td align = center>" +
Evt (I, j, minL, minL, aW * j + minL/2 + 8, aH * I + minL/2) + "</td> ");}
If (nameBak! = "Four" & nameBak! = "Turnover")/* Add the event to the table */
Array. push (evt (I, col, minL, minL, aW * col + minL/2 + 8, aH * I + minL/2 ));
Array. push ("</tr> ");
}
If (nameBak! = "Four" & nameBak! = "Turnover "){
For (var j = 0; j <= col; j ++ ){
Array. push (evt (row, j, minL, minL, aW * j + minL/2 + 8, aH * row + minL/2 ));
}
}
Document. write (array. join ("") + "</table> </div> ");
SetClick (row, col, minL, minL);/* initialization event */
Start ();/* initialize the pawn */
}
In the above Code, the most important thing is the 6th lines of code marked in the black body. There are two tips: the first is the definition of table, and the second is the use of Array. Why use arrays instead of defining a string? The answer is optimization, that is, the push method of Array is much faster than the addition and operation of String strings. There are a total of 16 lines of code, and a chessboard is ready. Of course, this is not just a line drawing, but also a call to methods such as chess piece processing and event definition, which will be discussed later.
Draw chess pieces
After the Board is drawn, we will draw the pawns. The four chess games we selected are the same and both black and white chess games, even though they are different on the board. In the past, in addition to the beautiful effect of Flash, the online comparison was also implemented. In the HTML5 era, the artist must first make a few small pictures. In this case, the labor and communication costs of the artist are reduced.
We have at least two ways to draw a piece. The first is the canvas class, and the second is the css rounded corner attribute. Which speed and less code is used? The answer is second, rounded corner. The Code is as follows:
 
Function man (width, height, id, colorBak) {/* draw a pawn */
Var color = colorBak = null? (Order ++ % 2 = 0? "000": "CCC"): colorBak;
Var r = "border-radius:" + width/2 + "px ;";
Var obj = id = null? Event. srcElement: _ $ (id );
Obj. innerHTML = "<div id = \" man _ "+ color +" _ "+ order +" \ "style = \" display: block;-webkit -"
+ R + "-moz-" + r + "" + r + "-moz-box-shadow: inset 0-10px 40px rgba (0, 0, 0, 1);" +
"Box-shadow: inset 0-10px 40px rgba (0, 0, 0, 1);" +
"Background:-webkit-gradient (radial, 50 40, 30, center, 80, from (#" + color + "),
To (rgba (255,255,255, 1); "+
"Width:" + width + "px; height:" + height + "px; \"> </div> ";
}
In the code above, we can see that we define a DIV for each piece, use the shadow and gradient attributes of CSS3, and automatically calculate the size of the piece based on the size of the Board. In addition, if users do not like the black and white colors or even the red and yellow colors, girls and children may like them. The five lines of code are the method of drawing a piece. To do a simple loop, you can draw multiple pieces. The method is as follows.
 
Function moreMan (array) {for (var I = 0; I <array. length; I ++)
Man (minL, minL, nameBak + "_" + array [I]);}
/* Draw multiple pawns */
Event handling
After drawing the chessboard and pawns, let's analyze the user's actions. User Actions are nothing more than two types. One is to click the chessboard table, and the other is to click the chess part DIV. The difficulty is to click table here. We want to know the location where the user clicks table.
The traditional approach may be to use the event method to obtain the coordinates of x and y, then perform subtraction with the upper left corner of the table, and then perform division with cells. It sounds troublesome.
If you carefully read the previous code, you should find that, in fact, when drawing the board, we pushed an evt Method to the array, obviously, the evt method returns a string variable. What is its content? Answer:
 
Function evt (I, j, width, height, left, top) {/* single cell event */
Return "<div id = \" "+ nameBak +" _ "+ I +" _ "+ j +" \ "style = \" position: "+
(NameBak = "four" | nameBak = "turnover "? "Block": "absolute") +
"; Border: 0px solid #000; width:" +
Width + "px; height:" + height + "px; top:" + top + "px; left:" + left + "px; \ "> </div> ";
}
The principle is a DIV. By the way, the method for adding events is very special. In fact, a DIV is drawn at the intersection of each board, and then an event is added to the DIV.
 
Function setClick (row, col, width, height ){
For (var I = 0; I <= row; I ++ ){
For (var j = 0; j <= col; j ++ ){
Var els = _ $ (nameBak + "_" + I + "_" + j );
If (els! = Null) els. onclick = function () {if (rule () man (width, height );};
}
}
}
It must be noted that the DIV must be defined first, that is, output from document. write, and then the onclick definition can be executed. Otherwise, an undefined error of the DIV will be returned. A few 10 lines of code to solve the event problem.
Sub-rule
As mentioned above, there are two types of user click events. We use the method of adding a DIV to click the checker table event. What about the second method of clicking a piece?
The first thing to note is that clicking a piece is actually a wrong event. clicking a piece on the board can fall down. What does it mean to clicking a piece? It makes no sense to click a piece in the black and white games. We have to make judgments. It is one of the rules that we cannot fall into a child place. Therefore, you must define a method to determine whether there are pawns in the clicked place. The Code is as follows:
 
Function isMan (row, col) {var obj = _ $ (nameBak + "_" + row + "_" + col, 1 );
If (obj = null | obj. indexOf ("man _") =-1) return null;
Else if (obj. indexOf ("000 ")! =-1)
Return 0;
Else if (obj. indexOf ("CCC ")! =-1) return 1 ;}
I can't think of it. In fact, only one line of code can be used to determine whether there is a sub-judgment. The trick is to determine the color of the DIV. The chess piece is either black, 0 is returned, or white, 1 is returned, but there is no color in the blank space. null is returned. Special attention should be paid to the return value, which will be used later to determine whether or not there is a child through the return value of true or false, but to determine the color of the child.
This rule is enough for both Wuzi and go games. But there is also a second rule for playing and playing games: it cannot be left blank around, that is, it must be connected. That is to say, it is not only necessary to judge whether there is a pawn in the clicked place, but also whether there is a pawn around it. A small loop is required. The Code is as follows:
 
Function rule () {/* Playing Rules */
Var id = event. srcElement. id;
If (id. indexOf ("man _") = 0) {alert ("sub-accounts cannot be found"); return false;} else {
Var p = id. indexOf ("_"), p1 = id. lastIndexOf ("_");
Var row = id. substr (p + 1, p1-p-1) * 1, col = id. substr (p1 + 1) * 1;
If ("gobang" = nameBak) return gobang (row, col );
Else if ("four" = nameBak ){
If (isMan (row, col + 1) = null & isMan (row, col-1) = null &&
IsMan (row + 1, col) = null &&
IsMan (row-1, col) = null ){
Alert ("sizio cannot be left blank around! ");
Return false;
}
Return gobang (row, col, 3 );
} Else if ("turnover" = nameBak ){
If (isMan (row, col + 1) = null & isMan (row, col-1) = null &&
IsMan (row + 1, col) = null & isMan (row-1, col) = null &&
IsMan (row-1, col-1) = null &&
IsMan (row + 1, col + 1) = null ){
Alert ("the player cannot be left blank around! ");
Return false;
}
Turnover ();
} Else if ("gogame" = nameBak ){
}
}
Return true;
}
In the loop, the isMan method is called repeatedly to determine whether there are pawns. Therefore, if isMan is not concise and fast enough, it does not know how much time it will take. A total of 19 lines of code are processed as sub-rules.
At this point, we have drawn a board, a chess piece, obtained the click time, determined the Sub-rule, and used about 40 lines of code. In fact, the program is basically available, but we cannot satisfy them. We have to make him smarter. We also need a referee to win or lose.
Determine whether to win or lose
To determine whether to win or lose, we must know the rules for playing chess:
Wuziqi is a five-player game in all directions. The four-player game Game is a little more troublesome, not just the number of chess games, the number of surrounding areas is also large.
Logically, it seems complicated. It seems to be the most computation. It's a bit of artificial intelligence. Yes, if the previous foundation is not good, it will indeed take a lot of code, but because we have defined the iaMan Method for DIV to determine whether there is a pawn by color, we will use another tips here, you can easily determine whether to win or lose. Let's take a look at the winning or losing judgment code of wuziqi and siziqi, and analyze it against the code.
 
Function gobang (row, col, num ){
Num = null? 4: num;
Var rs = [[], [], [], [], B = [], w = [];/* the four-dimensional array is used to store the position of a pawn */
For (var I = 0, j = 0; I <num * 2 + 1; I ++, j ++ ){
Rs [0]. push (isMan (row-num + I, col ));
Rs [1]. push (isMan (row, col-num + j ));
Rs [2]. push (isMan (row-num + I, col-num + j ));
Rs [3]. push (isMan (row-num + I, col-num + j ));
If (I <num) {B. push (0); w. push (1 );}
}
If (rs. join ("#"). indexOf (B. join (","))! =-1) {alert (""); return false;
} Else if (rs. join ("#"). indexOf (w. join (","))! =-1) {alert (""); return false ;}
Return true;
}
A total of 9 lines of code can be done, understand? First, a Javascript multi-dimensional array rs = [[], [], [], [] is defined. This method defines multi-dimensional arrays, because no search engine can be found, almost all of the students I met in my class are unclear. Most of them use the new Array and then add the loop snail ing method.
Step 2: cycle from the place where the child falls. Note that it is time-saving instead of loop the entire board. The cycle is designed to push the color of the pawns to the four-dimensional array where the pawns are located.
Step 3: join the array. If four or five of them are connected, the white game wins. Otherwise, the black game wins.
Here, it is a bit interesting. Pay attention to the data processing method. I call it the "block data" processing method, which is to make full use of the array to save a piece of data, both data writing, reading, and statistical analysis are performed on this piece of data. This improves cohesion and facilitates the extraction of reusable methods, which greatly speeds up execution.
When processing connections, it is easier to use the block data processing method.
 
Function turnover (){
If (order <64) return;
Var num = 0; var total = row * col; for (var I = 0; I <row; I ++ ){
For (var j = 0; j <col; j ++) {num + = isMan (I + "_" + j );}
}
If (num <total/2) alert ("" + (total-num * 2) + "sub ");
Else if (num> row * col/2) alert ("White wins" + (num * 2-total) + "sub ");
Else alert ("Draw ");
}
Pawn Initialization
Here, the last question about chess pieces needs to be addressed. That is, the playing five games started from the blank board, but the other three games started with sub-games. In fact, you can also give a blank board, but the other three games are fixed because the previous steps are generally fixed. To improve intelligence, we have to waste four lines of code. After all, our goal is a market-oriented product, rather than a program for beginners not to consider the user experience.
 
Function start (){
If ("turnover" = nameBak) {moreMan ([3 + "_" + 3, 4 + "_" + 3, 4 + "_" + 3 + "_" + 4]);
} Else if ("four" = nameBak) {man (minL, minL, nameBak + "_" + row/2 + "_" + 0 );
} Else if ("gogame" = nameBak) {moreMan ([3 + "_" + 3, 15 + "_" + 3, 15 + "_" + 15, 3 + "_" + 15]);
}
}
In fact, the moreMan method is called. It is also a block data reference. An array is transmitted, and horizontal and vertical coordinates are separated by underscores.
Offline applications
As I said at the beginning of this article, there are already many dual-person or multi-person programs on desktop computers. Only mobile applications can have a market. Our goal is to come here, therefore, it must be used as an Offline Application.
How to Implement HTML5 offline applications, search engines can quickly find results, in fact, there are only three key steps.
Step 1: declare it in the Web server configuration file. The methods for declaring Tomcat and Apache are different. Note that;
Step 2: Define the manifest file. Pay attention to the file format;
Step 3: Call the manifest file in the HTML file.
Based on these three steps, you can search for details by yourself. I will not go into details here. I will only talk about what the search engine cannot find.
In addition, it should be noted that the methods for implementing full screen in browsers on iPad and Android tablets are different. For iPad users, we must also define a line of code that can implement full screen.
9. Online demonstration and open source code
As shown in:
Figure 1.


The figure shows a function for selecting the chess type and setting the background. To obtain all the source code, you only need to use the browser's function for viewing the source code. The function will not be pasted here due to space limitations.
Summary
As a programmer, the highest level does not mean that the more code you write, the better. Instead, you can use the least code to achieve the most computing and solve the most problems. In retrospect, Gates spent a long time coding the Basic program to save a few characters, so that it left the age of worms. In contrast, today, in the cloud computing era, with the increasing capacity of hard disks and memory, CPU computing is getting faster and faster, and programmers in many large projects seem to have lost the habit of streamlining code. However, mobile computing hardware is not yet well configured. This article uses the "block data" Calculation Method in HTML5 benchmark games to achieve the goal of achieving the most computing with the least code, it is especially applicable to mobile computing and is shared with everyone.
 

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.