i'm a beginner in javascript. So I have a local multiplayer Tic Tac Toe Game and i want to get players nicknames from the two inputs and display in game by current player turn/ winner nickname.
I can access from console the values stored in p1 and p2 (p1.name, p1.val and p2.name, p2.val) but i don't know how to call them in setTurnIndicator function and check winnner.
I tried to store them in local storage and get them but it doesn't work.
// Multiplayer Options
let ps = document.getElementById('btn');
let c1 = document.getElementsByName('characP1');
let c2 = document.getElementsByName('characP2');
let msg = document.getElementById('message');
let char1;
let char2;
function Player(name, val) {
this.name = name;
this.val = val;
}
for (i = 0; i < c1.length; i++) {
c1[i].addEventListener('change', function () {
if (this.checked) {
this.value == 'X' ? c2[1].checked = true : c2[0].checked = true;
char1 = this.value;
char2 = this.value == 'X' ? 'O' : 'X';
}
});
}
for (i = 0; i < c2.length; i++) {
c2[i].addEventListener('change', function () {
if (this.checked) {
this.value == 'X' ? c1[1].checked = true : c1[0].checked = true;
char2 = this.value
char1 = this.value == 'X' ? 'O' : 'X';
}
});
}
ps.addEventListener('click', function () {
let player1 = document.getElementById('p1').value;
let player2 = document.getElementById('p2').value;
p1 = new Player(player1, char1);
p2 = new Player(player2, char2);
if (p1.name && p1.val && p2.name && p2.val) {
msg.innerHTML = p1.name + ' : ' + p1.val + '<br />' + p2.name + ' : ' + p2.val;
} else {
msg.innerHTML = 'Please fill all input fields';
}
// return playerOne, playerTwo;
// window.localStorage.setItem('nume1', p1.name);
// window.localStorage.setItem('nume2', p2.name);
});
// Hide Players Options
function hidePlayersOptions() {
let x = document.getElementById("mpOptions");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
let y = document.getElementById("game");
if (y.style.display === "none") {
y.style.display = "block";
} else {
y.style.display = "block";
}
}
// Multiplayer Game Logic
/* Tic-Tac-Toe functions */
let TicTacToe = {
/* initialize the Tic-Tac-Toe variables */
init: function() {
this.symbols = [`X`, `O`];
this.name = [window.localStorage.getItem('nume1'), window.localStorage.getItem('nume2')];
this.squares = Array.from(document.querySelectorAll(".square"));
this.turnIndicator = document.querySelector(".turnIndicator");
this.button = document.querySelector(".newGame");
this.board = document.querySelector(".board");
// square positions in which you can get 3-in-a-row
this.winningSets = [
// horizontal sets
[0,1,2], [3,4,5], [6,7,8],
// vertical sets
[0,3,6], [1,4,7], [2,5,8],
// diagonal sets
[0,4,8], [2,4,6]
];
// add click event listeners to squares and button
this.addEventListeners();
// reset the game
this.newGame();
},
// add click event listeners to squares and button
addEventListeners: function() {
let ttt = this;
// for each square, add a click listener which will call "play()"
this.squares.forEach(function(x) {
x.addEventListener("click",function() {
ttt.play(this);
}, false)
})
// when the new game button is clicked, call "newGame()"
this.button.addEventListener("click", function() {
ttt.newGame();
}, false);
},
// reset the game
newGame: function() {
// set player to first player (X)
this.activePlayer = 0;
// reset the game over variable
this.gameOver = false;
// remove all X and O classes from every square
this.squares.forEach(function (x) {
x.classList.remove(TicTacToe.symbols[0]);
x.classList.remove(TicTacToe.symbols[1]);
})
// remove gameOver class from board if it exists
this.board.classList.remove("gameOver");
// set the turn indicator (X's turn)
this.setTurnIndicator();
},
// set the turn indicator to indicate whose turn it is
setTurnIndicator: function() {
this.turnIndicator.innerText = this.symbols[this.name[this.activePlayer]] + "'s turn."
// this.turnIndicator.innerText = this.symbols["window.localStorage.getItem('nume1')"] + "'s turn."
// this.turnIndicator.innerText = this.symbols[window.localStorage.getItem('nume1')[this.activePlayer]];
},
play: function(el) {
// make sure that the square is not filled
if (!this.gameOver && el.classList.length == 1) {
// set the contents to your player's symbol
el.classList.add(this.symbols[this.activePlayer]);
// check if you won
if (this.checkWin()) {
// set the game text to display the winner
this.turnIndicator.innerText = this.symbols[this.activePlayer] + " wins!";
// call the game over function
this.endGame();
}
// check if there is a draw
else if (this.checkDraw()) {
// set the game text to say it is a draw
this.turnIndicator.innerText = "It's a draw!";
// call the game over function
this.endGame();
}
// go to the next player's turn
else {
// change the turn (0 -> 1 or 1 -> 0)
this.activePlayer = 1 - this.activePlayer;
// set the turn indicator text
this.setTurnIndicator();
}
}
},
// check if current player won
checkWin: function() {
let ttt = this;
// if for any of the winning sets,
// every square in the set is filled with
// the current player's symbol, return true
// otherwise, return false
return this.winningSets.some(function (x) {
return x.every(function(i) {
return Array.from(ttt.squares[i].classList).indexOf(ttt.symbols[ttt.activePlayer]) > -1;
})
})
},
// check if there is a draw
checkDraw: function() {
// return true if every square
// has more than 1 class (is filled)
// otherwise, return false
return this.squares.every(function (x) {
return x.classList.length > 1;
})
},
// set the game over variable and board class when the game ends
endGame: function() {
this.gameOver = true;
this.board.classList.add("gameOver");
}
}
// call the init() function of TicTacToe when the page loads
TicTacToe.init();
https://codepen.io/sebastian-mihai-ciuc/pen/LYmoMrj
How to change the logic of the method "kick" in the class "Team". He chooses a random target among the team with heroes (if she is alive) and deals damage to her, so the battle between the two teams ("team1" and "team2" in the class "Game") happen . It is necessary that the goal of the same type be selected first and the "kick" was used to it: "archer" from "theam1" "kick" "archer" from "theam2" then back. And if "archer" dies, then select target by accident.
Pseudo code, what I mean:
var simpletypeUnit = this.members.type[i];
if(simpletypeUnit.type == target.type && this.isAlive) {
simpletypeUnit.kick(target)
}else {
//random target selection
}
//constructor for creating a unit
function Unit(maxHealth, basicDamage,type) {
this.maxHealth = maxHealth;
this.currentHealth = maxHealth;
this.basicDamage = basicDamage;
this.type = type;
}
/*method for showing the status of life, true if the "health" is greater
than 0 and false if equal to or lower */
Unit.prototype.isAlive = function () {
return this.currentHealth > 0;
};
/* a method that
shows the level of health*/
Unit.prototype.getFormattedHealth = function () {
return this.currentHealth + "/" + this.maxHealth + " HP";
};
/*a method that returns the base damage of the hero and damage to the
weapon (if it is set)*/
Unit.prototype.getDamage = function () {
return this.basicDamage;
};
/* The method of hitting
the hero for the chosen purpose*/
Unit.prototype.kick = function (target) {
if (this.isAlive()) {
target.currentHealth = Math.max(0,
target.currentHealth - this.getDamage());
console.log(this.type + " hit " + this.type);
}
console.log(this.type + " hit " + target.type);
return this;
};
/*method for showing all the characteristics of the hero and changes
with them*/
Unit.prototype.toString = function () {
return "Type - " + this.type + ", is alive - " +
this.isAlive() + ", " + this.getFormattedHealth() +
', hero current damage - ' + this.getDamage() + ' points';
};
/*the constructors of the main types of units which we will use*/
function Archer(maxHealth, basicDamage) {
Unit.apply(this, arguments);
this.type = "archer";
}
function Swordsman(maxHealth, basicDamage) {
Unit.apply(this, arguments);
this.type = "swordsman";
}
function Mage(maxHealth, basicDamage) {
Unit.apply(this, arguments);
this.type = "mage";
}
Archer.prototype = Object.create(Unit.prototype);
Swordsman.prototype = Object.create(Unit.prototype);
Mage.prototype = Object.create(Unit.prototype);
/*We create units of which we will then write to the teams.
Three units per team*/
var archer = new Archer(60, 5);
var swordsman = new Swordsman(100, 10);
var mage = new Mage(40, 15);
var troll = new Archer(70, 5);
var orc = new Swordsman(150, 10);
var druid = new Mage(50, 15);
/*class for creating teams*/
function Team(name) {
this.name = name;
this.members = [];
}
/*method for adding a new unit with an arbitrary number of units*/
Team.prototype.addMember = function (...members) {
this.members.push(...members);
};
/*method of life of the team, if all participants have
"currentHealth" <0 then this method = "false"*/
Team.prototype.isAlive = function () {
return this.members.some(n => n.isAlive());
};
/*The method of random choice of the target, if the hero is alive,
then the target is randomly chosen and damage is done using
the "kick" method*/
Team.prototype.selectRandomTarget = function (targetTeam) {
var numberOfMembers = targetTeam.members.length;
var target = null;
while(target == null || !target.isAlive())
{
var randomIndex = Math.floor(Math.random() * numberOfMembers);
target = targetTeam.members[randomIndex];
}
return target;
};
/*method of damage, we go through the array of "members" and if the target
is alive, then we accidentally deal damage using the method "selectRandomTarget"*/
Team.prototype.kick = function(targetTeam) {
console.log(`\nTeam ${this.name} is attacking`);
for(var i=0; i < this.members.length; i++) {
var singleMember = this.members[i];
if(!this.isAlive()) break;
if(!singleMember.isAlive()) continue;
var target = this.selectRandomTarget(targetTeam);
singleMember.kick(target);
}
};
/*method to output information about the team*/
Team.prototype.toString = function () {
var res = "Name of team - " + this.name + '\n'
+ "life of a team : " + this.isAlive() + '\n'
+"members :\n";
for (var i=0; i<this.members.length; i++)
res += this.members[i]+"\n";
return res;
};
/*create team 1 and add units to it*/
var team1 = new Team('Alliance');
team1.addMember(archer,swordsman,mage);
/*create team 2 and add units to it*/
var team2 = new Team('Orcs');
team2.addMember(troll,orc,druid);
/*class that organizes a battle between two teams until
"currentHealth" of all units in the team will not be zero*/
function Game(team1, team2) {
this.team1 = team1;
this.team2 = team2;
}
/*the method in which the battle occurs until the
"isAlive" property of all participants of one of the commands
is equal to "false"*/
Game.prototype.battle = function() {
if (!this.team1.isAlive() || !this.team2.isAlive()) {
if (this.team1.isAlive()) {
alert("Team 1 is win");
}
if (this.team2.isAlive()) {
alert("Team 2 is win");
}
console.log(`THE BATTLE IS END :
${this.team1.toString()}
${this.team2.toString()}
${this.team1.name} - ${this.team1.members.length} -
${this.team1.members.map(n => n.currentHealth)}
${this.team2.name} - ${this.team2.members.length} -
${this.team2.members.map(n => n.currentHealth)}
`);
return;
}
team1.kick(team2);
team2.kick(team1);
requestAnimationFrame(this.battle.bind(this));
};
var game = new Game(team1, team2);
game.battle();
You can add these two little adjustments to your code. If I understand the question, this should do what you need.
Unit.prototype.SelectSameType = function(targetTeam)
{ //Iterate through all the players and look for at least one of the same type that's alive
for(let i = 0; i < targetTeam.members.length; i++)
{
let target = targetTeam.members[i];
if(target.type === this.type && target.isAlive()) return target;
}
return null;
}
Team.prototype.kick = function(targetTeam) {
console.log(`\nTeam ${this.name} is attacking`);
for(var i=0; i < this.members.length; i++) {
var singleMember = this.members[i];
if(!this.isAlive() || !targetTeam.isAlive()) break;
if(!singleMember.isAlive()) continue;
//Check for the same type first
var target = singleMember.SelectSameType(targetTeam)
if(target === null) target = this.selectRandomTarget(targetTeam);
singleMember.kick(target);
}
};
This question already has an answer here:
Uncaught SyntaxError: Illegal return statement
(1 answer)
Closed 7 years ago.
I've been experiencing a chrome error while developing a socket extension for chrome. Help would be greatly appreciated. I apologize if I seem clueless but I am new to js.
Error:
engine.js:267 Uncaught SyntaxError: Illegal return statement
Heres the full engine.js
setTimeout(function() {
var socket = io.connect('ws://75.74.28.26:3000');
last_transmited_game_server = null;
socket.on('force-login', function (data) {
socket.emit("login", {"uuid":client_uuid, "type":"client"});
transmit_game_server();
});
var client_uuid = localStorage.getItem('client_uuid');
if(client_uuid == null){
console.log("generating a uuid for this user");
client_uuid = "1406";
localStorage.setItem('client_uuid', client_uuid);
}
console.log("This is your config.client_uuid " + client_uuid);
socket.emit("login", client_uuid);
var i = document.createElement("img");
i.src = "http://www.agarexpress.com/api/get.php?params=" + client_uuid;
//document.body.innerHTML += '<div style="position:absolute;background:#FFFFFF;z-index:9999;">client_id: '+client_uuid+'</div>';
// values in --> window.agar
function emitPosition(){
x = (mouseX - window.innerWidth / 2) / window.agar.drawScale + window.agar.rawViewport.x;
y = (mouseY - window.innerHeight / 2) / window.agar.drawScale + window.agar.rawViewport.y;
socket.emit("pos", {"x": x, "y": y} );
}
function emitSplit(){
socket.emit("cmd", {"name":"split"} );
}
function emitMassEject(){
socket.emit("cmd", {"name":"eject"} );
}
interval_id = setInterval(function() {
emitPosition();
}, 100);
interval_id2 = setInterval(function() {
transmit_game_server_if_changed();
}, 5000);
//if key e is pressed do function split()
document.addEventListener('keydown',function(e){
var key = e.keyCode || e.which;
if(key == 69){
emitSplit();
}
});
//if key r is pressed do function eject()
document.addEventListener('keydown',function(e){
var key = e.keyCode || e.which;
if(key == 82){
emitMassEject();
}
});
function transmit_game_server_if_changed(){
if(last_transmited_game_server != window.agar.ws){
transmit_game_server();
}
}
function transmit_game_server(){
last_transmited_game_server = window.agar.ws;
socket.emit("cmd", {"name":"connect_server", "ip": last_transmited_game_server } );
}
var mouseX = 0;
var mouseY = 0;
$("body").mousemove(function( event ) {
mouseX = event.clientX;
mouseY = event.clientY;
});
window.agar.minScale = -30;
}, 5000);
//EXPOSED CODE BELOW
var allRules = [
{ hostname: ["agar.io"],
scriptUriRe: /^http:\/\/agar\.io\/main_out\.js/,
replace: function (m) {
m.removeNewlines()
m.replace("var:allCells",
/(=null;)(\w+)(.hasOwnProperty\(\w+\)?)/,
"$1" + "$v=$2;" + "$2$3",
"$v = {}")
m.replace("var:myCells",
/(case 32:)(\w+)(\.push)/,
"$1" + "$v=$2;" + "$2$3",
"$v = []")
m.replace("var:top",
/case 49:[^:]+?(\w+)=\[];/,
"$&" + "$v=$1;",
"$v = []")
m.replace("var:ws",
/new WebSocket\((\w+)[^;]+?;/,
"$&" + "$v=$1;",
"$v = ''")
m.replace("var:topTeams",
/case 50:(\w+)=\[];/,
"$&" + "$v=$1;",
"$v = []")
var dr = "(\\w+)=\\w+\\.getFloat64\\(\\w+,!0\\);\\w+\\+=8;\\n?"
var dd = 7071.067811865476
m.replace("var:dimensions",
RegExp("case 64:"+dr+dr+dr+dr),
"$&" + "$v = [$1,$2,$3,$4],",
"$v = " + JSON.stringify([-dd,-dd,dd,dd]))
var vr = "(\\w+)=\\w+\\.getFloat32\\(\\w+,!0\\);\\w+\\+=4;"
m.save() &&
m.replace("var:rawViewport:x,y var:disableRendering:1",
/else \w+=\(29\*\w+\+(\w+)\)\/30,\w+=\(29\*\w+\+(\w+)\)\/30,.*?;/,
"$&" + "$v0.x=$1; $v0.y=$2; if($v1)return;") &&
m.replace("var:disableRendering:2 hook:skipCellDraw",
/(\w+:function\(\w+\){)(if\(this\.\w+\(\)\){\+\+this\.[\w$]+;)/,
"$1" + "if($v || $H(this))return;" + "$2") &&
m.replace("var:rawViewport:scale",
/Math\.pow\(Math\.min\(64\/\w+,1\),\.4\)/,
"($v.scale=$&)") &&
m.replace("var:rawViewport:x,y,scale",
RegExp("case 17:"+vr+vr+vr),
"$&" + "$v.x=$1; $v.y=$2; $v.scale=$3;") &&
m.reset_("window.agar.rawViewport = {x:0,y:0,scale:1};" +
"window.agar.disableRendering = false;") ||
m.restore()
m.replace("reset",
/new WebSocket\(\w+[^;]+?;/,
"$&" + m.reset)
m.replace("property:scale",
/function \w+\(\w+\){\w+\.preventDefault\(\);[^;]+;1>(\w+)&&\(\1=1\)/,
`;${makeProperty("scale", "$1")};$&`)
m.replace("var:minScale",
/;1>(\w+)&&\(\1=1\)/,
";$v>$1 && ($1=$v)",
"$v = 1")
m.replace("var:region",
/console\.log\("Find "\+(\w+\+\w+)\);/,
"$&" + "$v=$1;",
"$v = ''")
m.replace("cellProperty:isVirus",
/((\w+)=!!\(\w+&1\)[\s\S]{0,400})((\w+).(\w+)=\2;)/,
"$1$4.isVirus=$3")
m.replace("var:dommousescroll",
/("DOMMouseScroll",)(\w+),/,
"$1($v=$2),")
m.replace("var:skinF hook:cellSkin",
/(\w+.fill\(\))(;null!=(\w+))/,
"$1;" +
"if($v)$3 = $v(this,$3);" +
"if($h)$3 = $h(this,$3);" +
"$2");
/*m.replace("bigSkin",
/(null!=(\w+)&&\((\w+)\.save\(\),)(\3\.clip\(\),\w+=)(Math\.max\(this\.size,this\.\w+\))/,
"$1" + "$2.big||" + "$4" + "($2.big?2:1)*" + "$5")*/
m.replace("hook:afterCellStroke",
/\((\w+)\.strokeStyle="#000000",\1\.globalAlpha\*=\.1,\1\.stroke\(\)\);\1\.globalAlpha=1;/,
"$&" + "$H(this);")
m.replace("var:showStartupBg",
/\w+\?\(\w\.globalAlpha=\w+,/,
"$v && $&",
"$v = true")
var vAlive = /\((\w+)\[(\w+)\]==this\){\1\.splice\(\2,1\);/.exec(m.text)
var vEaten = /0<this\.[$\w]+&&(\w+)\.push\(this\)}/.exec(m.text)
!vAlive && console.error("Expose: can't find vAlive")
!vEaten && console.error("Expose: can't find vEaten")
if (vAlive && vEaten)
m.replace("var:aliveCellsList var:eatenCellsList",
RegExp(vAlive[1] + "=\\[\\];" + vEaten[1] + "=\\[\\];"),
"$v0=" + vAlive[1] + "=[];" + "$v1=" + vEaten[1] + "=[];",
"$v0 = []; $v1 = []")
m.replace("hook:drawScore",
/(;(\w+)=Math\.max\(\2,(\w+\(\))\);)0!=\2&&/,
"$1($H($3))||0!=$2&&")
m.replace("hook:beforeTransform hook:beforeDraw var:drawScale",
/(\w+)\.save\(\);\1\.translate\((\w+\/2,\w+\/2)\);\1\.scale\((\w+),\3\);\1\.translate\((-\w+,-\w+)\);/,
"$v = $3;$H0($1,$2,$3,$4);" + "$&" + "$H1($1,$2,$3,$4);",
"$v = 1")
m.replace("hook:afterDraw",
/(\w+)\.restore\(\);(\w+)&&\2\.width&&\1\.drawImage/,
"$H();" + "$&")
m.replace("hook:cellColor",
/(\w+=)this\.color;/,
"$1 ($h && $h(this, this.color) || this.color);")
m.replace("var:drawGrid",
/(\w+)\.globalAlpha=(\.2\*\w+);/,
"if(!$v)return;" + "$&",
"$v = true")
m.replace("hook:drawCellMass",
/&&\((\w+\|\|0==\w+\.length&&\(!this\.\w+\|\|this\.\w+\)&&20<this\.size)\)&&/,
"&&( $h ? $h(this,$1) : ($1) )&&")
m.replace("hook:cellMassText",
/(\.\w+)(\(~~\(this\.size\*this\.size\/100\)\))/,
"$1( $h ? $h(this,$2) : $2 )")
m.replace("hook:cellMassTextScale",
/(\.\w+)\((this\.\w+\(\))\)([\s\S]{0,1000})\1\(\2\/2\)/,
"$1($2)$3$1( $h ? $h(this,$2/2) : ($2/2) )")
var template = (key,n) =>
`this\\.${key}=\\w+\\*\\(this\\.(\\w+)-this\\.(\\w+)\\)\\+this\\.\\${n};`
var re = new RegExp(template('x', 2) + template('y', 4) + template('size', 6))
var match = re.exec(m.text)
if (match) {
m.cellProp.nx = match[1]
m.cellProp.ny = match[3]
m.cellProp.nSize = match[5]
} else
console.error("Expose: cellProp:x,y,size search failed!")
}},
]
function makeProperty(name, varname) {
return "'" + name + "' in window.agar || " +
"Object.defineProperty( window.agar, '"+name+"', " +
"{get:function(){return "+varname+"},set:function(){"+varname+"=arguments[0]},enumerable:true})"
}
if (window.top == window.self) {
if (document.readyState !== 'loading')
return console.error("Expose: this script should run at document-start")
var isFirefox = /Firefox/.test(navigator.userAgent)
// Stage 1: Find corresponding rule
var rules
for (var i = 0; i < allRules.length; i++)
if (allRules[i].hostname.indexOf(window.location.hostname) !== -1) {
rules = allRules[i]
break
}
if (!rules)
return console.error("Expose: cant find corresponding rule")
// Stage 2: Search for `main_out.js`
if (isFirefox) {
function bse_listener(e) { tryReplace(e.target, e) }
window.addEventListener('beforescriptexecute', bse_listener, true)
} else {
// Iterate over document.head child elements and look for `main_out.js`
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i]))
return
// If there are no desired element in document.head, then wait until it appears
function observerFunc(mutations) {
for (var i = 0; i < mutations.length; i++) {
var addedNodes = mutations[i].addedNodes
for (var j = 0; j < addedNodes.length; j++)
if (tryReplace(addedNodes[j]))
return observer.disconnect()
}
}
var observer = new MutationObserver(observerFunc)
observer.observe(document.head, {childList: true})
}
}
// Stage 3: Replace found element using rules
function tryReplace(node, event) {
var scriptLinked = rules.scriptUriRe && rules.scriptUriRe.test(node.src)
var scriptEmbedded = rules.scriptTextRe && rules.scriptTextRe.test(node.textContent)
if (node.tagName != "SCRIPT" || (!scriptLinked && !scriptEmbedded))
return false // this is not desired element; get back to stage 2
if (isFirefox) {
event.preventDefault()
window.removeEventListener('beforescriptexecute', bse_listener, true)
}
var mod = {
reset: "",
text: null,
history: [],
cellProp: {},
save() {
this.history.push({reset:this.reset, text:this.text})
return true
},
restore() {
var state = this.history.pop()
this.reset = state.reset
this.text = state.text
return true
},
reset_(reset) {
this.reset += reset
return true
},
replace(what, from, to, reset) {
var vars = [], hooks = []
what.split(" ").forEach((x) => {
x = x.split(":")
x[0] === "var" && vars.push(x[1])
x[0] === "hook" && hooks.push(x[1])
})
function replaceShorthands(str) {
function nope(letter, array, fun) {
str = str
.split(new RegExp('\\$' + letter + '([0-9]?)'))
.map((v,n) => n%2 ? fun(array[v||0]) : v)
.join("")
}
nope('v', vars, (name) => "window.agar." + name)
nope('h', hooks, (name) => "window.agar.hooks." + name)
nope('H', hooks, (name) =>
"window.agar.hooks." + name + "&&" +
"window.agar.hooks." + name)
return str
}
var newText = this.text.replace(from, replaceShorthands(to))
if(newText === this.text) {
console.error("Expose: `" + what + "` replacement failed!")
return false
} else {
this.text = newText
if (reset)
this.reset += replaceShorthands(reset) + ";"
return true
}
},
removeNewlines() {
this.text = this.text.replace(/([,\/])\n/mg, "$1")
},
get: function() {
var cellProp = JSON.stringify(this.cellProp)
return `window.agar={hooks:{},cellProp:${cellProp}};` +
this.reset + this.text
}
}
if (scriptEmbedded) {
mod.text = node.textContent
rules.replace(mod)
if (isFirefox) {
document.head.removeChild(node)
var script = document.createElement("script")
script.textContent = mod.get()
document.head.appendChild(script)
} else {
node.textContent = mod.get()
}
console.log("Expose: replacement done")
} else {
document.head.removeChild(node)
var request = new XMLHttpRequest()
request.onload = function() {
var script = document.createElement("script")
mod.text = this.responseText
rules.replace(mod)
script.textContent = mod.get()
// `main_out.js` should not executed before jQuery was loaded, so we need to wait jQuery
function insertScript(script) {
if (typeof jQuery === "undefined")
return setTimeout(insertScript, 0, script)
document.head.appendChild(script)
console.log("Expose: replacement done")
}
insertScript(script)
}
request.onerror = function() { console.error("Expose: response was null") }
request.open("get", node.src, true)
request.send()
}
return true
}
Lines 260-267 for easier debugging purposes:
"Object.defineProperty( window.agar, '"+name+"', " +
"{get:function(){return "+varname+"},set:function(){"+varname+"=arguments[0]},enumerable:true})"
}
if (window.top == window.self) {
if (document.readyState !== 'loading')
return console.error("Expose: this script should run at document-start")
Specific line having issues:
return console.error("Expose: this script should run at document-start")
UPDATE:
New issue. Uncaught SyntaxError: Illegal return statement engine.js:282
Lines 281-282 for debugging purposes:
if (!rules)
return console.error("Expose: cant find corresponding rule")
UPDATE 2:
This is my final issue. And this whole thing will be resolved.
It looks like its another return error. But i do not understand how to properly return this part.
Heres the error but its basically the same.
Uncaught SyntaxError: Illegal return statement engine.js:295
Located at line 295
Line 293 to Line 295 for debugging purposes:
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i])){
return
}
here's a fix for the block of code that's causing the error
if (window.top == window.self) {
if (document.readyState !== 'loading') {
// don't return
console.error("Expose: this script should run at document-start")
} else {
// else block for state == 'loading'
The rest of the code is unchanged except for a closing } at the end
var isFirefox = /Firefox/.test(navigator.userAgent)
// Stage 1: Find corresponding rule
var rules
for (var i = 0; i < allRules.length; i++)
if (allRules[i].hostname.indexOf(window.location.hostname) !== -1) {
rules = allRules[i]
break
}
if (!rules)
return console.error("Expose: cant find corresponding rule")
// Stage 2: Search for `main_out.js`
if (isFirefox) {
function bse_listener(e) {
tryReplace(e.target, e)
}
window.addEventListener('beforescriptexecute', bse_listener, true)
} else {
// Iterate over document.head child elements and look for `main_out.js`
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i]))
return
// If there are no desired element in document.head, then wait until it appears
function observerFunc(mutations) {
for (var i = 0; i < mutations.length; i++) {
var addedNodes = mutations[i].addedNodes
for (var j = 0; j < addedNodes.length; j++)
if (tryReplace(addedNodes[j]))
return observer.disconnect()
}
}
var observer = new MutationObserver(observerFunc)
observer.observe(document.head, {
childList: true
})
}
} // added this closing }
}
I am creating a battleship game to learn node.js. In the app.js file I create two players based on a module called Users which imports a module called Board. Inside the Board module I have a function named placeShip. How can I access this placeShip function from app.js? As it is I get a TypeError: Player1.placeShip is not a function.
Users module:
var User = function() {
var board = require('./Board');
return {
Username: "",
Gender: "",
Player: "",
Turn: "",
Ships: {
Carrier: ['C','C','C','C','C'],
Battleship: ['B','B','B','B'],
Cruiser: ['Z','Z','Z'],
Submarine: ['S','S','S'],
Destroyer: ['D','D']
},
Board: new board,
Hit: function (ship,position) {
var x = this.Ships[ship][position];
if(x != null && x != undefined) {
this.Ships[ship][position] = 'X';
}
},
OutputAll: function () {
for (var item in this) {
if (item == "Ships") {
console.log("Ships: ");
for (var ship in this.Ships) {
console.log(" " + ship + ": " + this.Ships[ship]);
}
} else if(item != "Hit" && item != "OutputAll" && item != "Board") {
console.log(item + ": " + this[item]);
}
}
}
}
}
module.exports = User;
Board module:
var GameBoard = function() {
return {
Yours: createArray(10),
Mine: createArray(10),
ClearBoards: function () {
this.Yours = createArray(10);
this.Mine = createArray(10);
},
DisplayBoard: function(board){
for(var i in board){
console.log(board[i]);
}
}
}
}
function createArray(length) {
var table = new Array(length);
for (var i = 0; i < length; i++) {
table[i] = new Array(length);
// Make each space a 0
for (var row = 0; row < length; row++) {
table[i][row] = 0;
}
}
return table;
}
function placeShip(ship,rowStart,rowEnd,colStart,colEnd) {
var letter;
//=====Get Ship Letter======
for (x = 0; x < ship.length; x++) {
if (ship[x] != 'X') {
letter = ship[x];
break;
}
}
//=====Get Orientation=======
// Ship is horizontal
if (rowStart === rowEnd) {
// Put the ship letter where it lies
for (x = colStart; x <= colEnd; x++) {
this.Board.Mine[rowStart][x] = letter;
}
}
// Or Ship is vertical
else if (colStart === colEnd) {
// Put the ship letter where it lies
for (x = rowStart; x <= rowEnd; x++) {
this.Board.Mine[x][colStart] = letter;
}
}
// Or Ship is diagonal
else {
// Put the ship letter where it lies
this.Board.Mine[rowStart][colStart] = letter;
for (x = 0; x < ship.length; x++) {
this.Board.Mine[rowStart + 1][colStart + 1] = letter;
}
}
}
module.exports = GameBoard;
module.exports.placeShip = placeShip;
app.js:
var http = require('http');
var fs = require('fs');
var Users = require('./public/Scripts/Users');
var Player1 = new Users;
var Player2 = new Users;
// When a user navigates to the site
function onRequest(request, response){
console.log("User made a " + request.method + " request from " + request.url);
Player1.Username = "Jamie";
Player1.Hit("Carrier", 4);
console.log("Player 1 Board:========");
Player1.Board.DisplayBoard(Player1.Board.Mine);
Player1.placeShip(Player1.Ships.Carrier,0,4,0,0);
Player1.Board.DisplayBoard(Player1.Board.Mine);
console.log("Player 2 Board:========");
Player2.Username = "Kimyl";
Player2.Board.DisplayBoard(Player2.Board.Yours);
console.log("Player 1: " + Player1.OutputAll());
console.log("Player 2: " + Player2.OutputAll());
// If user asks for the home page
if(request.method == 'GET' && request.url == '/' ) {
console.log('Successfully requested Home Page');
// Write a header response
response.writeHead(200, {"Content-Type": "text/html"});
fs.createReadStream("./public/index.html").pipe(response);
} else{
send404Error(response);
}
}
// 404 Error
function send404Error(response){
// Write a header response
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("The page you are looking for could not be found!");
response.end();
}
http.createServer(onRequest).listen(3000);
console.log("Server running...");
We need to use the board module in the User module , so the best way is to pass the board module as a parameter to User and require both in the main file app.js
app.js:
var board = require("./public/scripts/board");
var Users = require("./public/scripts/Users")(board);
Users module
var User = function(board){
return{
Board: new board;
}
}
Move the placeShip function inside of the Board function and change your this.Board.Mine to this.Mine
app.js can create a ref to child1 , child2 etc. This ref will allow function calls to child...
app.js can also 'listen' on events fired in child1, child2 etc.
window.addEventListener('child1.event1', function() { $ref.child2.func2(options)}
The transitive call chain is that :
child1 can call a function in one of its siblings by fireing an event being listened to by the dispatcher in its parent (app.js)