H5 version of Tetris (3)---game AI algorithm

Source: Internet
Author: User
Tags hasownproperty

Objective:
"Long long Ago" thing, a famous internet company in our school held a "Lengend code" game, one of the questions is "smart Tetris." In the spirit of always gan to do the denominator, the green spirit of the shining molecule, and really hit a soy sauce on the ground. This time borrow study H5 opportunity, again to revisit the Russian block AI writing .
The articles in this series are linked as follows:
1). Demand analysis and target innovation
2). The basic framework and implementation of the game
These blog posts and code are basically synchronous, not sure whether the demand will change, whether the progress is shelved, but the wing can insist and realize.

Demo & Download:
This version is still relatively humble, the effect:
  
Its code is: Http://pan.baidu.com/s/1sjyY7FJ
Download the Extract directory structure as follows:
  
Click Tetris.html to run on the browser (due to the HTML5 program, it is best to run on Chrome/firefox).

Algorithm Analysis:
The core algorithms refer to the following blog posts:
• Traditional rules Tetris AI technology Introduction
• Console color version of "Tetris" with AI
The program also uses the improved Pierre dellacherie algorithm ( considering only the current block ).

Its assessment of the situation, using 6 indicators:
1).Landing height (drop altitude): The height where the piece is put (= the height of the column + (the height of the PIECE/2))
2).rows Eliminated (number of rows): The number of rows eliminated.
3).Row transitions (line transform): The total number of row transitions. A row transition occurs when an empty cell was adjacent to a filled cell on the same row and vice versa.
4).column transitions (row transform): The total number of column transitions. A column transition occurs when an empty cell was adjacent to a filled cell on the same column and vice versa.
5).number of Holes (voids): A hole is an empty cell, the have at least one filled cell above it in the same column.
6).Well Sums (number of Wells): A well is a succession of empty cells such this their left cells and right cells are both filled.

Weighted sum of the various indicators, weighted coefficients are taken from empirical values:

1-4.500158825082766 2 3.4181268101392694 3-3.2178882868487753 4-9.348695305445199 5-7.899265427351652 6-3 .3855972247263626

Source code interpretation:
Coding file structure:

  tetris_base.js : Public data structure,  including block definitions and block pools,
  tetris_ai.js : Defines the core algorithms and data structures of AI.
  tetris_game.js : The entire program is displayed and driven.
This side of the main talk about tetris_ai.js This code file, there are three important classes, Movegenerator, Evaluator, Aistrategy.
Movegenerator is used to generate each feasible landing point and the corresponding path line:

    /* * @brief Go Generator */function Movegenerator () {} MoveGenerator.prototype.generate = function (te        Trisunit, shape) {var keymapfunc = function (x, y, idx) {return "" + x + ":" + y + ":" + idx;        } var movemapfunc = function (step) {return {x:step.x, y:step.y, idx:step.idx};        } var results = [];        var boards = Tetrisunit.boards;        var rownum = Tetrisunit.row;        var colnum = Tetrisunit.col;        var shapearrs = shape.shapes;        var occupy = {} var actionqueues = [];        Actionqueues.push ({x:shape.x, y:shape.y, Idx:shape.idx, prev:-1});        Occupy[keymapfunc (shape.x, Shape.y, shape.idx)] = true;        var head = 0;            while (Head < actionqueues.length) {var step = Actionqueues[head]; 1).            Move left one step var tx = step.x-1;            var ty = step.y;            var tidx = Step.idx; if (Tetrisunit.checkavailable (TX, Ty, ShapearrS[TIDX]) {var key = Keymapfunc (TX, Ty, TIDX);                    if (!occupy.hasownproperty (key)) {Actionqueues.push ({x:tx, y:ty, Idx:tidx, prev:head});                Occupy[key] = true; }}//2).            Move Right One step tx = step.x + 1;            ty = step.y;            Tidx = Step.idx;                if (Tetrisunit.checkavailable (TX, Ty, Shapearrs[tidx])) {var key = Keymapfunc (TX, Ty, TIDX);                    if (!occupy.hasownproperty (key)) {Actionqueues.push ({x:tx, y:ty, Idx:tidx, prev:head});                Occupy[key] = true; }}//3).            Rotate one step tx = step.x;            ty = step.y;            Tidx = (step.idx + 1)% 4;                if (Tetrisunit.checkavailable (TX, Ty, Shapearrs[tidx])) {var key = Keymapfunc (TX, Ty, TIDX); if (!occupy.hasownproperty (key)) {Actionqueues.push ({X:tx, Y:ty, Idx:tidx, prev:head});                Occupy[key] = true; }}//4).            Move down one step tx = step.x;            ty = step.y + 1;            Tidx = Step.idx;                if (Tetrisunit.checkavailable (TX, Ty, Shapearrs[tidx])) {var key = Keymapfunc (TX, Ty, TIDX);                    if (!occupy.hasownproperty (key)) {Actionqueues.push ({x:tx, y:ty, Idx:tidx, prev:head});                Occupy[key] = true;                }} else {//*) If it cannot be down, it is an end node of the block.                var tmpmoves = [];                Tmpmoves.push (Movemapfunc (step));                var tprev = Step.prev;                    while (Tprev! =-1) {Tmpmoves.push (Movemapfunc (Actionqueues[tprev]));                Tprev = Actionqueues[tprev].prev;                } tmpmoves.reverse ();            Results.push ({last:step, moves:tmpmoves});    } head++;    } return results; }

  Evaluator, the previous evaluation factors are integrated:

    function Evaluator () {    }    Evaluator.prototype.evaluate = function (boards) {    }    function Pierredellacherieevaluator () {    }    Pierredellacherieevaluator.prototype = new Evaluator ();    PierreDellacherieEvaluator.prototype.constructor = Pierredellacherieevaluator;    PierreDellacherieEvaluator.prototype.evaluate = function (boards, shape) {        return (-4.500158825082766) * Landingheight (Boards, shape)          //Drop height                + (3.4181268101392694) * rowseliminated (Boards, shape)      //number of rows                + ( -3.2178882868487753) * rowtransitions (boards)            /Line transform                + ( -9.348695305445199) * Coltransitions ( Boards)             //Column change                + ( -7.899265427351652) * Emptyholes (boards)                 //Hole number                + (-3.3855972247263626) * Wellnums (boards);                 Number of Wells    }

Aistrategy integrates floor builder and evaluate function for the specific decision-making point, and the action Route .

    function Aistrategy () {this.generator = new movegenerator ();    This.evalutor = new Pierredellacherieevaluator (); }/* * @brief make the best strategy * @return {dest:{x:{x}, y:{y}, Idx:{idx}}, [{action_list}]} */Aistrategy.protot        Ype.makebestdecision = function (Tetrisunit, shape) {var bestmove = null;        var bestscore =-1000000;        1) Generate all feasible landing point, and the corresponding path line var allmoves = this.generator.generate (Tetrisunit, shape);             2) traverse each feasible landing point, select the optimal situation of the landing point for (var i = 0; i < allmoves.length; i++) {var step = allmoves[i].last;            var shapearrs = shape.shapes;            var bkboards = Tetrisunit.applyaction2data (step.x, STEP.Y, Shapearrs[step.idx]); 2.1) Evaluate each potential situation var Tscore = This.evalutor.evaluate (Bkboards, {x:step.x, y:step.y, Shapearr:shapearrs[step.            IDX]}); 2.2) Select the best placement and path for the update if (bestmove = = = NULL | | Tscore > Bestscore) {bestscore = Tscore;                Bestmove = allmoves[i].moves;     }}//3) returns the best possible landing point, and its path line return {score:bestscore, action_moves:bestmove}; }

Note: This code annotation interprets the entire process of the decision function.

Effect Evaluation:
The AI algorithm has a good effect, in the demo mode, ran all night, still live well. This also satisfies the needs and functions that were previously desired.

Summarize:
The weighted coefficients of the algorithm are based on empirical values. Of course, the simulation annealing algorithm can also be used to learn the parameters, but due to the game itself, the uncertainty/contingency effect, the convergence effect is not as good as expected. Have the opportunity to speak again.
In any case, the AI can play a qualified "trouble maker", making the game fun and challenging. Don't forget beginner's mind, let's go!!!

Written at the end:
  
If you think this article is helpful to you, please give it a little reward. In fact, I would like to try to see if blogging can bring me a little bit of revenue. No matter how much, is a kind of sincere affirmation to the landlord.

H5 version of Tetris (3)---game AI algorithm

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.