Need help correcting a function in text game - javascript

I'm trying to teach myself how to code a simple text game. I found a YouTube tutorial and am working my way through Der Kerker. A problem I have is that his final code doesn't match what he did in the videos, so I'm stuck.
Here's my problem:
When you load the game, the commands "take sword" and "help" both work as designed. However, if you put in jibberish or an unrecognized command, the game is supposed to say, "I don't understand ... "
Right now, it only clears the input box but doesn't actually run the command.
Here's my fiddle of the game:
https://jsfiddle.net/megler/hv7hqp1e/
If I remove the (check == false) portion - then the "I don't understand" part will work. However, if you type "help" - it will run the help segment AND say "I don't understand help."
The goal is for it to only say "I don't understand" if the player types in an unrecognized command.
Here's the JS:
//Check To See If True Function
var check = false;
// Been To Room Variables
var beenToCorridor = true;
//
//Inventory
var sword = false;
//
//Current Room
var currentRoom = "nCorridor";
$(document).ready(function() {
$("form").submit(function() {
var input = $("#commandLine").val();
function check() {
check = true;
}
if (input == "help") {
$("#messageHelp")
.clone()
.insertBefore("#placeholder")
.fadeIn(1000);
check();
}
if (input == "take sword" && currentRoom == "nCorridor") {
$("<p>You picked up a sword.</p>")
.hide()
.insertBefore("#placeholder")
.fadeIn(1000);
check();
}
else if (input == "take sword" && currentRoom != "nCorridor") {
$("<p>The sword is not here.</p>")
.hide()
.insertBefore("#placeholder")
.fadeIn(1000);
check();
}
else if (check == false) {
$("<p>I don't understand " + input + ".</p>")
.hide()
.insertBefore("#placeholder")
.fadeIn(1000);
}
$("#commandLine").val("");
});
});
Hope that makes sense.

I think this is what you want:
Code Replaced:
else if (input != "take sword" && input != "help") {
$("<p>I don't understand " + input + ".</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
Snippet:
//Check To See If True Function
var check = false;
// Been To Room Variables
var beenToCorridor = true;
//
//Inventory
var sword = false;
//
//Current Room
var currentRoom = "nCorridor";
$(document).ready(function() {
$("form").submit(function() {
var input = $("#commandLine").val();
function check() {
check = true;
}
if (input == "help") {
$("#messageHelp").clone().insertBefore("#placeholder").fadeIn(1000);
check();
}
if (input == "take sword" && currentRoom == "nCorridor") {
$("<p>You picked up a sword.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
}
else if (input == "take sword" && currentRoom != "nCorridor") {
$("<p>The sword is not here.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
}
else if (input != "take sword" && input != "help") {
$("<p>I don't understand " + input + ".</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
else
{
return false;
}
$("#commandLine").val("");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="console">
<p id="message_startGame">Welcome to my game!</p>
<p id="area_northCorridor">You are in the North Corridor. There is a sword on the ground.</p>
<p id="messageHelp" style = "display: none;">Here is a list of commands</p>
<!-- PLACEHOLDER: THIS IS WHERE EVERYTHING WILL BE INSERTED BEFORE
--->
<div id="placeholder"></div>
<form onsubmit="return false;">
<input type = "text" size ="50" autofocus="autofocus" id="commandLine">
</form>
</div>
</body>

Use different name for check variable. You should also separate last else if.
//Check To See If True Function
var _check = false;
// Been To Room Variables
var beenToCorridor = true;
//
//Inventory
var sword = false;
//
//Current Room
var currentRoom = "nCorridor";
$(document).ready(function() {
$("form").submit(function() {
var input = $("#commandLine").val();
function check() {
_check = true;
}
if (input == "help") {
$("#messageHelp")
.clone()
.insertBefore("#placeholder")
.fadeIn(1000);
check();
}
if (input == "take sword" && currentRoom == "nCorridor") {
$("<p>You picked up a sword.</p>")
.hide()
.insertBefore("#placeholder")
.fadeIn(1000);
check();
}
else if (input == "take sword" && currentRoom != "nCorridor") {
$("<p>The sword is not here.</p>")
.hide()
.insertBefore("#placeholder")
.fadeIn(1000);
check();
}
if (_check == false) {
$("<p>I don't understand " + input + ".</p>")
.hide()
.insertBefore("#placeholder")
.fadeIn(1000);
}
$("#commandLine").val("");
});
});

You should
first initialize var check = false; somewhere, otherwise the if condition never passes
add an else to your list of if ... else if ... checks.
Here's is the corrected code:
$(document).ready(function () {
$("form").submit(function () {
var input = $("#commandLine").val();
// INITIALIZE CHECK VARIABLE HERE
var check = false;
function check() {
check = true;
}
if (input == "help") {
$("#messageHelp").clone().insertBefore("#placeholder").fadeIn(1000);
check();
}
// NEEDS AN ADDITIONAL ELSE HERE TO PREVENT DOUBLE MESSAGE AFTER HELP
else if (input == "take sword" && currentRoom == "nCorridor") {
$("<p>You picked up a sword.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
} else if (input == "take sword" && currentRoom != "nCorridor") {
$("<p>The sword is not here.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
} else if (check == false) {
$("<p>I don't understand " + input + ".</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
$("#commandLine").val("");
});
});

Reset the check variable back to false every time the form is submitted, so you s=tart from a clean slate each time it is called. Also rename your function 'check' to 'setChecked' to not cause confusion between the global variable and the local function name.
$("form").submit(function() {
check = false;
function setChecked() {
check = true;
}
if (input == "help") {
setChecked();
}
//etc...
}

It's because you redefine 'check' as a function, so it's not equal to false anymore.
The solution is to use another name for your boolean, for example 'ischeck', like this:
//Check To See If True Function
var ischeck = false;
// Been To Room Variables
var beenToCorridor = true;
//
//Inventory
var sword = false;
//
//Current Room
var currentRoom = "nCorridor";
$(document).ready(function() {
$("form").submit(function() {
var input = $("#commandLine").val();
function check() {
ischeck = true;
}
if (input == "help") {
$("#messageHelp").clone().insertBefore ("#placeholder").fadeIn(1000);
check();
}
if (input == "take sword" && currentRoom == "nCorridor") {
$("<p>You picked up a sword.</p>").hide().insertBefore ("#placeholder").fadeIn(1000);
check();
}
else if (input == "take sword" && currentRoom != "nCorridor") {
$("<p>The sword is not here.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
check();
}
else if (ischeck == false) {
$("<p>I don't understand " + input + ".</p>").hide().insertBefore("#placeholder").fadeIn(1000);
}
$("#commandLine").val("");
});
});

Related

TypeError: Cannot read property 'target' of undefined, error received for checking if a div has not already been filled

Trying to make TicTacToe for an assignment, I'm pretty new to JavaScript, any help would be appreciated:
//onlick event listner
document.getElementById('board').addEventListener('click', handleTurn);
function addMarker(e){
if(e.target.textContent == fill.EMPTY){ //error shows up for this line specifically
count++;
if (count == 1 || count == 3 || count == 5 || count == 7 || count == 9){
playerTurn = fill.X;
document.getElementById("switch").innerHTML = "It's O's turn";
}
else {
playerTurn = fill.O;
document.getElementById("switch").innerHTML = "It's X turn";
}
e.target.textContent = playerTurn;
}
else{
alert('cannot click here, choose a free square!');
}
e.stopPropagation();
handleTurn();
render();
}
Check for the existence of target.
if(e.target && e.target.textContent == fill.EMPTY)
And return if no parameter given, when no event or such.
function addMarker(e){
if(!e) return;
if ...

HTML checkbox on/off detection in JavaScript

I have made a solar system simulation and have some 'settings' which the user can change. I have made it so the settings only update when the save button is pressed. This works and the bodies are hidden if a box is checked but say for example, i checked mercury and saved the changes then wanted to check Venus as well when i save the changes Venus is hidden but Mercury is shown again. how can i make it so that Mercury stays hidden until the box in uncheked.
(note the check boxes decide whether a planet should be hidden or not so hideMer for example when true would stop drawing mercury onto the canvas)
code which i think the issue applies to:
function animate() {
//clears canvas each new loop
if (showPath==false){
c.clearRect(-innerWidth/2,-innerHeight/2,innerWidth,innerHeight);
}
hideBodies = [hideMer, hideVen, hideEar, hideMar, hideJup, hideSat, hideUra, hideNep];
drawSun();
for (var i=0; i< xPosList.length; i++){
leapfrog(i);
if (hideBodies[i]==false){
drawBody(i);
}
}
}
function saveChanges() {
showPath=(document.getElementById("showPath").value=="True");
//Mercury
if (document.getElementById("mer").checked && hideMer == false){
hideMer = true;
} else if (document.getElementById("mer").checked && hideMer == true){
hideMer = false;
}
//Venus
if (document.getElementById("ven").checked && hideVen == false){
hideVen = true;
} else if (document.getElementById("ven").checked && hideVen == true){
hideVen = false;
}
//Earth
if (document.getElementById("ear").checked && hideEar == false){
hideEar = true;
} else if (document.getElementById("ear").checked && hideEar == true){
hideEar = false;
}
//Mars
if (document.getElementById("mar").checked && hideMar == false){
hideMar = true;
} else if (document.getElementById("mar").checked && hideMar == true){
hideMar = false;
}
//Jupiter
if (document.getElementById("jup").checked && hideJup == false){
hideJup = true;
} else if (document.getElementById("jup").checked && hideJup == true){
hideJup = false;
}
//Saturn
if (document.getElementById("sat").checked && hideSat == false){
hideSat = true;
} else if (document.getElementById("sat").checked && hideSat == true){
hideSat = false;
}
//Uranus
if (document.getElementById("ura").checked && hideUra == false){
hideUra = true;
} else if (document.getElementById("ura").checked && hideUra == true){
hideUra = false;
}
//Neptune
if (document.getElementById("nep").checked && hideNep == false){
hideNep = true;
} else if (document.getElementById("nep").checked && hideNep == true){
hideNep = false;
}
console.log(hideMer);
alert(hideMer);
}
whole code: https://jsfiddle.net/nczpod06/6/
In the function save changes for each planet I'm only changing the boolean value when it is checked and not when it is unchecked. To fix this (for example for mercury) I needed to add the not boolean logical operator and then it works... for example:
//Mercury
if (document.getElementById("mer").checked && hideMer == false){
hideMer = true;
} else if (!(document.getElementById("mer").checked) && hideMer == true){
hideMer = false;
}

Jquery: check if variable is defined after keyup() function

Am creating register form with jquery function keyup(),
for example if input is correct I assign it to a txtuname variable,then I press register button and I need to know that all form variables are correct and defined.Code below is not working:
<script type="text/javascript">
$("document").ready(function() {
$("#txtuname").keyup(function() {
if ($("#txtuname").val().length < 6) {
jQuery("label[for='txtuname']").text("user name is too short");
}
if ($("#txtuname").val().length >= 6) {
var txtuname = $("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function() {
if (typeof txtuname == 'defined') {
alert("defined");
}
if (typeof txtuname == 'undefined') {
alert("undefined");
}
});
});
</script>
Modified code. Main point of this code is that txtuname should be visible in both scopes of keyup event listner and click listner. So if there are more lements, create Validation object and just check whether all the values was set and correct. And yes, use or $ or jQuery in your code.
$("document").ready(function(){
var txtuname = null;
$("#txtuname").keyup(function(){
if($("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if($("#txtuname").val().length>=6){
txtuname=$("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function(){
if( txtuname == null || txtuname.length < 6) ){
alert("incorrect");
}
else{
alert("correct");
}
});
});
Updated check of variable using comment of #Rhumborl , thx
Replace code with below condition -
if( typeof txtuname !== 'undefined' && txtuname.length >= 6) ){
//proceed further
}else{
alert('Please correct entries.');
return false;
}
I would put the validation logic in a function and call that, you can update this with your specific requirements and only do it once:
function isValidName(field) {
var myName = field.val().trim();
// some of this is redundant but just to show possibilities
var isValid = myName.length && myName.length >= 6 && myName && undefined !== myName && myName != " ";
var myLabel = $("label[for='" + field.attr('id') + "']");
if (isValid) {
myLabel.text("");
} else {
myLabel.text("user name is too short");
}
return isValid;
}
$("document").ready(function() {
$("#txtuname").keyup(function() {
isValidName($(this));
});
$("#submitRegistration").click(function() {
var nameIsValid = isValidName($("#txtuname"));
if (nameIsValid) {
alert("valid");
} else {
alert("undefined or invalid");
}
});
});
You are using $ as well as jQuery window.jQuery object in your code. Do not use both at time , you can check by both
jQuery("document").ready(function() { jQuery("#txtuname").keyup(function(){ if(jQuery("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if(jQuery("#txtuname").val().length>=6){
var txtuname=jQuery("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
jQuery("#submitRegistration").click(function(){
if(typeof txtuname =='defined'){
alert("defined");
}
if(typeof txtuname =='undefined'){
alert("undefined");
}
});
});
Or use by replace jQuery by $ sign. It will work.
you can try this way too......
$("document").ready(function(){
var txtuname;
$("#txtuname").keyup(function(){
if($("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if($("#txtuname").val().length>=6){
txtuname=$("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function(){
if(typeof txtuname=="undefined"){
alert("undefined");
}
else{
alert("defined");
}
});
});

Javascript - while loop doesn't show success option

Why my code never alerts "be happy"?
It works for every other option, but not this one. Why so?
var i = "";
while (i != "YES"){
if(i == "NO"){
alert("You should be!");
}
else if(i == "YES") {
alert("Be happy!")
}
else{
if(i == ""){
}
else {
alert("C'mon dude... Answer simply yes or no!");
}
}
i = prompt("Are You happy?").toUpperCase();
}
Because when you enter the loop, the condition just ensure that i will never be 'Yes' when the loop starts.
Pull your i = prompt("Are You happy?").toUpperCase(); to the start of the loop.
When the user is prompted to write down "YES", you exit the while loop. Put it on top
var i = "";
while (i != "YES"){
i = prompt("Are You happy?").toUpperCase(); //*************** Put it here
if(i == "NO"){
alert("You should be!");
}
else if(i == "YES") {
alert("Be happy!")
}
else{ //Not needed (do else { alert("com...")} )
if(i == ""){
}
else {
alert("C'mon dude... Answer simply yes or no!");
}
}
}

Checkbox in HTML turns off a function in a .js file

I am looking to make a checkbox that when unchecked, will turn off a certain function in a .js file. Can someone help me?
popup.html
HTML Check box:
content.js
Turn off this function:
var tweet = new Array();
var tweetName = new Array();
function linkSnipe() {
for (var i = 0; i < 5; i++) {
tweetName[i] = document.getElementsByClassName("fullname js-action-profile-name show-popup-with-id")[0].innerHTML;
tweet[i] = document.getElementsByClassName("js-tweet-text")[i].innerHTML;
}
if (tweet[0].match(shoeName) == shoeName && tweet[0].match(filterer) != filterer && tweet[0].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[0].click();
update();
}
}
else if (tweet[1].match(shoeName) == shoeName && tweet[1].match(filterer) != filterer && tweet[1].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[1].click();
update();
}
}
else if (tweet[2].match(shoeName) == shoeName && tweet[2].match(filterer) != filterer && tweet[2].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[2].click();
update();
}
}
else if (tweet[3].match(shoeName) == shoeName && tweet[3].match(filterer) != filterer && tweet[3].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[3].click();
update();
}
}
else if (tweet[4].match(shoeName) == shoeName && tweet[4].match(filterer) != filterer && tweet[4].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[4].click();
update();
}
}
else if(checkon == "Tweets") {
location.reload();
}
}
setTimeout("linkSnipe()", 250);
}
When the checkbox is checked, redefine the function as:
<input type=checkbox ..... onchange="doit()">
function doit() {
window.linkSnipe=function() {}
}
I've used this too:
function doit() {
window['linkSnipe']=function() {}
}
If you want to turn the function on and off by the checkbox:
<input type=checkbox ..... onchange="doit(this)">
var linkSnipeSave = linkSnipe;
function doit(ck) {
if (ck.checked)
window['linkSnipe']=linkSnipeSave
else {
linkSnipeSave = linkSnipe; //not sure if this line is needed...pls test
window['linkSnipe']=function() {}
}
}
You could simply have a Boolean variable that changes with the state of your check box. You could then put an if statement around the function call that will only trigger if the checkbox is checked.
http://jsfiddle.net/W5P8X/
//initialize some variables.
bike_checked = false;
car_checked = false;
//get elements by their ID from html
bike = document.getElementById("bike");
car = document.getElementById("car");
//add event listeners to the html elements we found above
bike.addEventListener("click", toggle_bike, false);
car.addEventListener("click", toggle_car, false);
//toggle bike_checked variable on click
function toggle_bike(){
if(bike_checked == true)
bike_checked = false;
else
bike_checked=true;
current_state();
}
//toggle car_checked variable on click
function toggle_car(){
if(car_checked == true)
car_checked = false;
else
car_checked=true;
current_state();
}
//output current state.
function current_state(){
if(car_checked == true)
alert('Car checked');
if(bike_checked == true)
alert('Bike checked');
}
I answered with only javascript and no jQuery, but you could probably make it a bit more concise with jQuery.
I hope this helps.

Categories