/**#nocode+*/ (function (global) { /**#nocode-*/ /** * Callbacks * * @namespace Callbacks */ var Callbacks = { callback: function (state) { // its own id var id = state.player.name, target, i, c, ok = false, fow = []; // looking for enemy in fow for (i = 0, c = state.fow.length; i < c; i += 1) { // push fow elements to 2d array, required for movements if (!fow[state.fow[i].y]) { fow[state.fow[i].y] = []; } fow[state.fow[i].y][state.fow[i].x] = state.fow[i].object; if (typeof state.fow[i].object === 'object' && state.fow[i].object.name !== id) { // found! target = { x: state.fow[i].x, y: state.fow[i].y }; } } if (target) { // target - shoot! Player.post({ action: 'shoot', // shoot action options: target, // enemy xy direction: state.player.direction // do not change direction }); } else { // no target - seeking for target // make random moves if (Math.random() > 0.5) { // move to x while (!ok) { // check if cell not occupied target = { x: state.player.x + (~~(Math.random() * 3) - 1), y: state.player.y }; if (typeof fow[target.y] === 'undefined' || typeof fow[target.y][target.x] === 'undefined' ) { ok = true; // cell is free } } } else { // or move to y while (!ok) { // check if cell not occupied target = { x: state.player.x, y: state.player.y + (~~(Math.random() * 3) - 1) }; if (typeof fow[target.y] === 'undefined' || typeof fow[target.y][target.x] === 'undefined' ) { ok = true; // cell is free } } } Player.post({ action: 'move', // move action options: target, direction: ~~(Math.random() * 5) // random direction }); } }, onHit: function (param) { }, onDamage: function (param) { }, onKill: function (param) { }, onDead: function () { } }; /** * Player * @namespace Player */ var Player = { post: function (data) { global.postMessage(JSON.stringify(data)); } }; /** * Message listener */ global.onmessage = function (e) { var data = JSON.parse(e.data); if (data.call && typeof Callbacks[data.call] === 'function') { Callbacks[data.call](data.arguments); } }; /**#nocode+*/ }(this)); /**#nocode-*/
Source: https://habr.com/ru/post/110540/
All Articles