Cant figure out why my div output isn't working - javascript

I have a basic hangman program. Click on the letter, it then tells you if its right or wrong by coloring the letter red or green. If its green, it replaces a dash in the hidden word with the letter. That part of my code works. The part that doesn't work is that I have an output section to a div that is supposed to tell you if you got the guess correct or not, and upon 6 failed guesses, you lose and it resets. It's currently not doing any of that. It's not even displaying anything in the div at all.
TY ahead of time. If you have questions about something I didn't explain well enough, ill be back in about 1 hour to answer them. Thanks!
Jsfiddle - http://jsfiddle.net/25b3fr4u/
HTML -
<body>
<form id="form" name="form" method="post" action="">
<input type="button" id="but" value="Start"/>
<div id="hangman-jquery">
<div id="word"></div>
<div id="alpha"></div>
</div>
</form>
<div id="win">
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="hangman.js"></script>
</body>
JS -
function hangman(word) {
var trys = 0;
var guess = 0;
var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$.each(alpha.split(''), function(i, val) {
$('#alpha').append($('<span class="guess">' + val + '</span>'));
});
$.each(word.split(''), function(i, val) {
$('#word').append($('<span class="letter" letter="' + val + '">-</span>'));
});
$('.guess').click(function() {
var count = $('#word [letter=' + $(this).text() + ']').each(function() {
$(this).text($(this).attr('letter'));
}).length;
$(this).removeClass('guess').css('color', (count > 0 ? 'green' : 'red')).unbind('click');
if (guess > 0) {
$('#win').text("Correct Guess");
} else if (guess < 0) {
$(this).html(++trys);
$('#win').text("You have tried to guess the word and failed " + trys + " times");
}
if (trys == 6) {
alert("You have guessed six times, you lose");
trys = 0;
$("#win").text("");
}
});
}
$(document).ready(function() {
$('#but').click(function() {
var options = new Array("DOG", "CAT", "BAT", "HORSE", "TIGER", "LION", "BEAR", "LIGER", "DOOM", "SPIDER", "TREES", "LAPTOP");
var random = 1 + Math.floor(Math.random() * 12);
hangman(options[random]);
});
});

Code fixed :http://jsfiddle.net/25b3fr4u/1/. The trys where not incremeted properly and you have to check the count instead of guess in your condition. guess was set to 0 and never use.
var count = $('#word [letter=' + $(this).text() + ']').each(function() {
$(this).text($(this).attr('letter'));
}).length;
$(this).removeClass('guess').css('color', (count > 0 ? 'green' : 'red')).unbind('click');
if (count > 0) {
$('#win').text("Correct Guess");
} else if (!count > 0) {
trys++;
$('#win').text("You have tried to guess the word and failed " + trys + " times");
}
if (trys == 6) {
alert("You have guessed six times, you lose");
trys = 0;
$("#win").text("");
}
I'm sure you can handle the rest. Have fun.

Related

Function will not execute more then once

I am trying to make a hangman game with an on-screen keyboard, there is alot more code then this but this is the specfic function that won't run. The HTML is just an example of one key, there are 27 including a space, all of them only run the wrong() function once.
Here's the HTML that executes the function:
<p class="key" id="q" onclick="q(); setTimeout(allclick, 200); setTimeout(wrong, 1000);" onmouseover="hoverq()" onmouseout="unhoverq()">Q</p>
And the script that should fire off everytime one of the keys is pressed but it doesn't.
<script>
function wrong(){
console.log("wrong()")
console.log(clickon)
if(wrong == length){
console.log("all wrong")
document.getElementById(clickon).setAttribute("onmouseover", " ")
document.getElementById(clickon).setAttribute("onmouseout", " ")
document.getElementById(clickon).setAttribute("onclick", " ")
document.getElementById(clickon).style.backgroundColor="red"
}else{
wrongcheck = 1
console.log(wrongcheck)
}
console.log("_____")
</script>
Edit:
This may help you understand this better.
var length = word.length;
function allclick(){
for(l = 0; l <= length; l++){
if(clickon == letter[l]){
if(clickon == " "){
document.getElementById("blank" + l).innerHTML = " "
document.getElementById("space").setAttribute("onmouseover", "")
document.getElementById("space").setAttribute("onmouseout", "")
document.getElementById("space").setAttribute("onclick", "")
document.getElementById("space").style.backgroundColor="green"
document.getElementById("blank" + l).style.margin = "5px 50px"
}else{
console.log("correct")
document.getElementById("blank" + l).innerHTML = clickon + "&nbsp"
document.getElementById(clickon).setAttribute("onmouseover", "")
document.getElementById(clickon).setAttribute("onmouseout", "")
document.getElementById(clickon).setAttribute("onclick", "")
document.getElementById(clickon).style.backgroundColor="green"
}
}else if(clickon != letter[l]){
wrong = wrongcheck++
}
}
console.log("_____")
}
if you want I can send you the entire thing.

How do I use inner.HTML in a function?

I tried to create a Html / Js money counter but if i update, it updates one tick and then it resets itself to an old value. I tried creating a function named update and let it run every time the money value changes, but that did not work either.
<html>
<head>
<title>Betting Simulator Test!</title>
</head>
<body>
<br/>
<p id="p1">You have 500$</p>
<br/>
<form name="CoinFlip" action="" onsubmit="Create()" method="post">
Coins: <input type="text" name="Csubmit">
<input type="submit" value="Flip the Coin">
</form>
<script type="text/javascript">
Balance = 500;
function Game() {
if(Balance >= 1) {
var Coin = confirm("You have put " + sub + "$ in the CoinFlip!");
if(Coin == true) {
var flip = true
if(flip == true) {
alert("You won " + sub + "$");
Balance = Balance + sub*2 - sub;
Update = document.getElementById("p1").textContent="You have " + Balance + "$";
} else {
alert("You lost " + sub + "$");
Balance = Balance - sub;
Update = document.getElementById("p1").textContent="You have " + Balance + "$";
}
} else {
}
} else {
alert("You ran out of Money");
}
}
function Create() {
sub = document.forms["CoinFlip"]["Csubmit"].value;
if(sub <= Balance && sub > 0) {
Game();
} else {
alert("value does not make any sense!");
}
}
</script>
</body>
You have multiple problems. The first one is that you submit a form each time you play, so the page refreshes, and everything is lost. You could find a workaround to avoid this (see this), but in this case, a form is really not needed.
Also, the user is always going to win because you always set flip to true. You can simulate a random win by using this snippet:
var win = Math.round( Math.random() ); // 1 or 0 (truthy or falsy)
Here is a working example:
var balance = 500;
document.getElementById('flip').addEventListener('click', play);
function play(){
// parseInt() converts a String to an integer (10 is for decimal base)
var bet = parseInt(document.getElementById('bet').value, 10);
if(bet <= balance && bet > 0)
{
var accepted = confirm("Do you really want to bet " + bet + "$?");
if(accepted)
{
var win = Math.round( Math.random() ); // Random win
if(win)
{
alert("You won " + bet + "$!");
balance += bet;
}
else
{
alert("You lost " + bet + "$...");
balance -= bet;
}
if(!balance){ alert('You ran out of money...'); }
document.getElementById('p1').textContent = "You have " + balance + "$";
}
document.getElementById('bet').value = 0;
}
else
{
alert("Your bet makes no sense!");
}
}
<p id="p1">You have 500$</p>
<p>Coins: <input type="number" value="0" id="bet"> <button id="flip">Flip the coin</button>

How to stop this weird thing for limiting word in jquery?

Click http://jsfiddle.net/1ybzcppk/8/ to see.
I can successfully limit word enter, but there is a weird thing happening. When you reach the max, the sixth word still show up. If I kept enter, it kept replace the last word. I want nothing show up when it reach the 5th word. Help, appreciate.
JQuery:
$("#input").keydown(function(event) {
var count = $('#test').text();
var words = count.match(/\S+/g).length;
if (words >= 5) {
var trimmed = $('#test').text().split(/\s+/, 5).join(" ");
// Add a space at the end to keep new typing making new words
$('#test').text(trimmed + " ");
}
if (event.which == 13) {
event.preventDefault();
//put input value into div
var value = $('#input').val();
$('#test').text($('#test').html() + " " + value);
}
});
CSS:
.test {
display: inline-block;
}
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test" id="test">dog</div>
<input type="text" id="input" />
Move the enter handler to the else part
$("#input").keydown(function(event) {
var count = $('#test').text();
var words = count.match(/\S+/g).length;
if (words >= 5) {
var trimmed = $('#test').text().split(/\s+/, 5).join(" ");
// Add a space at the end to keep new typing making new words
$('#test').text(trimmed + " ");
} else if (event.which == 13) {
event.preventDefault();
//put input value into div
var value = $('#input').val();
$('#test').text($('#test').html() + " " + value);
}
});
.test {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="test" id="test">dog</div>
<input type="text" id="input" />

javaScript - guess tiles game

I am making an javaScript game - that in the end is going to be a battleship game with grid GUI and so forth.
Have started making a horizontal grid with tiles (that the user can define for himself(min. 4 tiles))
When clicked a tile turns from blue to red indicating if it has been hit or not - BUT it doesn't register that if it is hit 3 times then the stats and accuracy should pop-up:
etc. after 3 this it will pop-up with stats: "You took 3-4 guesses to sink my battleship and your accuracy is 30%"
Instead it gives me 0 guesses and my accuracy is infinity :)
I have posted my code below:
<html>
<head>
<title></title>
<style type="text/css">
td
{
width: 94px;
height: 94px;
background-color: blue;
}
.clicked
{
color: red;
}
</style>
</head>
<body>
<div id="board">
<div id="messageArea"></div>
<table>
<tr id="tblRow">
</tr>
</table>
</div>
<script type="text/javascript">
var boardLength;
do {
boardLength = prompt('Enter length of board length (min 4)')
}
while(boardLength <4);
var boardLengthCal = parseInt(boardLength)-2;
var randomLoc = Math.floor(Math.random() * boardLengthCal);
var location1 = randomLoc;
var location2 = location1 + 1;
var location3 = location1 + 2;
console.log(location1);
console.log(location2);
console.log(location3);
for (var i = 0; i < boardLength; i++){
document.getElementById('tblRow').innerHTML +="<td id='"+i+"'></td>"
};
var fields = document.getElementsByTagName('td');
for (var i =0; i < fields.length; i++){
fields[i].addEventListener('click', pickLocation)
};
function pickLocation(){
guess = this.id;
if (guess < 0 || guess > boardLength) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
changeColor(this, "red");
alert("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3*100/guesses)+"%";
alert(stats);
function changeColor(element, color)
{
element.style.backgroundColor = color;
};
</script>
</body>
</html>
Your stats showing code is executing before the game even started. At that time value of your guesses is 0, so dividing by 0 is giving you infinity. You need to put your stats code in a function and call it when the game ends (3 hits)
function stats(){
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3*100/guesses)+"%";
alert(stats);
}
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
stats();
}
Now when the user hits three time, only then stats will pop up with correct values.
See the DMEO here
EDIT:
I made some improvements in your game and now really made it playable by introducing random numbers instead of three in a line and other minor errors removed.. you can check that version HERE.

javascript hot and cold game

I'm making an app that compares a randomly generated number to a number input by the user. From there the app guides the user via "hotter" and "colder" prompts. I'm close, but right now my issue is that the prompts disappear after being displayed for about 1 second. I want the "hotter" or "colder" prompt to stay visible until the user inputs another number.
Here is a link to the app: http://dl.dropboxusercontent.com/u/91499081/HotOrCold/HotOrCold.html?guess=&submit=Submit
Here is my javascript code:
$(document).ready(function () {
var answer = Math.floor((Math.random() * 100) + 1);
console.log("The secret number is: " + answer);
var numberOfGuesses = 0;
var guesses = [];
var distance = null;
var previousDistance = null;
function getGuess() {
$("#submit").click(game);
$("#guess").keydown(function (enter) {
if (enter.keyCode == 13) {
game();
}
});
}
getGuess();
function game() {
var guess = parseInt($('#guess').val());
if (guess !== null && $.isNumeric(guess) && (1 < guess < 101)) {
$('#guess').val('');
numberOfGuesses += 1;
guesses.push(guess);
distance = Math.abs(answer - guess);
previousDistance = Math.abs(answer - guesses[guesses.length - 2]);
if (guess === answer) {
$('#hint').html('Congrats! You got it in ' + numberOfGuesses + ' attempts! The secret number was ' + answer);
} else {
console.log(guess, answer, previousDistance, distance);
if (isNaN(previousDistance)) {
if (guess > answer) {
$('#hint').html('Guess lower! Last guess: ' + guess);
} else if (guess < answer) {
$('#hint').html('Guess higher! Last guess: ' + guess);
}
} else if (distance > previousDistance) {
if (guess > answer) {
$('#hint').html('You\'re getting colder, guess lower! Last guess: ' + guess);
} else if (guess < answer) {
$('#hint').html('You\'re getting colder, guess higher! Last guess: ' + guess);
}
} else if (distance < previousDistance) {
if (guess > answer) {
$('#hint').html('You\'re getting hotter, guess lower! Last guess: ' + guess);
} else if (guess < answer) {
$('#hint').html('You\'re getting hotter, guess higher! Last guess: ' + guess);
}
} else if (distance === previousDistance) {
if (guess > answer) {
$('#hint').html('You\'re on fire, guess lower! Last guess: ' + guess);
} else if (guess < answer) {
$('#hint').html('You\'re on fire, guess higher! Last guess: ' + guess);
}
} else {
$('#hint').html('ERROR: Your guess must be a number between 1 and 100').css({
color: 'red'
});
}
}
}
$('#newgame').click(function (e) {
e.preventDefault();
answer = Math.floor((Math.random() * 100) + 1);
console.log(answer);
numberOfGuesses = 0;
guesses = [];
distance = null;
previousDistance = null;
$('#hint').html('');
$('#guess').val('');
});
}
});
The actual issue is in your HTML. You have a submit button that is part of a form. When you click submit, it is looking for a form action which isn't specified so it is reloading the page.
Change your <form> tag to keep you on the same page by changing it from this:
<form id="myform">
to this:
<form id="myform" action="#">
Or even better, make it so the JS function returns false so that the submit won't go through.
Don't use a <input type="submit" /> button. When it's clicked, your form will attempt to fire off whatever is in the action attribute, which is reloading your page.
You have many options.
I would just use <input type="button" /> or Submit. Then fire off the event when the button or link is clicked.
Your form performs its normal behaviour: post its data to the server. You need to disabled that action. You can either change your 'submit' button to be a normal button so it won't behave as submit:
<input type="button" name="submit" id="submit" class="button"/>
Or add a onsubmit to your form:
<form id="myform" onsubmit="return false">.
Your form is submitting regularly. Since you do not have any action attribute in your form, it will submit your form to the current page. What you want, is to handle the submit with javascript:
<form id="myform">
and in your javascript:
$('#myform').on('submit', game);
function game(event) {
// your code goes here
event.preventDefault();
}
in this way also enter will trigger a post which is handled by javascript, instead of only clicking a submit button.

Categories