We are working on another game and we have several answers to a question. Now the problem is that I need to compare the place of the whale to the place of a fish with the answer.
Does anyone know how to do that?
var Keys = {
left: 37,
right: 39,
up:38,
down:40
}
function Start(){
$("#start").hide();
alert ("test start weg");
Opdr1();
}
$(function(){
$(document).keydown(function(e){
switch(e.which){
case Keys.right:
$("#whale").css("left", "+=10px");
$("#whale").attr("src", "pacman-right.png");
break;
case Keys.left:
$("#whale").css("left", "-=10px");
$("#whale").attr("src", "pacman-left.png");
break;
case Keys.up:
$("#whale").css("top", "-=10px");
break;
case Keys.down:
$("#whale").css("top", "+=10px");
break;
}
});
});
function Opdr1(){
$(".bubbel").css("visibility", "visible");
$(".vis1-1").css("visibility", "visible");
$(".vis2-1").css("visibility", "visible");
$(".vis3-1").css("visibility", "visible");
$(".vis4-1").css("visibility", "visible");
//if the whale's css left and top is the same as the left and top of the vis-1 then { }
if($("#whale").css("left") == ("left") {
alert('vis-1 fout');
}
if($("#whale").css('left') == (".vis2-1").css('left')) {
alert('vis-2 fout');
}
if($("#whale").css('left') == (".vis3-1").css('left')) {
alert('vis-3 fout');
}
if($("#whale").css('left') == (".vis4-1").css('left')) {
alert('vis-4 fout');
}
}
You need to compare the offset of the two objects
For example,
if ( $("#whale").offset().top == $(".vis-1").offset().top )
{
}
similarly
if ( $("#whale").offset().left == $(".vis-1").offset().left )
{
}
Related
Is there a way to condense these four if statements into a for loop and with a single if condition? I was told that there is a way but I can only think of multiple else if statements.
function New() {
if (foodInOven == true) {
timeOfCooking += 1;
}
if (timeOfCooking == 10) {
console.log("cooked pasta");
} else if (timeOfCooking == 15) {
console.log("burning pasta!");
} else if (timeOfCooking == 20) {
console.log("pasta burnt!!");
}
}
One option could be to have a lookup for your times and, if there's a value, log it to the console.
const cookingLookup = {
10: "cooked pasta",
15: "burning pasta!",
20: "pasta burnt!!"
}
function New() {
if (foodInOven == true) {
timeOfCooking += 1;
}
if (cookingLookup[timeOfCooking]) {
console.log(cookingLookup[timeOfCooking]);
}
}
I have around 5 javascript files in my WordPress website, And I tried to execute them one by one based on a boolean condition.
The javascript calls tag1.js if the count is 0.
tag2.js if the count is 1 and so on.
If the count reaches 4, the count resets to 0. And thus this is repeated continously. I tried this code. But it doesn't work even for the first time.
jQuery(document).ready(function( $ ) {
var canClick = true;
var count= 0;
$("body").click(function () {
if (canClick) {
if(parseInt(count) === 0) {
$.getScript("https:example.com/custom_js/atag1.js");
}
else if(parseInt(count) === 1) {
$.getScript("https:example.com/custom_js/atag2.js");
}
else if(parseInt(count) === 2) {
$.getScript("https:example.com/custom_js/atag3.js");
}
else if(parseInt(count) === 3) {
$.getScript("https:example.com/custom_js/atag4.js");
}
else if(parseInt(count) === 4){
$.getScript("https:example.com/custom_js/atag5.js");
count=0;
}
canClick = false;
setTimeout(() => {
canClick = true
},10000);
count = parseInt(count)+1;
}
});
});
Basically this code executes each javascript if the user clicks on the page with timeout differentiating the clicks.
If you want to load the script as per the number of clicks. Then you can look at this solution which will look more precise.
var clicks = 0;
document.addEventListener('click', () => {
loadJS();
++clicks;
});
function loadJS() {
if (clicks === 4) {
clicks = 0;
}
switch (clicks) {
case 0:
console.log('load first js');
break;
case 1:
console.log('load second js');
break;
case 2:
console.log('load 3rd js');
break;
case 3:
console.log('load 4th js');
break;
case 4:
console.log('load 5th js');
break;
default:
// code block
}
}
working demo
Alright, I have made some JavaScript for an assessment. Everything worked fine until I put in a new function with a switch statement called:
function differentComments(answer) {
The program doesn't seem to load the follow function anymore when the function differentComments is in there:
function genQuestion() {
All of my JavaScript code is below (HTML is available on Pastebin):
var x, y; //the global variables
function aNumber() {
return Math.floor(1 + Math.random() * 12);
}
function genQuestion() {
x = aNumber();
y = aNumber();
dout = document.getElementById('Question');
dout.value = x + " times " + y;
}
function buttonPressed() {
var input = document.getElementById('Typed').value;
var answer = x * y;
if (input == answer) {
differentComments("Right");
genQuestion();
} else {
differentComments("Wrong");
}
document.getElementById('Typed').value="";
}
function differentComments(answer) {
var random_number = Math.floor(1 + Math.random() * 4);
if (answer == "Right") {
switch (random_number) {
case 1:
window.alert("Very Good!");
break;
case 2:
window.alert("Excellent!");
break;
case 3:
window.alert("Correct - Nice work!");
break;
case 4:
window.alert("Correct - keep up the good work!");
break;
default:
break;
}
} else (answer == "Wrong") {
switch (random_number) {
case 1:
window.alert("No. Please try again.");
break;
case 2:
window.alert("Wrong. Try once more.");
break;
case 3:
window.alert("Incorrect – Don’t give up.");
break;
case 4:
window.alert("No – keep trying.");
break;
default:
break;
}
}
}
Your else clause is incorrect.
if (answer == "Right") {
switch(random_number) {
...
}
else (answer == "Wrong") {
}
won't parse because the second test is missing an if.
if (answer == "Right") {
switch(random_number) {
...
}
else **if** (answer == "Wrong") {
}
Essentially you're treating an if() as if it's a switch(), and that's not syntactically correct.
The first thing you should do when you run into situations like this is use either jshint or jslint to check the syntactical correctness of your code.
In your code block :
if (answer == "Right") {
switch(random_number) {
...
}
else (answer == "Wrong") {
switch(random_number) {
...
}
}
mean you put if and else statement and a else condition only execute when all if conditions are return false. So there is no need to put conditional-statement(like in your case -else (answer == "Wrong") {) ).
You can simply write this :
if (answer == "Right") {
switch(random_number) {
...
}
else {
switch(random_number) {
...
}
}
It's means if your answer is not equal to Right, it always go to else statement.
OR
If you want to check for more conditions, use else if(){} statements.
if (answer == "Right") {
switch(random_number) {
...
}
else if (answer == "Wrong") {
switch(random_number) {
...
}
}
Read this
I have to make a game for school with html5 canvas Javascript.
I am new to javascript and still learning but i really need some help with this issue that i have and would appreciate it if someone could help me out. I tried several things but nothing seems to work and im at a loss.
So this is the code for the player object. It can move from left to right.
Now the problem is that it leaves the canvas. I want it to stay in the canvas on the x axes.
// Things to do when keys are down
function onKeyDown(event) {
// prevent arrow keys from scrolling the page
if (event.keyCode >= 37 && event.keyCode <= 39) event.preventDefault();
switch (event.keyCode) {
case 37:
player.vx = -1;
player.image = player.imgLeft;
break; // left key
// case 38: player.vy = -1; break; // up key
case 39:
player.vx = 1;
player.image = player.imgRight;
break; // right key
}
}
// Things to do when keys are up
function onKeyUp(event) {
switch (event.keyCode) {
case 37:
case 39:
player.vx = 0;
player.image = player.original;
break; // left or right key released
// case 38: player.vy = 0; break; // up or down key released
}
}
This is what i got so far....
if ((player.x >= 800) && (player.x <= 0)) {
} else {
}
You could consider adding two functions to check that you're within bounds.
(Essentially the same as your code, albeit with my true condition returned in what would be your else statement.)
// returns true if param is in range [0..799]
function isInXrange(intPos)
{
if ((intPos>=0) && (intPos<800))
return true;
else
return false;
}
// returns true if param is in range [0..599]
function isInYrange(intPos)
{
if ((intPos>=0) && (intPos<600))
return true;
else
return false;
}
You could then add a function to move the player and another to handle colliding with the walls/wandering out of bounds
function movePlayer()
{
if (isInXRange(player.x))
player.x += player.vx;
if (isInXRange(player.y))
player.y += player.vy;
}
function handleOutOfBounds()
{
if (isInXRange(player.x) == false)
{
// do something;
}
if (isInYRange(player.y) == false)
{
// do something else
}
}
Basically just test to see if x + width (optional: + velocity) > canvas.width and the same for height.
I'm creating a UI with sliding panels much in the fashion of this site: http://smithandhawken.catalogs.target.com/#/intro-cover
I have two ways to change the pages though, by column and by row. The user can use the keyboard as well as some visual elements to navigate the pages. The movement is handled by functions like this:
function moveDown()
{
unbindAll();
currentPage = 1;
$('div.section').each(function(index, element) {
if(index+1 == currentSec) {
console.log($(this));
$(this).css({ 'margin-top': 0, 'z-index': (storyCount-1)*100 });
if($(this).next().size()) {
populate(currentSec+1, currentPage);
$(this).next().children('div.page').css('left', $(window).width());
$(this).next().children('div.page').eq(0).css('left', 0);
console.log(storyCount);
$(this).next().css({ 'margin-top': $(window).height(), 'z-index': storyCount*100 }).stop().animate({marginTop:0}, 500, function() {
currentSec++;
bindAll();
});
}
else {
populate(1, currentPage);
$(this).parent().children().first().children('div.page').css('left', $(window).width());
$(this).parent().children().first().children('div.page').eq(0).css('left', 0);
$(this).parent().children().first().css({ 'margin-top': $(window).height(), 'z-index': storyCount*100 }).stop().animate({marginTop:0}, 500, function() {
currentSec = 1;
bindAll();
});
}
}
else if(index != currentSec) {
$('#section'+(index+1)).css({ 'margin-top': 0, 'z-index': 100 });
}
});
}
THe line above that doesn't work the same way 100% of the time is - $(this).css({ 'margin-top': 0, 'z-index': (storyCount-1)*100 });
When the user uses the keyboard and the left/right visual elements, everything works fine. When they use the visual elements that translate between each row (up/down methods only), the function fires, but not all CSS properties are applied. Here is the function for the visual elements I'm talking about:
function mdlButton(btnHit)
{
btnLabel = btnHit.attr('id').substr(3);
console.log('enter first swtich '+currentSec);
switch(currentSec)
{
case 1:
console.log('enter second switch '+btnLabel);
if (btnLabel == 1) {
console.log('dont do anything');
}
else if (btnLabel == 2) {
console.log('move down one');
moveDown();
}
else if (btnLabel == 3) {
console.log('move down two');
moveDown();
moveDown();
}
break;
case 2:
console.log('enter second switch');
if (btnLabel == 1) {
console.log('move up');
moveUp();
}
else if (btnLabel == 2) {
console.log('dont do anything');
}
else if (btnLabel == 3) {
console.log('move down one');
moveDown();
}
break;
case 3:
console.log('enter second switch');
if (btnLabel == 1) {
console.log('move up two');
moveUp();
moveUp();
}
else if (btnLabel == 2) {
console.log('move up');
moveUp();
}
else if (btnLabel == 3) {
console.log('dont do anything');
}
break;
}
if(!btnHit.hasClass('mdlSelected')) {
$('div.mdlSec').removeClass('mdlSelected');
$('div.mdlSec').find('#selected').remove();
btnHit.addClass('mdlSelected');
btnHit.find('div.divider').after('<div id="selected"></div>');
reSize();
}
}
I can't figure out the reason why the z-index wouldn't change when called from the above function as opposed to just the keyboard or when left/right call the moveDown()/moveUp() methods. Just in case, here's what the left/right look like:
function moveLeft()
{
unbindAll();
$('#section'+currentSec+' div.page').each(function(index, element) {
if(index+1 == currentPage) {
if($(element).prev().size()) {
populate(currentSec, currentPage-1);
$(this).animate({'left': $(window).width()}, 500, function() {
currentPage--;
bindAll();
});
}
else {
moveUp();
}
}
});
}
Any help would be much appreciated! Thanks
The z-index was being reset back to another value by the reSize() function which was called to resize the footer buttons. I've separated the resize functions and the problem disappeared. No problems with the code itself, just the execution order.
Thanks for all the help!