"HTML5 realization of Artificial intelligence" small game "well Word chess" released, it is said that IQ 200 to win "algorithm & Code explanation + Resources Package Download" __ Data structure

Source: Internet
Author: User
Tags abs addchild
One, what is tictactoe (well word chess)

This game for the next with lufylegend development of the second game. This game is everyone must have played as a child, because playing it is very simple, only need a draft paper and a pen can start the game, so widely welcomed by children. Perhaps I said for a long time, to its name unfamiliar friends do not understand I am talking about God horse. That's okay, I'll cite the wiki (Wikipedia) introduction as a recognition of its name, incidentally also reminds us of childhood memories:

Well word chess, the mainland, Taiwan is also known as the Well Word game, the Circle fork; In addition, there are drilling game, ox Chess title, Hong Kong more than Guan, too guan, is a kind of pen and paper game. Two players, a ring (O), a dozen forks (X), in turn in 3 times 3 of the lattice to play their own symbols, the first to horizontal, straight, oblique line is the victory. If both sides are right, the draw will be drawn. The game is actually controlled by the first player, the first player is the attack, and the second player is the one who defends. The first player in the corner of the first son words to win the biggest (see figure I), if the second player in the side, the corner, the first player can be a two-grain link to hold the second player, and then create "two snakes."


figure I


two, where the game plays.

I believe you have read the introduction on the Well word chess has an understanding. Now I use HTML5 to cooperate with open source game engine Lufylegend developed this game, and realized the artificial intelligence (AI) to make sure the player in the game can sew the opponent.

Next is the game online demo and download source address:

download address (including source code):Http://files.cnblogs.com/yorhom/Tic_Tac_Toe.rar

Online Demo Address:http://www.lufylegend.com/lufylegend_developers/yorhom_Tic_Tac_Toe/index.html


third, the game screenshot




four, game engine

This game uses the domestic lufylegend engine, the version is 1.6 1, if everybody is interested may go to the official website to see

Lufylegend official website:

Http://lufylegend.com/lufylegend

lufylegend API Documentation:

Http://lufylegend.com/lufylegend/api

There are downloads and API descriptions for this engine. Other articles about developing games with Lufylegend:

"HTML5 Game development" simple "find different Chinese version", to test your eyesight it


Five, Algorithm & code explanation

Let's start with a game initialization:

Init ("Mylegend", 390,420,main);

To facilitate manipulation of some of the data in the game, we set many variables:

var Backlayer,chesslayer,overlayer;
var statustext = new Ltextfield ();
var statuscontent= "You first please ...";
var matrix = [
	[0,0,0],
	[0,0,0],
	[0,0,0]
];
var Usersturn = true;
var step = 0;
var title = "Well word chess";
var introduction = ""
var infoarr = [Title,introduction];

The first row is a layer variable, the second row is an instantiated text box object that displays text, and the third line is the text that currently displays information, such as which side to go, which side wins, and so on, depending on the circumstances.

The matrix is an array of data that is used to hold the current checkerboard if the next move, it will change the data, by the way, in order to distinguish the "blank lattice", "Our position", "the location of the computer", we use-one to represent "our position", with 0来 on behalf of "Blank lattice", one to represent " The position under the computer "reader and remember, these -1,0,1 are represented in the chessboard array.

Userturn is used to determine whether the player can play chess, step is used to indicate the number of steps to determine whether the board is full, title,introduction and Infoarr was used to make about the interface, the result is finally even if, we directly ignore it.

And then there's the main function, because there's no picture, so there's no loading part:

function Main () {
	gameinit ();
	AddText ();
	Addlattice ();	
}
Several functions called by Main are as follows:

function Gameinit () {
	initlayer ();
	Addevent ();
}
function addtext () {
	statustext.size =;	
	Statustext.weight = "bold";
	Statustext.color = "White";
	Statustext.text = statuscontent;
	Statustext.x = (Lglobal.width-statustext.getwidth ()) *0.5;
	Statustext.y = 393;
	
	Overlayer.addchild (statustext);
}
function Addlattice () {
	backLayer.graphics.drawRect (ten, "Dimgray", [0,0,390,420],true, "Dimgray");
	BackLayer.graphics.drawRect ("Dimgray", [0,0,390,390],true, "Lavender");
	for (Var i=0;i<3;i++) {
		backLayer.graphics.drawLine (3, "Dimgray", [130*i,0,130*i,390]);
	}
	for (Var i=0;i<3;i++) {
		backLayer.graphics.drawLine (3, "Dimgray", [0,130*i,390,130*i]);
	}
Explain their function. First of all, Gameinit is used to initialize the game, including initializing layers of things. AddText is used to add the following text. Addlattice used to draw a chessboard. The code is simple and can be read with reference to the Lufylegend API documentation.

Next, let's look at the functions called in Gameinit:

function Initlayer () {
	backlayer = new Lsprite ();
	AddChild (Backlayer);

	Chesslayer = new Lsprite ();
	Backlayer.addchild (Chesslayer);

	Overlayer = new Lsprite ();
	Backlayer.addchild (Overlayer);
}
function addevent () {
	backlayer.addeventlistener (lmouseevent.mouse_down,ondown);
}
Initlayer is used to instantiate layers, which illustrates the point of instantiating Lsprite. Addevent is used to add click events.

Then let's take a look at the Ondown of the event trigger:

function Ondown () {
	var Mousex,mousey;
	MouseX = Event.offsetx;
	Mousey = event.offsety;

	var partx = Math.floor (mousex/130);
	var party = Math.floor (mousey/130);
	if (matrix[partx][party]==0) {
		usersturn=false;
		Matrix[partx][party]=-1;
		step++;
		Update (partx,party);
		
		if (Win (Partx,party)) {
			statuscontent = "handsome, you win." Click the screen to restart the game. ";
			Gameover ();
			AddText ();
		} else if (Isend ()) {
			statuscontent = "Draw ~ ~ Click the screen to restart the game." ";
			Gameover ();
			AddText ();
		} else{
			statuscontent = "The computer is thinking ...";
			AddText ();
			Computerthink ();}}
The function to do is to first remove the click Position, then according to the position of the point of a chess, and then will be in the chessboard array in the corresponding position of-1, indicating that we go, and then judge: after this move after the game or the draw, and call the corresponding function and display the corresponding text. Judge win, we use the win function, the code is as follows:

Function Win (x,y) {
	if (Math.Abs (matrix[x][0]+matrix[x][1]+matrix[x][2)) ==3) {return
		true;
	}
	if (Math.Abs (Matrix[0][y]+matrix[1][y]+matrix[2][y]) ==3) {return
		true;
	}
	if (Math.Abs (matrix[0][0]+matrix[1][1]+matrix[2][2]) ==3) {return
		true;
	}
	if (Math.Abs (matrix[2][0]+matrix[1][1]+matrix[0][2]) ==3) {return
		true;
	}
	return false;
}
First we judge Line X, and the absolute value of the number in the 0,1,2 column is 3 (because this function is used below, so we have to do the universal, so we use the absolute value). Why is it equal to 3. Because reader remember what we said above:-1 for "Our position", 0 for "blank grid" and 1 for "position under the computer". But where the chess is, the value is always 1 or 1, so if there are three pieces connected together, the absolute value of these values must be 3. So the return of true means win. If you have not been judged until the end, return false, the Representative has not won.

We use Isend to judge the draw, the code is as follows:

function Isend () {return
	step>=9;
}
The code is very simple, is to judge the board is not full.

The updata is used to update the chessboard. The code is as follows:

function Update (x,y) {
	var v = matrix[x][y];
	if (v>0) {
		CHESSLAYER.GRAPHICS.DRAWARC (ten, "green", [X*130+65,y*130+65,40,0,2*math.pi]);
	} else if (v<0) {
		chessLayer.graphics.drawLine, "#CC0000", [130*x+30,130*y+30,130* (x+1) -30,130* (y+1) -30]);
		ChessLayer.graphics.drawLine ("#CC0000", [130* (x+1) -30,130*y+30,130*x+30,130* (y+1) -30]);
	}

The above code is also very good understanding, is to take out the painting that point is what, if it is our painting (in the chessboard array is-1), in judgment, the value of the removal if less than 0, draw a fork. If more than 0 is the computer painting (representing 1 in the Checkerboard Array), draw a circle. The Gameover function is also used in the Ondown code as follows:

function Gameover () {
	backlayer.removeeventlistener (lmouseevent.mouse_down,ondown);
	Backlayer.addeventlistener (Lmouseevent.mouse_down,function () {
		chesslayer.removeallchild ();
		Backlayer.removechild (Chesslayer);
		Backlayer.removechild (Overlayer);
		RemoveChild (Backlayer);
		Matrix = [
			[0,0,0],
			[0,0,0],
			[0,0,0]
		];
		Step = 0;
		Main ();
		Statuscontent = "You first please ...";
		AddText ();
	});
Looks like the code is a bit long, in fact very simple, is simply remove all the objects on the interface, and restore some values to the default values. There is also the Computerthink function in Ondown, the code is as follows:

function Computerthink () {
	var b = Best ();
	var x = b.x;
	var y = b.y;
	Matrix[x][y]=1;
	step++;
	Update (x,y);
	
	if (Win (x,y)) {
		statuscontent = "Haha, you lost." Click the screen to restart the game. ";
		Gameover ();
		AddText ();
	} else if (Isend ()) {
		statuscontent = "Draw ~ ~ Click the screen to restart the game." ";
		Gameover ();
		AddText ();
	} else{
		statuscontent = "It's your time ... ";
		AddText ();
	}

First, the function uses the best function, which returns a position to go down, and then we set the corresponding position in the checkerboard array to 1, and take the steps +1. Then draw on the corresponding position. Then decide whether to win or draw, or not win or lose or draw. Best is the computer AI algorithm section, the code is as follows:

function Best () {
	var bestx;
	var besty;
	var bestv=0;
	for (Var x=0;x<3;x++) {for
		(var y=0;y<3;y++) {
			if (matrix[x][y]==0) {
				matrix[x][y] = 1;
				step++;
				if (Win (x,y)) {
					step--;
					Matrix[x][y] = 0;	
					return {' X ': x, ' y ': y, ' V ': 1000};
				} else if (Isend ()) {
					step--;
					matrix[x][y]=0;	
					return {' X ': x, ' y ': y, ' V ': 0};
				} else{
					var v=worst (). V;
					step--;
					matrix[x][y]=0;
					if (Bestx==null | | v>=bestv) {
						bestx=x;
						besty=y;
						Bestv=v
	}
	}}} return {' x ': bestx, ' y ': besty, ' V ': BesTV};
}
The idea of the algorithm is as follows: First we go through the checkerboard array, and then we judge if the grid that we're going to go to is empty (and the value is 0), let's assume the picture, and set the corresponding position in the checkerboard array to 1, indicating that the computer is down, and then the step number +1. The normal operation is over, and the next step is to give the next grading stage, the code is as follows:

if (Win (x,y)) {
	step--;
	Matrix[x][y] = 0;	
	return {' X ': x, ' y ': y, ' V ': 1000};
} else if (Isend ()) {
	step--;
	matrix[x][y]=0;	
	return {' X ': x, ' y ': y, ' V ': 0};
} else{
	var v=worst (). V;
	step--;
	matrix[x][y]=0;
	if (Bestx==null | | v>=bestv) {
		bestx=x;
		besty=y;
		Bestv=v
	}
}
First we judge if this is the next step, whether to win, if it is, the first to change the number of steps back, and the chessboard array to the next step before the board array (because we want to change in the Computerthink, so first change back to avoid heavy), and then return to the position of this step, And the score is 1000. Finally this process with return to achieve, return is God horse, I think it is needless to say. To judge whether or not to win, we used the win function, which has already been said.

But in case of this step did not win how to do, then judge whether it is a draw, how to become a draw. is to fill the entire chessboard and the other side did not win, they did not win is a draw. Because if someone wins, there will be no computer AI, it will not call the best function, in other words, it is impossible to go to this step; if the computer wins, in the superior judge has done the corresponding operation and with return has launched the function, also will not run to this step, so the direct judgement is not enough. So I used the isend function, and I used it, and I talked about it, and it's not wordy.

What if both of the above are wrong. Well, let's go to the next bar. But whatever you do, you can't mess around. Therefore, the use of worst to choose the "random" the best position. The code is as follows:

function worst () {
	var bestx;
	var besty;
	var BesTV = 0;
	for (Var x=0;x<3;x++) {for
		(var y=0;y<3;y++) {
			if (matrix[x][y) = = 0) {
				Matrix[x][y] =-1;
				step++;
				if (Win (x,y)) {
					step--;
					Matrix[x][y] = 0;	
					return {' X ': x, ' y ': y, ' V ': -1000};
				} else if (Isend ()) {
					step--;
					matrix[x][y]=0;	
					return {' X ': x, ' y ': y, ' V ': 0};;
				} else{
					var v=best (). V;
					step--;
					matrix[x][y]=0;
					if (Bestx==null | | v<=bestv) {
						bestx=x;
						besty=y;
						Bestv=v
	}
	}}} return {' x ': bestx, ' y ': besty, ' V ': BesTV};
}

This function and best are reversed, it is assumed that after a certain step, others will win or draw. If someone else is going to win, go back to this position and take this position first. A draw is the same principle as winning the other side, which is to fill out where it is wrong. The final interpretation is taken in the unlikely event that the other person wins, and the best function is the one. The best function has been said above. No explanation ~ ~ by worst This function returns a few values, the first and second is a random position, and the last one is the score. In best we receive these returns and judge by the score whether the choice is worse than the result of the draw, and return to the Computerthink function to paint the layout. So the process is very winding. It is not difficult for us to get a clear understanding of the relationship.


This is the time for this tutorial. Thanks for joining us.

If the game is abnormal, please contact me in time. Thank you for your support.

----------------------------------------------------------------

you are welcome to reprint my article.

Reprint Please specify: Transferred from Yorhom ' s Game Box

Welcome to keep an eye on my blog

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.