Replace window when script ends JavaScript/HTML [duplicate] - javascript

This question already has answers here:
Window location replace - timeout help? Javascript question
(2 answers)
Closed 1 year ago.
Is there a way I can insert:
location.replace("https://www.google.com");
After all the functions in my javascript have run, aka when my script ends? I've tried putting it in different parts of my script but it just replaces it straight away.
This is my script currently (sorry it's so long its a text adventure game):
var currentFrame = 0;
var images = document.getElementById("images");
var text = document.getElementById("text");
var buttonBox = document.getElementById('buttonBox');
var input = document.getElementById('input');
//this is the variable for the name of the character
var yerdog;
//this is how after we type in the character name and hit enter
//we will add the name to the variable, remove the input box and start our first scenario
input.onkeypress = function(event) {
console.log(input.value);
if (event.key == "Enter" || event.keyCode == 13) {
yerdog = input.value;
input.parentNode.removeChild(input)
advanceTo(scenario.two)
}
};
//this changes the text and puts in your characters name
var changeText = function(words) {
text.innerHTML = words.replace("Your dog", yerdog);
};
//this takes the image link and puts it in the proper format, sending it to the html
var changeImage = function(img) {
images.style.backgroundImage = "url(" + img + ")";
};
//this looks at the number of options we have set and creates enough buttons
var changeButtons = function(buttonList) {
buttonBox.innerHTML = "";
for (var i = 0; i < buttonList.length; i++) {
buttonBox.innerHTML += "<button onClick="+buttonList[i][1]+">" + buttonList[i][0] + "</button>";
};
};
//this is what moves the game along
var advanceTo = function() {
if (currentFrame >= scenario.length) {
//finish the game code here:
location.replace("https://www.google.com");
}
var s = scenario[currentFrame];
changeImage(s.image)
changeText(s.text)
changeButtons(s.buttons)
};
var scenario = [
one: {
image: "https://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "You have finally decided to take your dog out for a walk. You smile and pat your trusty companion's head. What the dog's name?\n",
},
];
input.onkeypress = function(event) {
console.log(input.value);
if (event.key == "Enter" || event.keyCode == 13) {
yerdog = input.value;
input.parentNode.removeChild(input)
currentFrame = currentFrame + 1; // <--- here
advanceTo() // <-- and here
}
};
//this is the code that starts the game
advanceTo(scenario.one);

You can use ifelse statement as well as timeout for it
setTimeout ( "location()", 5000 );
function location( )
{
location.replace("https://www.google.com");
}

var currentFrame = 0;
var images = document.getElementById("images");
var text = document.getElementById("text");
var buttonBox = document.getElementById('buttonBox');
var input = document.getElementById('input');
//this is the variable for the name of the character
var yerdog;
var scenario = [
{
image: "https://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "You have finally decided to take your dog out for a walk. You smile and pat your trusty companion's head. What the dog's name?\n",
buttons: [],
},
]
//this changes the text and puts in your characters name
var changeText = function(words) {
text.innerHTML = words.replace("Your dog", yerdog);
};
//this takes the image link and puts it in the proper format, sending it to the html
var changeImage = function(img) {
images.style.backgroundImage = "url(" + img + ")";
};
//this looks at the number of options we have set and creates enough buttons
var changeButtons = function(buttonList) {
buttonBox.innerHTML = "";
for (var i = 0; i < buttonList.length; i++) {
buttonBox.innerHTML += "<button onClick="+buttonList[i][1]+">" + buttonList[i][0] + "</button>";
}
};
//this is what moves the game along
var advanceTo = function() {
if (currentFrame >= scenario.length) {
//finish the game code here:
console.log("end of the game");
//location.replace("https://www.google.com"); // uncomment on your page
return;
}
var s = scenario[currentFrame];
changeImage(s.image)
changeText(s.text)
changeButtons(s.buttons)
};
input.onkeypress = function(event) {
console.log(input.value);
if (event.key == "Enter" || event.keyCode == 13) {
yerdog = input.value;
input.parentNode.removeChild(input)
currentFrame = currentFrame + 1; // <--- here
advanceTo() // <-- and here
}
};
//this is the code that starts the game
advanceTo();
<div id="images"></div>
<div id="text"></div>
<div id="buttonBox"></div>
<input type="text" id="input"/>
Based on the code your posted you have 3 important parts:
the advanceTo function
the input.onkeypress event
the scenario list
for that I can suggest one of two changes:
change the scenario to an array (end and call the replace when there is no more elements)
add a end scenario (that calls the replace when it comes to it)
Array approach:
you can change the scenario to an array instead an object:
var scenario = [
{
image: "https://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "You have finally decided to take your dog out for a walk. You smile and pat your trusty companion's head. What the dog's name?\n",
},
{
image: "https://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "You have finally decided to take your dog out for a walk. You smile and pat your trusty companion's head. What the dog's name?\n",
},
]
Also store the current frame in a variable (I suggest at the top of your code):
var currentFrame = 0;
So you can call advanceTo and starting the game (we are not passing the index anymore because is stored in the currentFrame variable:
advanceTo()
and change the logic of the advanced to a little bit:
var advanceTo = function() {
if (currentFrame >= scenario.length) {
//finish the game code here:
location.replace("https://www.google.com");
return;
}
var s = scenario[currentFrame];
changeImage(s.image)
changeText(s.text)
changeButtons(s.buttons)
};
At the end, you need to change your input.onkeypress event:
input.onkeypress = function(event) {
console.log(input.value);
if (event.key == "Enter" || event.keyCode == 13) {
yerdog = input.value;
input.parentNode.removeChild(input)
currentFrame = currentFrame + 1; // <--- here
advanceTo() // <-- and here
}
};

Related

How to add a difficulty to a Javascript hangman game

I want to allow the user to select the difficulty of the game. Easy is words length 3-5, Medium is length 6-9, Hard is 10-15. The word is being pulled from an AJAX API. Also, I've consulted this example but am still struggling to apply it to my own. I included extra code because I'm not sure if I could add radio buttons that store the level and word.length that then updates the word retrieved from the api to be the correct length.
var api = 'https://hangman-api.lively.software';
//add alphabet to div
alphabet.forEach((i) => {
$('.hangman-letters').append(`<div id="letter-${i}">${i}</div>`);
});
//set up initial puzzle
newPuzzle();
//set up new puzzle when user clicks "start over"
$('#game-over-replay').click(function(){
newPuzzle();
});
//trigger game on clicking letter button
$('.hangman-letters div').click(function(){
submitLetter(this.innerHTML, this);
});
//trigger game on keypress
$(window).keypress(function(e){
var thisKey = String.fromCharCode(e.which);
if(alpha.indexOf(thisKey) > -1) {
submitLetter(thisKey, document.getElementById(`letter-${thisKey}`));
}
})
//functions
//handle clicked letter or keyboard input
function submitLetter(letter, thisLetterButton) {
var isCorrect = letterChosen(letter);
if(isCorrect) $(thisLetterButton).addClass('disabled correct');
else $(thisLetterButton).addClass('disabled');
if(remainingBlanks < 1) {
gameOver(true);
}
if(totalIncorrect >= hangmanParts.length + 1) {
gameOver(false);
}
}
//wipe variables and containers and set up new game
//now called after api call is complete
function setUp(){
$('.game-over').hide();
puzzleLetterContainers = [];
previouslyChosen = '';
totalIncorrect = 0;
remainingBlanks = puzzle.length;
$('.hangman-puzzle').html('');
$('#added-parts').html('');
$('.hangman-letters div').each(function(){
this.classList = '';
})
puzzle.split('').forEach((i) => {
var thisClass = "hangman-puzzle-letters",
placeholder = " ";
if(i == ' ' || i == '-') {
thisClass += ' space';
remainingBlanks--;
placeholder = i;
}
$('.hangman-puzzle').append(`<div class="${thisClass}">${placeholder}</div>`);
});
//var difficulty[] = new difficulty;
//var difficulty[1] = Easy;
//var difficulty[2] = Medium;
//var difficulty[3] = Hard;
puzzleLetterContainers = document.getElementsByClassName('hangman-puzzle-letters');
}

JS : press enter and go to the next input

(Sorry if my english is bad)
I try to make a little game where you have to answer question in inputs. When you valid with the key "Enter", next input appear, and a new question in.
It is complicated to explain, so I leave you the test URL : nicolaslorand.com/bac.php
Here is my a part of my code :
var i = 1;
var j = 2;
$('#input'+i).keypress(function(event) {
console.log('input actuel :'+i);
console.log('input suivant :'+j);
if (event.which == 13) {
verification();
console.log("Touche entrée");
}
});
function verification(){
document.getElementById('input'+j).style.display = "block";
var index = $(".inputform").index(this) + 1;
$(".inputform").eq(index).focus();
var recup = document.getElementById('input'+i);
var verif = recup.value.toUpperCase();
var divLettre = document.getElementById('lettre');
var premiereLettre = divLettre.innerText || divLettre.textContent;
if ( verif.charAt( 0 ) === premiereLettre ) {
$("#input"+i).addClass('trueanswer');
i++; j++;
scoreTotal++;
console.log(i);console.log(j);
}
else{
$("#input"+i).addClass('falseanswer');
i++; j++;
console.log(i);console.log(j);
}
With this code, when I press enter, next input appear, but I have to write in the first input so that my answer is verified by the function.
You are using this inside function this refers to window object. i think you should use i instead of this
var index = $(".inputform").index(i) + 1;

My simple card game will not show the second card before it resets it's game board

My simple card game below will not show the picture of the second card before it goes on to display the alert message and then immediately reset its game board. Anyone able to help ?
Also, I'm kind of new to coding may anyone help to point out areas of code I could improve on?
var cards = ['queen', 'queen', 'king', 'king'];
var cardsInPlay = [];
var gb = document.getElementById('game-board');
//allows me to compare the pushed elements in the array cardsInPlay and erase all innerHTML when its done
var isMatch = function () {
if (cardsInPlay[0] === cardsInPlay[1]) {
alert('You found a match!');
} else {
alert('Sorry, try again.')
};
document.getElementsByClassName('card')[0].innerHTML = "";
document.getElementsByClassName('card')[1].innerHTML = "";
document.getElementsByClassName('card')[2].innerHTML = "";
document.getElementsByClassName('card')[3].innerHTML = "";
};
//pushes the 'data-card-' of a card upon an eventlistener and "flip"/show the cards image based on its 'data-card' info. triggers function check if cards are a match.
var isTwoCards = function () {
cardsInPlay.push(this.getAttribute('data-card'));
if (this.getAttribute('data-card') === 'king') {
this.innerHTML = '<img src="kingcard.png" alt="King" />'
} else {
this.innerHTML = '<img src="queencard.png" alt="Queen" />'
};
if (cardsInPlay.length === 2) {
isMatch(cardsInPlay);
cardsInPlay = [];
};
};
//iterates and creates cards, while setting an attribute and eventListener
var createCards = function () {
for (var i = 0; i < cards.length; i++) {
var children = document.createElement('div');
children.className = 'card';
gb.appendChild(children);
document.getElementsByClassName('card')[i].setAttribute('data-card', cards[i]);
document.getElementsByClassName('card')[i].addEventListener('click', isTwoCards);
};
};
createCards();

Uncaught TypeError: Cannot set property 'onfocus' of null

I am trying to learn JavaScript and I'm building this basic tutorial. In trying to demonstrate onfocus and onblur, I get this error message in my JavaScript console: Uncaught TypeError: cannot set property 'onfocus' of null.
Here is my code. I am new to learning JavaScript and could really use some help.
//alert("Hello, world!");
// this is a JavaScript alert button
//
var year = 2014;
var userEmail = "";
var todaysDate = "";
/*var donation = 20;
if (donation < 20) {
alert("For a $20 you get a cookie. Change your donation?");
}
else {
alert("Thank you!");
} */
var mainfile = document.getElementById("mainTitle");
console.log("This is an element of type: ", mainTitle.nodeType);
console.log("The inner HTML is ", mainTitle.innerHTML);
console.log("Child nodes: ", mainTitle.childNodes.length);
var myLinks = document.getElementsByTagName("a");
console.log("Links: ", myLinks.length);
var myListElements = document.getElementsByTagName("li");
console.log("List elements: ", myListElements.length);
var myFirstList = document.getElementById("2 paragraphs");
/* you can also use: var limitedList = myFirstList.getElementsByTagName("li");
to dig deeper into the DOM */
var myElement = document.createElement("li");
var myNewElement = document.createElement("li");
//myNewElement.appendChild(myNewElement);
var myText = document.createTextNode("New list item");
myNewElement.appendChild(myText);
// creating elements
var newListItem = document.createElement("li");
var newPara = document.createElement("p");
// To add content, either use inner HTML
// or create child nodes manually like so:
// newPara.innerHTML = "blah blah blah...";
var paraText = document.createTextNode("And now for a beginner level intro to JavaScript! YAY!");
newPara.appendChild(paraText);
//And we still need to attach them to the document
document.getElementById("basic").appendChild(newPara);
var myNewElement = document.createElement("li");
var secondItem = myElement.getElementsByTagName("li")[1];
myElement.insertBefore(myNewElement, secondItem);
// An example of using an anonymous function: onclick.
//When you click anywhere on the page, an alert appears.
//document.onclick = function() {
// alert("You clicked somewhere in the document");
//}
// And example of restricting the click alert to
// an element on the page.
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
function prepareEventHandlers() {
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
//onfocus and onblur event handler illustration
var emailField = document.getElementById("email");
emailField.onfocus = function() {
if (emailField.value == "your email") {
emailField.value = "";
}
};
emailField.onblur = function() {
if (emailField.value == "") {
emailField.value = "your email";
}
};
}
window.onload = function() {
// preps everything and ensures
// other js functions don't get
// called before document has
// completely loaded.
prepareEventHandlers(); // This is a named function call nested inside an anonymous function.
}
//Sometimes we want js to run later or call a
// function in 60 seconds or every 5 sec, etc.
// Two main methods for timers: setTimeout and setInterval
// these timer functions are in milliseconds
var myImage = document.getElementById("mainImage");
var imageArray = ["images/Blue-roses.jpg", "images/Purple-Rose.jpg", "images/White-Rose.jpg", "images/orange-rose.jpg", "images/pink-roses.jpg", "images/red-roses.jpg", "images/yellow-roses.jpg", "images/murdock.jpg", "images/dorothy-red-ruby-slippers.jpg"];
var imageIndex = 0;
function changeImage(){
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setInterval(changeImage, 5000);
//Sometimes we may want some random alert
// to pop up x-number of seconds later.
//So we use the setTimeout, like so:
/*function simpleMessage() {
alert("Get ready to learn!");
}
setTimeout(simpleMessage, 5000); */
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_POST); */
If it's giving you that error, then it means that document.getElementById("email") evaluates to null, which means that no element exists with the id email.
That's all I can tell you without seeing the HTML that this JS is connected to.

Javascript dialog script feedback needed

I am writing a Javascript dialog script which is seen in a lot of typical Role Playing Games.alt text http://www.dailynintendo.com/wp-content/uploads/2008/12/luminous-arc-2-dialogue.jpg
At the moment I got an array with text strings which you can skip trough. I got at the point where you can make a decision and based on the input a different string will show.
However I don't think this is the right way to do it. These are the requirements for the script:
Support for multiple dialog scripts
multiple characters
user decision input ("Do you like me?" -yes -no)
This is my code at the moment:
// Intro script
var script_intro = [];
script_intro[0] = 'Hello how are you?';
script_intro[1] = 'So I heard..';
script_intro[2] = 'This is a cool game!';
script_intro[3] = [];
script_intro[3][0] = 'Do you like me?';
script_intro[3][1] = [];
script_intro[3][1][0] = 'Jah';
script_intro[3][1][1] = 4;
script_intro[3][2] = [];
script_intro[3][2][0] = 'Nah';
script_intro[3][2][1] = 5;
// Intro script: variation I
var script_intro_1 = [];
script_intro_1[0] = 'I love you too!';
// Intro script: variation II
var script_intro_2 = [];
script_intro_2[0] = 'Damn you...';
function initDialog()
{
// This is where the text will be shown
var dialog = document.getElementById('dialog');
var content = document.getElementById('content');
var nextButton = document.getElementById('nextButton');
var optionButton_1 = document.getElementById('optionButton_1');
var optionButton_2 = document.getElementById('optionButton_2');
// How fast the characters will appear after each other (milliseconds)
var scrollSpeed = 50;
}
// Scroll text per line, character
function scrollText(script, line)
{
var char = 0;
// If this line contains a question that requires user input
if(typeof(script[line]) == 'object')
{
var textScroller = setInterval(
function()
{
// Add the string char for char
content.innerHTML += script[line][0][char];
char ++;
if(char >= script[line][0].length)
{
clearInterval(textScroller);
// Show options
options(script, line);
}
}, scrollSpeed);
}
else
{
var textScroller = setInterval(
function()
{
content.innerHTML += script[line][char];
char++;
if(char >= script[line].length)
{
clearInterval(textScroller);
// Show next line
next(script, line);
};
}, scrollSpeed);
}
}
function next(script, line)
{
line = line + 1;
// Last line has been shown
if(script[line] == undefined)
{
//alert('End of dialog');
}
else
{
nextButton.style.visibility = 'visible';
nextButton.onclick = function()
{
nextButton.style.visibility = 'hidden';
content.innerHTML = '';
scrollText(script, line);
}
}
}
function options(script, line)
{
optionButton_1.innerHTML = script[line][1][0];
optionButton_2.innerHTML = script[line][2][0];
optionButton_1.style.visibility = 'visible';
optionButton_2.style.visibility = 'visible';
optionButton_1.onclick = function()
{
optionButton_1.style.visibility = 'hidden';
optionButton_2.style.visibility = 'hidden';
content.innerHTML = '';
scrollText('script_intro_1', 0);
}
optionButton_2.onclick = function()
{
optionButton_1.style.visibility = 'hidden';
optionButton_2.style.visibility = 'hidden';
content.innerHTML = '';
scrollText('script_intro_2', 0);
}
}
html
<body onload="scrollText(script_intro, 0)">
<h1>rpg</h1>
<a id="reset" href="#">Reset</a>
<div id="device">
<div id="dialog">
<strong>NPC:</strong>
<div id="content"></div>
<a id="nextButton" href="#">Next</a>
<a id="optionButton_1" href="#"></a>
<a id="optionButton_2" href="#"></a>
</div>
</div>
</body>
I could really use some feedback. What is the best way to write such script with the requirements above? Is using JSON or XML a better option than an Array for the dialog scripts?
I especially need some hints on how to implement multiple choices in the script.
Thank you!
If this is a script that has a scripted flow to it, I would use the state machine pattern.
http://www.eventhelix.com/RealtimeMantra/HierarchicalStateMachine.htm
There are tons of links, I just grabbed the first I searched from google. What I would do is have a state for each situation the user will presented with options. Each option would be a transition to another state. So for instance
function State(questionText){
this.transitionsOut = [];
this.questionText = questionText;
}
State.prototype = {
transitionsOut:null,
questionText:null,
}
function Transition(startState, endState, optionText){
startState.transitionsOut[startState.transitionsOut.length] = this;
this.start = startState;
this.end = endState;
}
Transition.prototype = {
start:null,
end:null,
optionText:null
}
Then what you can do, is make your state machine, and then for the current state, print out your State Message, then underneath list each option for that state.
var startState = new State('Where do you want to go');
var north = new State('North');
var south = new State('South');
var transition1 = new Transition(startState,north,'Lets go north');
var transition2 = new Transition(startState,south,'Lets go south');
The code to then display what is in the current state, and the options is trivial, as is the transition from one state to another based on what the user picks.

Categories

Resources