How to get winner detection?
My code isn't working right now i only need the winner detection if someone can help me then do this .
$(document).ready(function() {
var xoro = 1;
$('#reset').on("click", function() {
$('img').attr("src", "blank.png");
});
$('img').on("click", function() {
var tmp = $(this).attr("src");
if (tmp == "blank.png" && xoro == 1) {
$(this).attr("src", "x.png");
xoro = 0;
} else if (tmp == "blank.png" && xoro == 0) {
$(this).attr("src", "o.png");
xoro = 1;
}
});
});
With your code you cant really determine a winner.
Options you have are :
Give your images ids . like
Let say we have this 3x3 field and we say its a 2dimensional array. Then the top left field is [0][0] and your bottom right is [3][3]
Your HTML code should be somethig like this
<img src="x.png" id="0-0"></img><img src="blank.png" id="0-1"></img>...
And so on.
After youve eine that you have to Start writing a huge if statement with all the winning Casey where you check if the SRC are all "x.PNG" or so.
EG: if ID 0-0,0-1 and 0-2 all have the SRC x.PNG x wins .
Best is to put these into a function named checkForWinner() and then just call this Funktion after every click or so
I hope i could help you out.
This question has already been answered here (in Java language though but the idea is the same). For that I suggest you store every move in a matrix which you can the use to determine the winner.
In addition, you have to make the images identifiable (as zeropublix suggested) so that you can actually capture the user's input and fill the matrix.
Related
My function is as follows:
function mySound() {
var eventTable = document.querySelector("#eventContent");
var eventCella=eventTable.getElementsByClassName("ago_eventlist_activity");
var eventCellb = eventTable.getElementsByClassName("missionFleet");
for (var i = 0; i < eventTable.rows.length-1; i++) {
var cella = eventCella[i];
var cellb = eventCellb[i];
if (cella.src == "Activity15.gif" && cellb.src == "60a018ae3104b4c7e5af8b2bde5aee.gif")
{theSound = probeSound; oaPlaySound();}
if (cella.img == "Activity15.gif" && cellb.img == "cd360bccfc35b10966323c56ca8aac.gif")
{theSound = attackSound; oaPlaySound();}
if (cella.img == "Activity15.gif" && cellb.img == "575dfbbe877f58d6c09120ffbcaabe.gif") {theSound = attackSoundRIP; oaPlaySound();}
} /* for i */
}
*I can't use ...byid cause it doesn't seem to have one?
I am including a link to the FireFox inspect element so you can see what I can see to try to make this work.
Image of InspectElement:
Any help would be helpful I am just trying to code this for a friend and I really don't know java at all.
Thanks
There is a difference between Java and javascript. I'm guessing you mean javascript since that is what the code appears to be.
There are a few issues with the code
cella.img does not target the image inside of the cell, you'll need to target the image first, or use find the image inside the cell.
var eventCella = eventTable.querySelector(".missionFleet img");
or
var imgb = eventCellb[i].querySelector("img");
Does the ago_eventlist_activity cell even contain an image? There doesn't seem to be one in the screenshot.
Checking the image src needs to include the complete url, unless you use an indexOf...
if (imgb.src.indexOf('60a018ae3104b4c7e5af8b2bde5aee.gif') > -1) {
// do something
}
I hope that helps. Please, the next time you ask a question, include the HTML instead of a screenshot. Or better yet, include a demo (jsFiddle) that shows the problem because it makes it easier for others to help. Not everyone will take the time or make an effort.
I'm trying to work through an assignment to further my understanding of js but I'm running into some issues that are keeping me from final code. The code executes a short quiz- inputs from radio buttons are taken in and matched to an object containing answers, then outputting a final score.
code at http://jsfiddle.net/8ax9A/3/
issues I'm aware of now :
my $response variable doesn't seem to work.
var $response = $('[name=rad]:checked').val();
counter is listening for clicks through questions. After the last question, I want to report final score. I can't get counter to reach the end of questions + 1, and I cant get an accurate final score listener reported (var finalScore).
if ($response == parseInt(questions[counter].answer, 10)) {
finalScore++;
}
Those are just snippets so check out the fiddle for full code. I'd love some suggestions on how to understand where I'm going wrong.
Here is one way you could do it:
//Initialization
var counter=0;
var score=0;
loadQuestion();
$('#next').on('click',answer);
//functions
function answer(){
// if the user did not answer
if ($('input:radio:checked').length == 0){
alert('You have to answer!');
return;
}
var currentQ=questions[counter];
// if answer is correct
if($('[name=rad]:checked').val()==currentQ.answer){score++;}
counter++;
// if there are no questions left
if(counter >= questions.length) {displayResults(); return;}
loadQuestion();
}
function loadQuestion(){
// clear the radio buttons
$("input:checked").removeAttr("checked");
var currentQ=questions[counter];
// display the question
$('h1').text(currentQ.question);
$('#a1').text(currentQ.choices[0]);
$('#a2').text(currentQ.choices[1]);
$('#a3').text(currentQ.choices[2]);
}
function displayResults(){
$("h1").text("You've finished with a score of " + score + "!");
$('[name=rad], #a1, #a2, #a3, #next').remove();
}
JS Fiddle
I am a beginner with all coding. Here is my general goal. I am running something relatively simple where I have 8 superheroes on the screen. I would like the user to eliminate the 4 DC superheroes from the screen and after all 4 of them are eliminated from the screen I want the system to alert the user that they have won the game. They don't have to do it in any order so I ran the superHero function each time a DC character was clicked to check if all four DC superheroes had been eliminated yet. Somebody please help me. I feel like it is something very simple I am messing up on. Thanks a ton in advance.
/*This is my jquery that shows all 8 of my superheroes*/
$('#heroes').show();
var flashHidden = !$('#greenlantern').is(':visible');
var greenHidden = !$('#greenlantern').is(':visible');
var batmanHidden = !$('#batman').is(':visible');
var supermanHidden = !$('#superman').is(':visible');
function superHero() {
if(flashHidden && batmanHidden && supermanHidden && greenHidden) {
alert ("Congratulations!!! You have won the game!! Please proceed forward and fill out a quick survey for the developers");
}
}
$('#flash').click(function(){
$('#flash').hide('slow',function(){
superHero();
});
});
$('#greenlantern').click(function(){
$('#greenlantern').hide('slow',function(){
superHero();
});
});
$('#batman').click(function(){
$('#batman').hide('slow',function(){
superHero();
});
});
$('#superman').click(function(){
$('#superman').hide('slow',function(){
superHero();
});
});
});
Right now the current thing that is happening is I will eliminate all of the correct superheroes and it will not alert me that the user has won. I've tried a lot of different things and the only other result I've gotten is to have the system alert the user every time they click on a superhero that they've won which is also incorrect.
EDIT
This has been solved by changing the scope of the variables to inside the function.
You should declare your variables i.e. flashHidden in your function. Currently you are setting then at the start.
function superHero() {
var flashHidden = !$('#flash').is(':visible');
var greenHidden = !$('#greenlantern').is(':visible');
var batmanHidden = !$('#batman').is(':visible');
var supermanHidden = !$('#superman').is(':visible');
if(flashHidden && batmanHidden && supermanHidden && greenHidden) {
alert ("Congratulations!!! You have won the game!! Please proceed forward and fill out a quick survey for the developers");
}
}
Additionally your click handler can be condensed into
$('#flash, #greenlantern, #batman, #superman').click(function(){
$(this).hide('slow',function(){
superHero();
});
});
You're setting...
var flashHidden = !$('#greenlantern').is(':visible');
...to start with. But you're not updating that variable later on when it gets hidden. So according to your check of:
if(flashHidden && batmanHidden && supermanHidden && greenHidden) {
...Flash is still visible. Even though, yes, on the page he's gone.
Try adding this:
$('#flash').click(function(){
$('#flash').hide('slow',function(){
flashHidden=true;
superHero();
});
});
Can someone tell me how I can achieve the following?
I want to display a banner on my website's page (of course this is easy). However I want it to appear randomly (a single time) in one of the 4 positions I selected (DIV ID's bannerpos1, bannerpos2, bannerpos3 and bannerpos4).
If the banner shows up in bannerpos2, it shouldn't appear at any other location and vice versa.
And, only if possible, it should display a random banner as well (choice out of 3 banners or so).
So in short; I want a random banner in a random position on my page. Of course the banners and positions are yet to be defined.
Can someone help me, or point me in the right direction?
//update 7th of November
Okay, I have been fooling around with the script as show by Joe, however I am experiencing some problems...
Currently the code looks like this (before body-tage):
<script type="text/javascript">
$(function(){
var position = Math.floor((Math.random()*3));
console.log(position)
var $a = $("#advertentieplaats1");
var $b = $("#advertentieplaats2");
var $c = $("#advertentieplaats3");
var $advertentietype1 = $("#advinhoud1");
var $advertentietype2 = $("#advinhoud2");
var $advertentietype3 = $("#advinhoud3");
if (position == 0){
$a.append($advertentietype1);
}
if (position == 1){
$b.append($advertentietype2);
}
if (position == 2){
$c.append($advertentietype3);
}
});
</script>
And at the bottom of the page I have the following:
<div id="advinhoud1">adsense code 1</div>
<div id="advinhoud2">adsense code 2</div>
<div id="advinhoud3">adsense code 3</div>
Or there are some problems with this, or I am doing it wrong somehow...
In Firefox it shows the adsense code on random (defined) locations. It also shows the remaining 2 advertisements at the bottom (which should not be visible or even loaded).
In Internet Explorer it doesn't do anything at all...? All Adsense is shown at the bottom, nothing in random locations...?
Something like this. You can make it more dynamic, but here's the idea.
var position = Math.floor((Math.random()*3));
var $a = $("#myDiv1"); // Get the three containers as JQuery objects by id.
var $b = $("#myDiv1");
var $c = $("#myDiv1");
var $myAd = $("#myAd"); // Get the content you want to place.
// You could include it as a string in your JS
// or as a hidden element.
if (position == 0)
{
$a.append($myAd);
}
if (position == 1)
{
$b.append($myAd);
}
if (position == 2)
{
$c.append($myAd);
}
I have been building my own carasol over the past few days.
My Jquery is based on tutorials on the web and also from help and advice from SO.
I am not a Jquery guru just an enthusiast and think my code is a little sloppy, hence the post.
here is a link to the working code: http://jsfiddle.net/JHqBA/2/ (updated link)
basically what happens is:
if someone hits the page with a # values in the url it will show the appropriate slide and example would be www.hello.com#two, this would slide to slide two
if someone clicks the numbers it will show the appropriate slide
next and prev also slide through the slides.
The question is, is there anything i could have wrote better as i know there is alot of duplicate code.
I understand its a big ask but it would help me learn a little more (i think my code is a little old school)
if anyone has any questions please feel free to ask and ill answer what it does or is supposed to do.
Sluap
--- Edit ----
I have made only one aniamtion function now which has got rid of alot of duplicate code.
I have yet to look into on function but will do soon.
I would like to know more about the create a new function, outside of the jQuery ready block as i cant get this working or quite understand how i can get it to work sorry
any more tips would be great ill carry on working on this project till i am happy with it.
also is there a better way to write:
if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == divSum) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
Jquery full:
$(document).ready(function () {
//////////////////////////// INITAL SET UP /////////////////////////////////////////////
//Get size of images, how many there are, then determin the size of the image reel.
var divWidth = $(".window").width();
var divSum = $(".slide").size();
var divReelWidth = divWidth * divSum;
//Adjust the image reel to its new size
$(".image_reel").css({ 'width': divReelWidth });
//set the initial not active state
$('#prev').attr("class", "not_active");
//////////////////////////// SLIDER /////////////////////////////////////////////
//Paging + Slider Function
rotate = function () {
var triggerID = $slideNumber - 1; //Get number of times to slide
var image_reelPosition = triggerID * divWidth; //Determines the distance the image reel needs to slide
//sets the active on the next and prev
if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == divSum) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
//Slider Animation
$(".image_reel").animate({
left: -image_reelPosition
}, 500);
};
//////////////////////////// SLIDER CALLS /////////////////////////////////////////////
//click on numbers
$(".paging a").click(function () {
$active = $(this); //Activate the clicked paging
$slideNumber = $active.attr("rel");
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
});
//click on next button
$('#next').click(function () {
if (!$(".image_reel").is(':animated')) { //prevent clicking if animating
var left_indent = parseInt($('.image_reel').css('left')) - divWidth;
var slideNumberOn = (left_indent / divWidth);
var slideNumber = ((slideNumberOn * -1) + 1);
$slideNumber = slideNumber;
if ($slideNumber <= divSum) { //do not animate if on last slide
rotate(); //Trigger rotation immediately
};
return false; //Prevent browser jump to link anchor
}
});
//click on prev button
$('#prev').click(function () {
if (!$(".image_reel").is(':animated')) { //prevent clicking if animating
var left_indent = parseInt($('.image_reel').css('left')) - divWidth;
var slideNumberOn = (left_indent / divWidth);
var slideNumber = ((slideNumberOn * -1) - 1);
$slideNumber = slideNumber;
if ($slideNumber >= 1) { //do not animate if on first slide
rotate(); //Trigger rotation immediately
};
}
return false; //Prevent browser jump to link anchor
});
//URL eg:www.hello.com#one
var hash = window.location.hash;
var map = {
one: 1,
two: 2,
three: 3,
four: 4
};
var hashValue = map[hash.substring(1)];
//animate if hashValue is not null
if (hashValue != null) {
$slideNumber = hashValue;
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
};
});
Question and answer has been moved over to https://codereview.stackexchange.com/questions/8634/jquery-carasol-build-finished-and-would-like-advice-on-best-practice-neateni/8635#8635
1) Separation of Concerns
Start by refactorring your code in to more granular functions.
You can read more about SoF at http://en.wikipedia.org/wiki/Separation_of_concerns
Update:
E.g. Instead of having your reel resizing code inline, put it in it's own function, like this:
function setImageReelWidth () {
//Get size of images, how many there are, then determin the size of the image reel.
var divWidth = $(".window").width();
var divSum = $(".slide").size();
var divReelWidth = divWidth * divSum;
//Adjust the image reel to its new size
$(".image_reel").css({ 'width': divReelWidth });
}
This achieves 2 things:
a. First, it groups a block of code that is logically cohesive, removing it from the main code which results in a much cleaner code habitat.
b. It effectively gives a label to the code block via the function name that is descriptive of what it does, and therefore makes understanding of the code much simpler.
Later, you can also encapsulate the whole thing in it's own "class" (function) and you can move it into it's own js file.
2) The jQuery "on" function
Use the "on" function to attach your click events, rather than the "click" function.
http://api.jquery.com/on/
This has the added advantage of also binding it to future elements matching your selector, even though they do not exist yet.
3) The ready function
// I like the more succinct:
$(handler)
// Instead of:
$(document).ready(handler)
But you might like the more obvious syntax.
Those are just a few things to start with.
-- Update 1 --
Ok, StackOverflow is not really suited to a refactoring work in progress, but we'll make do. I think you should keep your original code block in your question, so that future readers can see where it started and how it systematically improved.
I would like to know more about the create a new function, outside of
the jQuery ready block as i cant get this working or quite understand
how i can get it to work sorry
I am not familiar with jsfiddle.net, but it looks cool and helpful, but might also be a bit confusing if you don't know what is going on. I am not sure I do :), but I think that script editor window results in a .js file that is automatically referenced by the html file.
So here is an example of a function defined outside of the ready block, but referenced from within.
function testFunction () {
alert ('it works');
}
$(document).ready(function () {
testFunction();
// ... other code
});
This should pop up an alert box that says, "it works" when the page is loaded.
You can try it for yourself.
Then, once you got that working, you can refactor other logically cohesive blocks of code into their own functions. Later you can wrap them all up into their own javascript 'class'. But we'll get to that.