"this" function with parameter - javascript

I've got a class Robot as defined below. But for some reason there's an error with the processCommand function and I can't figure out what it is. It's the only function that takes a parameter so I'm wondering if there's something wrong with the way I pass it in the readCommands function?
Any help or opinion is appreciated!
function Robot(pos){
this.pos = pos;
this.language;
this.printCoords = function(){}
this.setLanguage = function() {}
this.setPos = function() {}
this.processCommand = function(s){
var direction = this.pos[2];
direction = direction.replace(" ", "");
if( (s.match('V') && this.language.match("svenska")) ||
(s.match('L') && this.language.match("engelska")) ){
switch(direction){
case "N":
// Look West
this.pos[2] = " W";
break;
case "E":
// Look North
this.pos[2] = " N";
break;
case "S":
// Look East
this.pos[2] = " E";
break;
case "W":
// Look South
this.pos[2] = " S";
break;
default:
break;
}
}
else if( (s.match('H') && this.language.match("svenska")) ||
(s.match('R') && this.language.match("engelska")) ){
switch(direction){
case "N":
// Look East
this.pos[2] = " E";
break;
case "E":
// Look South
this.pos[2] = " S";
break;
case "S":
// Look West
this.pos[2] = " W";
break;
case "W":
// Look North
this.pos[2] = " N";
break;
default:
break;
}
}
else if( (s.match('G') && this.language.match("svenska")) ||
(s.match('F') && this.language.match("engelska"))){
switch(direction){
case "N":
// Walk North
this.pos[1] += 1;
break;
case "E":
// Walk East
this.pos[0] += 1;
break;
case "S":
// Walk South
this.pos[1] -= 1;
break;
case "W":
// Walk West
this.pos[0] -= 1;
break;
default:
break;
}
}
this.printCoords();
}
this.readCommands = function() {
document.getElementById("textField").onkeyup = function(key){
key = window.event;
keyCode = key.keyCode || key.which;
if(keyCode == '13'){
var commandString = document.getElementById("textField").value;
for(var i = 0; i < commandString.length; i++){
this.processCommand(commandString[i]);
}
}
}
}
}

I believe your event handler, (function(key){}) isn't doing what you want it to do.
This is because in the context of an event handler invocation, this usually refers to the DOM element on which the event occurred, not the instance of Robot.
Try this code instead:
this.readCommands = function() {
var that = this;
document.getElementById("textField").onkeyup = function(key){
key = window.event;
keyCode = key.keyCode || key.which;
if(keyCode == '13'){
var commandString = document.getElementById("textField").value;
for(var i = 0; i < commandString.length; i++){
that.processCommand(commandString[i]);
}
}
}
}
This way, you store a reference to the actual object you want to call the method processCommand() on, and can invoke it in the event handler.

using the old that=this trick:
function Robot(pos){
this.pos = pos;
this.language;
this.printCoords = function(){}
this.setLanguage = function() {}
this.setPos = function() {}
this.processCommand = function(s){
var direction = this.pos[2];
direction = direction.replace(" ", "");
if( (s.match('V') && this.language.match("svenska")) ||
(s.match('L') && this.language.match("engelska")) ){
switch(direction){
case "N":
// Look West
this.pos[2] = " W";
break;
case "E":
// Look North
this.pos[2] = " N";
break;
case "S":
// Look East
this.pos[2] = " E";
break;
case "W":
// Look South
this.pos[2] = " S";
break;
default:
break;
}
}
else if( (s.match('H') && this.language.match("svenska")) ||
(s.match('R') && this.language.match("engelska")) ){
switch(direction){
case "N":
// Look East
this.pos[2] = " E";
break;
case "E":
// Look South
this.pos[2] = " S";
break;
case "S":
// Look West
this.pos[2] = " W";
break;
case "W":
// Look North
this.pos[2] = " N";
break;
default:
break;
}
}
else if( (s.match('G') && this.language.match("svenska")) ||
(s.match('F') && this.language.match("engelska"))){
switch(direction){
case "N":
// Walk North
this.pos[1] += 1;
break;
case "E":
// Walk East
this.pos[0] += 1;
break;
case "S":
// Walk South
this.pos[1] -= 1;
break;
case "W":
// Walk West
this.pos[0] -= 1;
break;
default:
break;
}
}
this.printCoords();
}
var that=this;
this.readCommands = function() {
document.getElementById("textField").onkeyup = function(key){
key = window.event;
keyCode = key.keyCode || key.which;
if(keyCode == '13'){
var commandString = document.getElementById("textField").value;
for(var i = 0; i < commandString.length; i++){
that.processCommand(commandString[i]);
}
}
}
}
}

That's a lot of code to quickly glance at and surmise an answer. But, this errors are typically a result of this not having the value you think it should.
It's important to recognize that the value of this changes based on the calling context of the function. A typical solution to solve errors like this is to store the value of this in a variable that can be referenced later, i.e.;
var self = this;
and then use self instead of this directly.

Related

Unable to invoke JS function: Syntax mistake or eyes too crossed?

Happy holidays first of all.
I am unable to find the reason why I am unsuccessful at invoking the 'commands' function with its relative orders on this Javascript exercise. Have I messed up with the {}?
//// Rover object goes here ////
const rover = {
direction: "N",
x: 5,
y: 5,
travelLog: []
};
// ========================
//// Rover turns left switch case ////
function turnLeft(rover) {
switch (rover.direction) {
case "N":
rover.direction = "W";
break;
case "W":
rover.direction = "S";
break;
case "S":
rover.direction = "E";
break;
case "E":
rover.direction = "N";
break;
}
console.log("turnLeft was called!");
console.log(`Rover has now direction:"${rover.direction}"`);
}
//// Rover turns right switch case ////
function turnRight(rover) {
switch (rover.direction) {
case "N":
rover.direction = "E";
break;
case "W":
rover.direction = "N";
break;
case "S":
rover.direction = "W";
break;
case "E":
rover.direction = "S";
break;
}
console.log("turnRight was called!");
console.log(`Rover has now direction:"${rover.direction}"`);
}
//// Moving the rover ////
function moveForward(rover) {
console.log("moveForward was called!");
let newPosition = { x: rover.x, y: rover.y };
rover.travelLog.push(newPosition);
switch (rover.direction) {
case "N":
if (rover.y <= 0) {
console.log("you can't travel out there, bud");
} else {
rover.y--;
console.log(
`Rover moved North: position is now: ${rover.x} , ${rover.y}`
);
}
break;
case "E":
if (rover.x >= 9) {
console.log("you can't travel out there, bud");
} else {
rover.x++;
console.log(
`Rover moved East: position is now: ${rover.x} , ${rover.y}`
);
}
break;
case "S":
if (rover.y >= 9) {
console.log("you can't travel out there, bud");
} else {
rover.y++;
console.log(
`Rover moved South: position is now: ${rover.x} , ${rover.y}`
);
}
break;
case "W":
if (rover.x <= 0) {
console.log("you can't travel out there, bud");
} else {
rover.x--;
console.log(
`Rover moved West: position is now: ${rover.x} , ${rover.y}`
);
}
break;
}
}
//move backward//
function moveBackward(rover) {
console.log("moveBackward was called!");
let newPosition = { x: rover.x, y: rover.y };
rover.travelLog.push(newPosition);
switch (rover.direction) {
case "N": // Rover is facing North, but it will take one step backwards, hence direction South //
if (rover.y >= 9) {
console.log("watch your steps, don't trip");
} else {
rover.y++;
console.log(
`Rover moonwalked South: position is now: ${rover.x} , ${rover.y}`
);
}
break;
case "E": //moving direction South
if (rover.x <= 0) {
console.log("watch your steps, don't trip");
} else {
rover.x--;
console.log(
`Rover moonwalked West: position is now: ${rover.x} , ${rover.y}`
);
}
break;
case "S": // direction North
if (rover.y <= 0) {
console.log("watch your steps,don't trip");
} else {
rover.y--;
console.log(
`Rover moonwalked North: position is now: ${rover.x} , ${rover.y}`
);
}
break;
case "W": //direction East
if (rover.x >= 9) {
console.log("watch your steps, don't trip");
} else {
rover.x++;
console.log(
`Rover moonwalked East: position is now: ${rover.x} , ${rover.y}`
);
}
break;
}
//// Assigning commands ////
function commands(rover, orders) {
for (let i = 0; i < orders.length; i++) {
let order = orders[i];
switch (order) {
case "f":
moveForward(rover, order);
break;
case "b":
moveBackward(rover, order);
break;
case "r":
turnRight(rover, order);
break;
case "l":
turnLeft(rover, order);
break;
default:
console.log("Please use only 'r', 'f', 'b' or 'l'");
}
}
}
commands(rover,"ffbrl");
////printout all the rover's movements////
/*
for (let i = 0; i < rover.travelLog.length; i++) {
console.log(`Path ${i} ==> x=${rover.travelLog[i].x}, y=${rover.travelLog[i].y}`);
}
*/
}
Any input/suggestion will be greatly appreciated. I can't seem to find the mistake and it is quite infuriating. However, thank you again and have a lovely and festive time!
You need one more closing brace } at the end of the moveBackward function. You closed the switch statement but not the function.
Happy Holidays!

Keyboard Arrow Key Controls in Javascript

function control()
{
var ship = document.getElementById("ship");
document.onkeydown = function(e) {
switch (e.keyCode) {
case 38:
ship.style.top += "5%";
break;
case 40:
ship.style.top -= "5%";
break;
default:
break;
}
}
}
setInterval(control,1000);
This code is not working.
The object I'm trying to move is not moving when I'm pressing the Up & Down Arrow Key.
You can't do
ship.style.top += "5%";
because ship.style.top value is not a number but a string. the += opérator is concatening strings here.
You should do something like that:
const ship = document.getElementById("ship");
document.onkeydown = function (e) {
let winHeigth = window.innerHeight;
let top = ship.style.top;
switch (e.code) {
case "ArrowUp":
ship.style.top = (Number(top.substring(0, top.length - 2)) - (winHeigth / 20)) + "px";
break;
case "ArrowDown":
ship.style.top = (Number(top.substring(0, top.length - 2)) + (winHeigth / 20)) + "px";
break;
default:
break;
}
}
The position attribute of the "ship" must be like "relative".
By the way, e.keyCode is deprecated, you can use e.code instead ^^

Switch Statement running more than once

I'm back again, just as stumped as ever... I have gotten further with my game, but looking back at one part of the game, I have a check to see if you have potions, and if you do, and you try to use it, it calculates whether the current health and the added amount from the potion is more than the max health of the player. If it is then it tells you you cannot drink it, and if it isn't, then it lets you drink it. And then if you don't have any potions and you try to use it, then it tells you you don't have any.
The part I am having issue with, is that it is running twice, and I am not sure why. Here is a snippet of the Switch Statement:
while (currentarea == "Hero's Turn") {
if (hTurn == true) {
switch (classType) {
case "Warrior":
case "Archer":
switch (input) {
case "punch":
case "p":
Punch();
break;
case "kick":
case "k":
Kick();
break;
case "attack":
case "a":
Attack();
break;
case "health potion":
case "h":
HealthPotion();
break;
default:
}
case "Mage":
switch (input) {
case "fire":
case "f":
FireMagic();
break;
case "wind":
case "w":
WindMagic();
break;
case "frost":
case "c":
IceMagic();
break;
case "health potion":
case "h":
HealthPotion();
break;
case "mana potion":
case "m":
ManaPotion();
break;
default:
}
default:
}
return;
}
}
I tried to move the Archer to its own line and that just made it run three times. The issue is with the Warrior and Archer, the Mage only pushes the info once as intended.
This is the code for the function:
function HealthPotion() {
if (healthPotion.AmountOf < 1) {
$("<p>Sorry, you don't have any more of those.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
checkH();
return;
}
if (healthPotion.AmountOf != 0) {
if(battleHealth + healthPotion.Health <= maxHealth) {
$("<p>You regained some Health! You regained " + healthPotion.Health + " HP!</p>").hide().insertBefore("#placeholder").fadeIn(1000);
battleHealth += healthPotion.Health;
document.getElementById("battleHealth").innerHTML = battleHealth;
healthPotion.AmountOf--;
document.getElementById("healthPotion.AmountOf").innerHTML = healthPotion.AmountOf;
checkE();
return;
}
else {
$("<p>Your health isn't damaged enough for that! It would be a waste to use that right now.<br />Press enter to carry on.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
checkH();
return;
}
}
}
Here is how I have the potion constructed:
var healthPotion = { //Recovers battle HP.
Name: "Health Potion",
Health: 20,
AmountOf: 5,
Value: 30,
}
This is where the loops go to (the enemy and the hero check):
function checkE() {
if (eHealth >= 1) {
currentarea = "Enemy's Turn";
document.getElementById("currentarea").innerHTML = currentarea;
hTurn = false;
eTurn = true;
return;
}
else if (eHealth <= 0) {
eHealth = 0;
document.getElementById("eHealth").innerHTML = eHealth;
currentarea = "Death";
win++;
document.getElementById("win").innerHTML = win;
hTurn = false;
eTurn = false;
return;
}
}
function checkH() {
if (battleHealth >= 1) {
currentarea = "Battle";
document.getElementById("currentarea").innerHTML = currentarea;
eTurn = false;
hTurn = true;
return;
}
else if (battleHealth <= 0) {
battleHealth = 0;
document.getElementById("battleHealth").innerHTML = battleHealth;
currentarea = "Death";
document.getElementById("currentarea").innerHTML = currentarea;
lose++;
document.getElementById("lose").innerHTML = lose;
return;
}
}
At this point I am completely stumped, as I have switch statements and nested functions in all of my coding at this point, but this is the only area I am seeing this issue.
My main browser is Firefox, but I I tested on Chrome and Edge, which both have the same results. IE will not play my game, mainly because I haven't coded it to do so yet.
I looked around at other's questions before posting here, and didn't see anything that matched up to this particular issue.
Looking in the Admin Console of each browser, no error was thrown, just the multiple lines of repeated verbage.
If you keep playing and taking damage enough to use the potion, you see this:
You break out of the inner switch, that break does nothing for the outer switch so when you have "Warrior" it does that case and since there is no break at its level, it goes to "Mage"
switch (classType) {
case "Warrior":
case "Archer":
switch (input) {
case "punch":
case "p":
Punch();
break;
case "kick":
case "k":
Kick();
break;
case "attack":
case "a":
Attack();
break;
case "health potion":
case "h":
HealthPotion();
break;
default:
}
break; // <-- YOU NEED THIS HERE
case "Mage":
switch (input) {
case "fire":
case "f":
FireMagic();
break;
case "wind":
case "w":
WindMagic();
break;
case "frost":
case "c":
IceMagic();
break;
case "health potion":
case "h":
HealthPotion();
break;
case "mana potion":
case "m":
ManaPotion();
break;
default:
}
break; // <-- YOU NEED THIS HERE IF YOU DO SOMETHING IN DEFAULT
default:
}

Limitations of Javascript or simple error?

While re creating a game in the style of ZORK recently, I have come across a problem and have no idea what is causing it or how to deal with it.
I used a while loop on a prompt box, comparing the user input against a switch() case, and returning a response. I have been building on it for some time now and there is over 600 lines of JavaScript.
After adding a few more lines for another element of the game, I noticed that the script suddenly quit in the middle of using it (meaning that the prompt did not show again.) This had not ever happened before with any previous versions, and I triple checked for errors, but could not find any. I looked up JavaScript limitations on certain browsers and it said that 5,000,000 was the maximum allowed statements. I did not think that only 600 lines, even looping, could amount to that much after only a minute or two of usage.
So I am stumped. I don't know what is causing this problem or how to fix it or work around it. I ran it through a js minifier and got the same result as before.
//FNIJ V0.9
function officeintro() {
alert('You are sitting in your office. There are two doors, one to the left and one to the right. They are both open.');
}
function intro() {
alert('Welcome to Five Nights in Javascript!');
alert('This game is a javascript recreation of Five Nights at Freddy\'s created by Scott Cawthon, and inspired by the game ZORK.\n\nPlease remember to not click \"Prevent this page from creating additional dialogs\". This will quit the game.');
var gameconf = confirm('Are you familiar with Five Night at Freddy\'s? \n\nClick OK for yes, Cancel for no.');
switch (gameconf) {
case false:
alert('Here is the description from Steam:\n\nWelcome to your new summer job at Freddy Fazbear\'s Pizza, where kids and parents alike come for entertainment and food as far as the eye can see! The main attraction is Freddy Fazbear, of course; and his two friends. They are animatronic robots, programmed to please the crowds! The robots\' behavior has become somewhat unpredictable at night however, and it was much cheaper to hire you as a security guard than to find a repairman.');
alert('From your small office you must watch the security cameras carefully. You have a very limited amount of electricity that you\'re allowed to use per night (corporate budget cuts, you know). That means when you run out of power for the night- no more security doors and no more lights! If something isn\'t right- namely if Freddybear or his friends aren\'t in their proper places, you must find them on the monitors and protect yourself if needed!');
alert('Five Nights at Freddys is better explained by either watching a gameplay video or playing the actual game.');
alert('I recommend watching Pewdiepie or Markiplier (\my favorite)\ playing the game. Remember that this game is based off of the first game.');
alert('The official game can be downloaded from "gg.gg/getfnaf", without the quotes.');
break;
case true:
break;
}
var ctrlconf = confirm('Would you like to hear the controls? \n\nClick OK for yes, Cancel for no.');
switch (ctrlconf) {
case true:
alert('You will be given a prompt box in which you can type commands.');
alert('Most command will be intuitive, such as \'Open cam\', \'Close left door\', \'Check left light\' , etc.');
alert('Some command can also be abbrevated. For example, \'Close cam\' can be abrivated to \'CC\'.');
alert('You\'re all set! Let\'s get started!');
officeintro();
break;
case false:
alert('You\'re all set! Let\'s get started!');
officeintro();
break;
}
}
function gameplay() {
var stS = 1;
var stM = 1;
var stH = 1;
var time = 12;
var c = "Chica";
var f = "Freddy";
var b = "Bonnie";
var cf = "Chica and Freddy";
var fb = "Bonnie and Freddy";
var cb = "Chica and Freddy";
var cbf = "Bonnie, Chica and Freddy";
var n = "Nothing";
var showstage = cbf;
var backstage = n;
var supplycloset = n;
var diningarea = n;
var pirate = "Foxy";
var whall = n;
var whallcorner = n;
var rr = n;
var kitchen = n;
var ehall = n;
var ehallcorner = n;
var lastcamsee = showstage;
var llight = n;
var rlight = n;
var goldfred = false;
var leftdoor = "open";
var rightdoor = "open";
var cam = "closed";
var lastcam = "showstage";
var look = "your office";
var playing = true;
var night = 1;
var pwruse = 1;
var power = 99;
var pwrrate = 0;
var disppwr = 99;
function initTime() {
var now = new Date();
stS = now.getSeconds();
stM = now.getMinutes();
stH = now.getHours();
}
function computeTime() {
var now = new Date();
var reS = now.getSeconds();
var reM = now.getMinutes();
var reH = now.getHours();
var elapS = reS - stS;
var elapM = reM - stM;
var elapH = reH - stH;
if (elapM < 0) {
reM = reM + 60;
elapM = reM - stM;
}
if (elapS < 0) {
reS = reS + 60;
elapS = reS - stS;
}
var finalH = elapH * 3600;
var finalM = elapM * 60;
var finalS = finalM + elapS + finalH;
if (finalS > 86 && finalS < 172) {
time = 1;
}
if (finalS > 172 && finalS < 258) {
time = 2;
}
if (finalS > 258 && finalS < 344) {
time = 3;
}
if (finalS > 344 && finalS < 430) {
time = 4;
}
if (finalS > 430 && finalS < 516) {
time = 5;
}
if (finalS > 516) {
time = 6;
alert('5 A.M.');
alert('A clock is chiming...');
alert('6 A.M.');
var advn = confirm('Start next night?\n\nOK for yes, Cancel for no.');
switch (advn) {
case true:
night++;
initTime();
setVars();
break;
default:
playing = false;
alert('Thanks for playing! Goodbye!');
}
}
}
function initPwr() {
var nowpwr = new Date();
stpS = nowpwr.getSeconds();
stpM = nowpwr.getMinutes();
stpH = nowpwr.getHours();
}
function computePwr() {
var nowpwr = new Date();
var repS = nowpwr.getSeconds();
var repM = nowpwr.getMinutes();
var repH = nowpwr.getHours();
var elappS = repS - stpS;
var elappM = repM - stpM;
var elappH = repH - stpH;
if (elappM < 0) {
repM = repM + 60;
elappM = repM - stpM;
}
if (elappS < 0) {
repS = reppS + 60;
elappS = repS - stpS;
}
var finalpH = elappH * 3600;
var finalpM = elappM * 60;
var finalpS = finalpM + elappS + finalpH;
if (pwruse == 1) {
pwrrate = .141;
}
if (pwruse == 2) {
pwrrate = .235;
}
if (pwruse == 3) {
pwrrate = .341;
}
if (pwruse == 4) {
pwrrate = .447;
}
var pwrsxr = finalpS * pwrrate;
power = power - pwrsxr;
disppwr = Math.floor(power);
}
function stopCall() {
document.getElementById('call').pause();
}
function playcall() {
document.getElementById('call').play();
}
function curiousAlert() {
alert('Error.\n\n How did you even get here?.\n Please email charles.fecht#outlook.com with an explanation.');
}
initTime();
while (playing) {
computeTime();
initPwr();
var combox = prompt('Night: ' + night + ' \nTime: ' + time + ' A.M.\nPower Left: ' + disppwr + '%\nUsage: Lvl ' + pwruse + '\n\nGive a command');
combox.toLowerCase();
switch (combox) {
case "help":
alert('Help: \n\nFor a list of commands, type \'Com\' or \'Commands\'.\n\nIf you press the CANCEL button on the prompt box at any time, the game will be terminated.\n\nDue to the limitations of JavaScript, character movements are not functional. I am working towards a solution, so this will be fixed in a future update. ');
alert('UPDATE: \n\nI have figured out a workaround for the time mechanism!\n The time will work now!');
break;
case "time":
alert('The time is ' + time + ' A.M.');
break;
case "open door":
alert('Open which door?');
break;
case "status":
case "stat":
case "stats":
alert('Status:\n\Time: ' + time + ' A.M.\nNight: ' + night + '\nPower Left: '+disppwr+' % \nPower usage: ' + pwruse + '.\nCamera is ' + cam + '.\nLeft door: ' + leftdoor + '. \nRight door: ' + rightdoor + '. \nYou are looking at ' + look + '.\nThe last viewed camera: ' + lastcam + '.');
break;
case "com":
case "commands":
case "command":
alert('Here is a complete list of commands\n\nAny multiple word phrases can be used by abbreviating them \n\nHelp: Calls up the help menu \nCom: Shows this menu\nExit: Quits the game\nOpen Cam: Opens the security camera\nClose Cam: Closes the Security camera\nLook: Check what is in front of you\nOpen & Close Left/Right door: Self explanatory\nStatus: Show the status of the doors, time, power usage, etc.\nCams: Displays a complete list of camera names.');
break;
case "cams":
case "cam":
alert('Here is a list of camera angles. Use them by typing the full name or abreviating them.\n\nShowstage\nBackstage\nRestrooms\nPirate Cove\nDining area\nKitchen\nSupply closet\nWest Hall\nWest Hall corner\nEast Hall\nEast Hall corner\n');
break;
case "open cam":
case "open camera":
case "oc":
switch (cam) {
case "open":
alert('Your camera is already open');
break;
default:
pwruse++;
cam = "open";
look = "the camera";
alert('Camera is open. You are looking at ' + lastcam + '. ' + lastcamsee + ' is here.');
}
break;
case "left light":
case "ll":
case "check left light":
case "check ll":
case "cll":
//pwruse++;
alert('Checked the left light. ' + llight + ' appears.');
break;
case "right light":
case "rl":
case "check right light":
case "check rl":
case "crl":
//pwruse++;
alert('Checked the right light. ' + rlight + ' appears.');
break;
case "power use":
case "pu":
case "power usage":
alert('Power usage is at level ' + pwruse + '.');
break;
case "answer phone":
case "phone call":
case "answer call":
alert('You found an easter egg!');
var callplay = true;
playcall();
var askcall = confirm('Do you hear the phone call?\n\nOK for yes, Cancel for no.');
switch (askcall) {
case true:
alert('Back to the game then!');
break;
default:
alert('Then it should load when the game is over.');
}
alert('To stop the audio, type "mute".');
break;
case "mute":
stopCall();
break;
case "close cam":
case "close camera":
case "cc":
switch(cam) {
case "open":
switch (goldfred) {
case true:
cam = "closed";
look = "golden freddy";
alert('Camera is closed. You are looking at Golden Freddy.');
alert(' ');
alert('IT\'S ME');
alert(' ');
playing = false;
var i = 5;
while (i <= 0) {
console.log(i);
i++;
}
break;
case false:
cam = "closed";
pwruse--;
look = "your office";
alert('Camera is closed. You are looking at your office. The left door is ' + leftdoor + '. The right door is ' + rightdoor + '.');
break;
} break;
case "closed": alert('Your camera is already closed'); break;}
break;
case "look":
switch (look) {
case "your office":
alert('You are looking at ' + look + '. The left door is ' + leftdoor + ' and the right door is ' + rightdoor + '.');
break;
case "the camera":
alert('You are look at ' + lastcam + '.');
}
break;
case "old":
case "open left door":
case "open ld":
switch (cam) {
case "open":
alert('You cannot do that. Your camera is open.');
break;
case "closed":
switch (leftdoor) {
case "open":
alert('The door is already open');
break;
case "closed":
leftdoor = "open";
pwruse--;
alert('Left door open');
break;
}
break;
default:
curiousAlert();
}
break;
case "find golden freddy":
switch (look) {
case "the camera":
goldfred = true;
alert('You are looking at west hall corner. The poster of freddy has been painted gold.');
break;
default:
alert('Please open your camera first');
}
break;
case "cld":
case "close left door":
case "close ld":
switch (cam) {
case "open":
alert('You cannot do that. Your camera is open.');
break;
case "closed":
switch (leftdoor) {
case "closed":
alert('The left door is already closed');
break;
case "open":
pwruse++;
leftdoor = "closed";
alert('Left door closed');
break;
}
break;
default:
curiousAlert();
}
break;
case "ord":
case "open right door":
case "open rd":
switch (cam) {
case "open":
alert('You cannot do that. Your camera is open.');
break;
case "closed":
switch (rightdoor) {
case "open":
alert('The right door is already open');
break;
case "closed":
rightdoor = "open";
pwruse--;
alert('Right door open');
break;
}
break;
default:
curiousAlert();
}
break;
case "crd":
case "close right door":
case "close rd":
switch (cam) {
case "open":
alert('You cannot do that. Your camera is open.');
break;
case "closed":
switch (rightdoor) {
case "closed":
alert('The right door is already closed');
break;
case "open":
pwruse++;
rightdoor = "closed";
alert('Right door closed');
break;
}
break;
default:
curiousAlert();
}
break;
case "showstage":
case "ss":
switch (look) {
case "the camera":
lastcam = "the showstage";
lastcamsee = showstage;
alert('You are looking at the showstage. ' + showstage + ' is here.');
break;
default:
alert('Please open your camera first');
}
break;
case "dining area":
case "da":
switch (look) {
case "the camera":
lastcam = "dining area";
lastcamsee = diningarea;
alert('You are looking at the dining area. ' + diningarea + ' is here.');
break;
default:
alert('Please open your camera first');
}
break;
case "backstage":
case "bs":
switch (look) {
case "the camera":
lastcam = "backstage";
lastcamsee = backstage;
alert('You are looking backstage. ' + backstage + ' is here.');
break;
default:
alert('Please open your camera first');
}
break;
case "pirate cove":
case "pc":
switch (look) {
case "the camera":
lastcam = "pirate cove";
lastcamsee = pirate;
alert('You are looking at pirate cove. ' + pirate + ' is here.');
break;
default:
alert('Please open your camera first');
}
break;
case "restrooms":
case "restroom":
case "rr":
case "rest rooms":
case "rest room":
switch (look) {
case "the camera":
lastcamsee = rr;
lastcam = "restroom";
alert('You are looking at the rest rooms. ' + rr + ' is here.');
}
break;
case "supply closet":
case "sc":
switch (look) {
case "the camera":
lastcam = "supply closet";
lastcamsee = supplycloset;
alert('You are looking at the supply closet. ' + supplycloset + ' is here.');
break;
default:
alert('Please open your camera first');
}
break;
case "kitchen":
switch (look) {
case "the camera":
lastcam = "kitchen";
lastcamsee = kitchen;
alert('The camera is disabled. You are listening to the kitchen. You hear ' + kitchen + '.');
break;
default:
alert('Please open your camera first');
}
break;
case "ehc":
case "east hall corner":
switch (look) {
case "the camera":
lastcam = "east hall corner";
lastcamsee = ehallcorner;
alert('You are looking at the east hall corner. ' + ehallcorner + ' is here.');
break;
default:
alert('Please open your camera first');
}
break;
case "eh":
case "east hall":
switch (look) {
case "the camera":
lastcam = "east hall";
lastcamsee = ehall;
alert('You are looking at the east hall. ' + ehall + ' is here.');
break;
default:
alert('Please open your camera first');
}
break;
case "whc":
case "west hall corner":
switch (look) {
case "the camera":
lastcam = "west hall corner";
lastcamsee = whallcorner;
alert('You are looking at the west hall corner. ' + whallcorner + ' is here.');
break;
default:
alert('Please open your camera first');
}
break;
case "wh":
case "west hall":
switch (look) {
case "the camera":
lastcam = "west hall";
lastcamsee = whall;
alert('You are looking at the west hall. ' + whall + ' is here.');
break;
default:
alert('Please open your camera first');
}
break;
case "exit":
var close = confirm('Do you really want to quit?');
switch (close) {
case true:
alert('Thanks for playing! Goodbye!');
playing = 0;
break;
case false:
break;
default:
curiousAlert();
}
break;
case false:
alert('Please enter something. If you are trying to quit the game, type EXIT.');
break;
default:
alert('I didn\'t understand that. Use "com" for a complete list of commands or "help" for more help.');
} //End of switch statement
computePwr();
} //End of while loop
} //End of Gameplay Function
intro();
gameplay();
<audio id="call" src="https://89d0b33f6a3e9119d631e45a4b55916d65742a63.googledrive.com/host/0B-uT9QTKkBoRM2pONTNHSHZiZmM/call.mp3" preload="auto"></audio>
You really should learn to use the console in your browser. I just played it for a little bit with the console open, and got an error:
Uncaught ReferenceError: reppS is not defined
In your computePwr function, you have a variable named repS, but one time you typed it as reppS.
repS = reppS + 60;
Corrected:
repS = repS + 60;
Next time, you should check your console. You could also run your code through jslint, which will catch simple typos and other errors.

Keyboard Error Sound when catching KeyCode

I'm programming something withe Javascript which captures keyboard input, but the problem is that every time the user presses a key there an error sound. How can I disable it?
#Polaris878
function KeyPressed(e)
{
if (!e) e = window.event;
if (e.which)
{
keycode = e.which
}
else if (e.keyCode)
{
keycode = e.keyCode
}
switch (keycode)
{
case 49:
key = "1";
break;
case 50:
key = "2";
break;
case 51:
key = "3";
break;
case 52:
key = "4";
break;
case 53:
key = "5";
break;
case 54:
key = "6";
break;
case 55:
key = "7";
break;
case 56:
key = "8";
break;
case 57:
key = "9";
break;
case 48:
key = "0";
break;
default:
key = "";
return false;
break
}
if (keys == "NULL")
{
keys = key
}
else
{
keys = keys + key
} if (keys.length >= 5)
{
document.formular.submit();
}
document.formular.code.value = keys;
}
var keys = "";
document.onkeydown = KeyPressed

Categories

Resources