В этой статье описывается исходный код шахматных шахмат в мини -играх JS и обменивается с вами для вашей ссылки. Детали следующие:
После того, как игра запускается, показан следующий рисунок:
Раздел JavaScript:
/ ** Китайские шахматы * Автор: fdipzone * Дата: 2012-06-24 * ver: 1,0 */ var gameimg = ['Images/a1.gif', 'Images/a2.gif', 'Images/a3.gif', 'images/a4.gif', 'Images/a5.gif', 'Images/a6.gif', 'Images/a7.gif', 'Images/b1.gif', 'Images/b2.g if ',' Images/b3.gif ',' Images/b4.gif ',' Images/b5.gif ',' Images/b6.gif ',' Images/b7.gif ',' Images/bg.gif ',' Images/bg_over.gif ',' images/bg_sel.gif ']; var Chess_obj = new Chessclass (); window.onload = function () {$ ('init_btn'). onclick = function () {chess_obj.init (); } var callback = function () {chess_obj.init (); } img_preload (gameimg, обратный вызов); } // Функция Function Class Chessclass () {this.chess = []; this.boardrows = 4; this.boardcols = 8; this.area = 82; this.player = 1; // 1: красный 2: зеленый this.selected = null; // Выбранный шахмат this.chestype = ['', 'a', 'b']; this.isover = 0; } // init chessclass.prototype.init = function () {this.reset_grade (); this.create_board (); this.create_chess (); this.create_event (); this.player = 1; this.selected = null; this.isover = 0; disp ('init_div', 'Hide'); } // Создание платы chessclass.prototype.create_board = function () {var poard = ''; for (var i = 0; i <this.boardrows; i ++) {for (var j = 0; j <this.boardCols; j ++) {poard = poard + '<div id = "' + i + '_' + j + '"> <img src = "Images/schessbg.gif"/> </div>' "; }} $ ('alp'). innerhtml = poard; $ ('board'). style.width = this.boardcols * (this.area + 2) + 'px'; $ ('board'). style.height = this.boardrows * (this.area + 2) + 'px'; } // Создать случайные шахматные шахматы. ['a1', 'b7', 'a2', 'b7', 'a2', 'b7', 'a3', 'b7', 'a3', 'b7', 'a4', 'b6', 'a4', 'b6', 'a5', 'b5' 'a5', 'b5', 'a6', 'b4', 'a6', 'b4', 'a7', 'b3', 'a7', 'b3', 'a7', 'b2', 'a7', 'b2', 'a7', 'b1']; this.chess = []; while (Chesses.length> 0) {var rnd = math.floor (math.random ()*Chesses.length); var tmpchess = chemes.splice (rnd, 1) .toString (); this.chess.push ({'шахмат': tmpchess, 'type': tmpchess.substr (0, 1), 'val': tmpchess.substr (1,1), 'status': 0}); }} // Создать событие chessclass.prototype.create_event = function () {var self = this; var Chess_area = $ _tag ('div', 'board'); for (var i = 0; i <chess_area.length; i ++) {chess_area [i] .onmouseover = function () {// mouseover if (this.classname! = 'onsel') {this.classname = 'on'; }} chess_area [i] .onmouseout = function () {// mouseout if (this.classname! = 'onsel') {this.classname = ''; }} chess_area [i] .onclick = function () {// onclick self.action (this); }}} // ID изменение индекса chessclass.prototype.getindex = function (id) {var tid = id.split ('_'); вернуть Parseint (tid [0])*this.boardcols + parseint (tid [1]); } // ИНДЕКС Изменить ID Chessclass.prototype.getid = function (index) {return parseint (index/this.bordcols) + '_' + parseint (index%this.bordcols); } // action chessclass.prototype.action = function (o) {if (this.isover == 1) {// игра за возврат false; } var index = this.getIndex (o.id); if (this.selected == null) {// шахматная часть не выбрана, если (this.chess [index] ['status'] == 0) {// не открыл это .show (index); } else if (this.chess [index] ['status'] == 1) {// opened if (this.chess [index] ['type'] == this.chestype [this.player]) {this.select (index); }}} else {// Выбранный шахматный кусок if (index! = this.selected ['index']) {// выбрано не в одной и той же положении if (this.chess [index] ['status'] == 0) {// Неокрытый шахмат this.show (index); } else if (this.chess [index] ['status'] == -1) {// пустая позиция this.move (index); } else {// другие шахматные пьесы if (this.chess [index] ['type'] == this.chestype [this.player]) {this.select (index); } else {this.kill (index); }}}}}} // Показать шахматный шахматный класс. this.chess [index] ['status'] = 1; // открыт if (this.selected! = null) {// clear $ (this.getid (this.selected.index)). classname = '' '; this.selected = null; } this.Change_Player (); this.gameover (); } // Выберите Chess Chessclass.prototype.select = function (index) {if (this.selected! = null) {$ (this.getId (this.selected ['index'])). classname = ''; } this.selected = {'index': index, 'chance': this.chess [index]}; $ (this.getid (index)). classname = 'onsel'; } // Перемещать шахматный шахматный класс. 'Status': this.selected ['шахматы'] ['status']}; this.remove (this.selected ['index']); this.show (index); }} // Убить шахмат Chessclass.prototype.kill = function (index) {if (this.beside (index) == true && this.can_kill (index) == true) {this.chess [index] = {'warse': this.selected ['chance'] ['chems'], 'type': this.sele. 'val': this.selected ['шахматы'] ['val'], 'status': this.selected ['chare'] ['status']}; this.remove (this.selected ['index']); var убит = this.player == 1? 2: 1; $ ('grad_num' + убит) .innerhtml = parseint ($ ('grad_num' + убит) .innerhtml) -1; this.show (index); }} // Удалить Chess Chessclass.prototype.remove = function (index) {this.chess [index] ['status'] = -1; // пусто $ (this.getId (index)). innerhtml = ''; $ (this.getId (index)). classname = ''; } / * Проверка находится рядом с * @param индекс индекса часа. Если он пуст, выбранная шахматная часть считывается */ chessclass.prototype.beside = function (index, selindex) {if (typeof (selindex) == 'undefined') {if (this.selected! = Null) {selindex = this.selected ['index']; } else {return false; }} if (typeof (this.chess [index]) == 'undefined') {return false; } var from_info = this.getid (selindex) .split ('_'); var to_info = this.getid (index) .split ('_'); var fw = parseint (from_info [0]); var fc = parseint (from_info [1]); var tw = parseint (to_info [0]); var tc = parseint (to_info [1]); if (fw == tw && math.abs (fc-tc) == 1 || fc == tc && math.abs (fw-tw) == 1) {// row или colunm одинаковы, а интервал = 1 вернуть true; } else {return false; }} / * Проверка может убить * @param Индекс шахматных произведений, который был уничтожен * @param selindex. Индекс шахматного произведения, который был выполнен, может быть пустым, и если он пуст, выбранная шахматная пьеса считывается * / chessclass.prototype.can_kill = function (index, selindex) {if (selindex) = выполнено if (this.selected! = null) {// есть выбранная шахматная часть selindex = this.selected ['index']; } else {return false; }} if (this.chess [index] ['type']! = this.chestype [this.player]) {if (parseint (this.chess [selindex] ['val']) == 7 && parseint (this.chess [index] ['val']) == 1) {// 7 может убить 1 Вернуть true; } else if (parseint (this.chess [selindex] ['val']) == 1 && parseint (this.chess [index] ['val']) == 7) {// 1 не может убить 7 вернуть false; } else if (parseint (this.chess [selindex] ['val']) <= parseint (this.chess [index] ['val'])) {// small kill big return true; }} вернуть false; } // Изменение игрока chessclass.prototype.change_player = function () {if (this.player == 1) {this.player = 2; // green $ ('grade_img2'). classname = 'img_on'; $ ('grad_img1'). classname = 'img'; } else {this.player = 1; // red $ ('grade_img1'). classname = 'img_on'; $ ('grad_img2'). classname = 'img'; }} // сбросить класс chessclass.prototype.reset_grade = function () {$ ('grade_img1'). classname = 'img_on'; $ ('grad_img2'). classname = 'img'; $ ('grad_num1'). innerhtml = $ ('grad_num2'). innerhtml = 16; $ ('grad_res1'). classname = $ ('grade_res2'). classname = 'none'; $ ('grade_res1'). innerhtml = $ ('grad_res2'). innerhtml = '' '; } // game over shessclass.prototype.gameover = function () {if ($ ('grade_num1'). innerhtml == 0 || $ ('grade_num2'). innerhtml == 0) {// Часть шахмата - 0 this.isover = 1; this.show_grade (); disp ('init_div', 'show'); } else {if (this.can_action () == false) {this.isover = 1; this.show_grade (); disp ('init_div', 'show'); }}} // показать chrade chessclass.prototype.show_grade = function () {var num1 = parseint ($ ('grade_num1'). innerhtml); var num2 = parseint ($ ('grad_num2'). innerhtml); if (num1> num2) {// red square win $ ('grade_res2'). innerhtml = 'Потеря'; $ ('grad_res2'). classname = 'потеря'; $ ('grade_res1'). innerhtml = 'win'; $ ('grad_res1'). classname = 'win'; } else if (num1 <num2) {// Black Square Win $ ('grad_res1'). innerhtml = 'LOSS'; $ ('grad_res1'). classname = 'потеря'; $ ('grade_res2'). innerhtml = 'win'; $ ('grad_res2'). classname = 'win'; } else {// draw $ ('grad_res1'). innerhtml = $ ('grade_res2'). innerhtml = 'draw'; $ ('grad_res1'). classname = $ ('grade_res2'). classname = 'draw'; }} // Проверка шахмат CAN Действие Chessclass.prototype.can_action = function () {var Chess = this.chess; for (var i = 0, max = chess.length; i <max; i ++) {if (chance [i] .status == 0) {// Существует неоткрытая шахматная часть возврата true; } else {if (chare [i] .status == 1 && Chess [i] .type == this.chestype [this.player]) {// Шахматная пьеса, которую вы открыли if (this.beside (i-this.boardcols, i) && (Chess [i-this.boardcols] .status ==-1 | this.can_kill (i-this.boardcols, i))) {// return true; } if (this.beside (i+this.boardcols, i) && (chacess [i+this.boardcols] .status ==-1 || this.can_kill (i+this.bordcols, i))) {// return true; } if (this.beside (i+this.boardcols, i) && (chacess [i+this.boardcols] .status ==-1 || this.can_kill (i+this.bordcols, i))) {// return true; } if (this.beside (i-1, i) && (chance [i-1] .status ==-1 || this.can_kill (i-1, i))) {// Left return true; } if (this.beside (i+1, i) && (chare [i+1] .status ==-1 || this.can_kill (i+1, i))) {// right return true; }}}} вернуть false; } / ** Общая функция* / // получить document.getElementby (id) функция $ (id) {this.id = id; return document.getElementbyId (id); } // Получить document.getElementsbytagname function $ _tag (name, id) {if (typeof (id)! = 'undefined') {return $ (id) .getElementsbytagname (name); } else {return document.getElementsbytagname (name); }} / * div Показать и скрыть * @param id dom id * @param handle show или hide * / function disp (id, handle) {if (handle == 'show') {$ (id) .style.display = 'block'; } else {$ (id) .style.display = 'none'; }} /* img preload* @param img массив изображений для загрузки* @param метод обратного вызова после успешного загрузки изображения* / function img_preload (img, callback) {var onload_img = 0; var tmp_img = []; for (var i = 0, imgnum = img.length; i <imgnum; i ++) {tmp_img [i] = new image (); tmp_img [i] .src = img [i]; if (tmp_img [i] .complete) {onload_img ++; } else {tmp_img [i] .onload = function () {onload_img ++; }}} var et = setInterval (function () {if (onload_img == img.length) {// timer, обратный вызов callback clearInterval (et); callback ();}}, 200); }Нажмите здесь, чтобы загрузить полный пример кода.
Я полагаю, что описание в этой статье будет иметь определенную справочную ценность для каждого изучения дизайна игры JavaScript.