How can I make this more manageable? The song elements are generated by PHP so I don't know how many there will be. The number of variables for current_song is also unknown but is the same as the song elements. Thanks...
function gid(name)
{
return document.getElementById(name);
};
function itemMonitor(obj)
{
var current_song = jwplayer().getPlaylistItem().index;
gid('nowplaying').innerHTML = 'Now Playing: <span>' + player.getPlaylist()[obj.index].title + '</span>';
if (current_song == 0) {
gid('song0').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 0) {
gid('song0').style.backgroundColor = "#ffffff";}
if (current_song == 1) {
gid('song1').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 1) {
gid('song1').style.backgroundColor = "#ffffff";}
if (current_song == 2) {
gid('song2').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 2) {
gid('song2').style.backgroundColor = "#ffffff";}
if (current_song == 3) {
gid('song3').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 3) {
gid('song3').style.backgroundColor = "#ffffff";}
if (current_song == 4) {
gid('song4').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 4) {
gid('song4').style.backgroundColor = "#ffffff";}
if (current_song == 5) {
gid('song5').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 5) {
gid('song5').style.backgroundColor = "#ffffff";}
if (current_song == 6) {
gid('song6').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 6) {
gid('song6').style.backgroundColor = "#ffffff";}
if (current_song == 7) {
gid('song7').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 7) {
gid('song7').style.backgroundColor = "#ffffff";}
if (current_song == 8) {
gid('song8').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 8) {
gid('song8').style.backgroundColor = "#ffffff";}
if (current_song == 9) {
gid('song9').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 9) {
gid('song9').style.backgroundColor = "#ffffff";}
if (current_song == 10) {
gid('song10').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 10) {
gid('song10').style.backgroundColor = "#ffffff";}
};
Use the following code. All song-elements are obtained through document.querySelectorAll('[id^="song"]'). Then, you loop through this collection, and set the desired property:
function gid(name) {
return document.getElementById(name);
}
function itemMonitor(obj) {
var current_song = jwplayer().getPlaylistItem().index;
var currentPlayListItem = player.getPlaylist()[obj.index];
if (!currentPlayListItem) {
// The song does not exist, atm. Do something, e.g. throw an error:
alert("Song does not exist!");
return;
}
gid('nowplaying').innerHTML = 'Now Playing: <span>' + currentPlayListItem.title + '</span>';
var all_songs = document.querySelectorAll('[id^="song"]');
for (var i=0; i<all_songs.length; i++) {
var song = all_songs[i];
var songId = /^song(\d+)$/.exec(song.id);
if (songId === null) continue; // Not a song
else songId = 1*songId[1]; // Match the songId, convert to number
all_songs[i].style.backgroundColor = current_song === songId ? "#E6E8FA" : "#FFF";
// Or, replace the previous line with:
/*if (current_song === songId) {
all_songs[i].style.backgroundColor = "#E6E8FA";
} else {
all_songs[i].style.backgroundColor = "#ffffff";
}*/
}
}
Note regarding coding style:
Function declarations (function name(){}) do not have to be postfixed by a semicolon. It's not illegal though.
if (a === b) { ... } else if (a !== b){..} can be shortened to if (a === b) {...} else { ... }, because if a is not equal to b, then it is unequal.
Related
I'm making a puzzle game where the user uses WASD to move a character up, left, down, right respectively. It works fine at the moment but I was wondering if there was a way to break the code down into more intuitive functions. Below is my code:
function move(e)
{
for (var y = 0; y < mapHeight; y++) {
for (var x = 0; x < mapWidth; x++) {
if (map[y][x] == "#" || map[y][x] == "+") {
break;
}
}
if (map[y][x] == "#" || map[y][x] == "+") {
break;
}
}
var player_x = x;
var player_y = y;
if (e.key == 'w') {
var player_new_x = player_x;
var player_new_y = player_y - 1;
if (moveBox(player_new_x, player_new_y, "up") === false) {
return;
}
if (map[player_new_y][player_new_x] == " " ||
map[player_new_y][player_new_x] == ".") {
if (map[player_new_y][player_new_x] == " ") {
map[player_new_y][player_new_x] = "#";
} else if (map[player_new_y][player_new_x] == ".") {
map[player_new_y][player_new_x] = "+";
}
if (map[player_y][player_x] == "#") {
map[player_y][player_x] = " ";
} else if (map[player_y][player_x] == "+") {
map[player_y][player_x] = ".";
}
}
} else if (e.key == 's') {
var player_new_x = player_x;
var player_new_y = player_y + 1;
if (moveBox(player_new_x, player_new_y, "down") === false) {
return;
}
if (map[player_new_y][player_new_x] == " " ||
map[player_new_y][player_new_x] == ".") {
if (map[player_new_y][player_new_x] == " ") {
map[player_new_y][player_new_x] = "#";
} else if (map[player_new_y][player_new_x] == ".") {
map[player_new_y][player_new_x] = "+";
}
if (map[player_y][player_x] == "#") {
map[player_y][player_x] = " ";
} else if (map[player_y][player_x] == "+") {
map[player_y][player_x] = ".";
}
}
} else if (e.key == 'a') {
var player_new_x = player_x - 1;
var player_new_y = player_y;
if (moveBox(player_new_x, player_new_y, "left") === false) {
return;
}
if (map[player_new_y][player_new_x] == " " ||
map[player_new_y][player_new_x] == ".") {
if (map[player_new_y][player_new_x] == " ") {
map[player_new_y][player_new_x] = "#";
} else if (map[player_new_y][player_new_x] == ".") {
map[player_new_y][player_new_x] = "+";
}
if (map[player_y][player_x] == "#") {
map[player_y][player_x] = " ";
} else if (map[player_y][player_x] == "+") {
map[player_y][player_x] = ".";
}
}
} else if (e.key == 'd') {
var player_new_x = player_x + 1;
var player_new_y = player_y;
if (moveBox(player_new_x, player_new_y, "right") === false) {
return;
}
if (map[player_new_y][player_new_x] == " " ||
map[player_new_y][player_new_x] == ".") {
if (map[player_new_y][player_new_x] == " ") {
map[player_new_y][player_new_x] = "#";
} else if (map[player_new_y][player_new_x] == ".") {
map[player_new_y][player_new_x] = "+";
}
if (map[player_y][player_x] == "#") {
map[player_y][player_x] = " ";
} else if (map[player_y][player_x] == "+") {
map[player_y][player_x] = ".";
}
}
} else {
return;
}
render();
}
Is it possible to make four functions, one for each of the movement keys? Any help would be much appreciated
Yes
It´s possible to do what you want, 4 different functions
But ... you should intercept the events keydown (when the user presses the key) and keyup (when the user releases the key)
As long as the key is "pressed" you do the movement
You can create an object like this
let move = { moveH : 0 , moveV :0 }
When the keydown event is detected for "a" -> {moveH : -1, moveV :0}
"s" -> { moveH :0 , moveV :1 }
"w" -> { moveH :0 , moveV :-1 }
"d" -> { moveH :1 , moveV :0 }
When the keyup event is detected .. for any key -> {moveH :0 , moveV:0 }
Meanwhile
apply the move to the object on the screen
something like
stuff.position = { x : stuff.position.x + move.moveH , y: stuff.position.y + move.moveV }
I want to match two variables.
var this_roll;
and
var last_roll;
I have this code, that i want the output of "win" or "losse". The output should be "win" if last_roll and this_roll have the same value and "lose" if not
"use strict";
var x;
var win_losse = 'losse';
var last_roll;
var last_bet;
var this_roll = $('#past')[0].childNodes[9].textContent;
var bet_input = document.getElementById('betAmount').value=x;
var roll_time = $('#banner')[0].childNodes[0].textContent;
var base_bet = 5;
function thisRoll() {
console.log(this_roll);
if (this_roll == 0) {
this_roll = 'green';
} else if ((this_roll >= 1) && (this_roll <= 7)) {
this_roll = 'red';
} else if ((this_roll >= 8) && (this_roll <= 14)) {
this_roll = 'black';
}
}
function compare() {
if (this_roll == last_roll) {
win_losse = 'win';
} else {
win_losse = 'losse';
}
console.log(win_lose);
}
function lastRoll() {
console.log(this_roll);
if (this_roll == 0) {
last_roll = 'green';
} else if ((this_roll >= 1) && (this_roll <= 7)) {
last_roll = 'red';
} else if ((this_roll >= 8) && (this_roll <= 14)) {
last_roll = 'black';
}
}
function bet() {
if (win_losse == 'win') {
x = base_bet;
} else if (win_losse == 'losse') {
x = last_bet * 2;
}
}
console.log(x);
This works for sure
"use strict";
//Removed the global x variable
//Removed the global win_lose variable
var last_roll = $('#past')[0].childNodes[8].textContent;
var last_bet;
var this_roll = $('#past')[0].childNodes[9].textContent;
var bet_input = document.getElementById('betAmount').value=x;
//Removede the Roll_time variable because it wasn't used
var base_bet = 5;
function ThisRoll(this_roll) {
var rollhisThis; //Added a local variable
if (this_roll === 0) {
rollhisThis = 'green';
} else if ((this_roll >= 1) && (this_roll <= 7)) {
rollhisThis = 'red';
} else if ((this_roll >= 8) && (this_roll <= 14)) {
rollhisThis = 'black';
}
return rollhisThis; //Added return
}
var thisRoll = ThisRoll(this_roll); //Added a new global variable
console.log(thisRoll);
function LastRoll(last_roll) {
var rollhisLast; //Added a local variable
if (last_roll === 0) {
rollhisLast = 'green';
} else if ((last_roll >= 1) && (last_roll <= 7)) {
rollhisLast = 'red';
} else if ((last_roll >= 8) && (last_roll <= 14)) {
rollhisLast = 'black';
}
return rollhisLast; //Added return
}
var lastRoll = LastRoll(last_roll); //Added a new global variable
console.log(LastRoll);
function compare(thisRoll, lastRoll) {
var win_lose; //Added a local win_lose variable
if (thisRoll !== lastRoll) {
win_lose = 'lose';
} else {
win_lose = 'win';
}
return win_lose; //Added return
}
var winLose = compare(thisRoll, lastRoll); //Added a gloabl variable
console.log(winLose);
function bet() {
if (win_losse == 'win') {
x = base_bet;
} else if (win_losse == 'losse') {
x = last_bet * 2;
}
}
console.log(x);
Rps game code isn't working. My battle function is supposed to set win to a 1,2, or 3 but it always stays at the default 0. I've checked the other values through the console, and they all seem to be working. here is my code.
function Player(number) {
this.number = number;
this.choice = 0;
}
var player1 = new Player(1);
var player2 = new Player(2);
var win = 0;
var battle = function() {
if (player1.choice === player2.choice) {
win = 3;
} else if (player1.choice + 2 === player2.choice && player1.choice === 1){
win = 2;
} else if (player1.choice + 1 === player2.choice && player1.choice === 1) {
win = 1;
} else if (player1.choice + 1 === player2.choice && player1.choice === 2) {
win = 1;
} else if (player1.choice - 1 === player2.choice && player1.choice === 2) {
win = 2;
} else if (player1.choice - 1 === player2.choice && player1.choice === 3) {
win = 2;
} else if (player1.choice - 2 === player2.choice && player1.choice === 3) {
win = 1;
} else {
alert ('someone pressed the wrong button')
}
}
var Reset = function () {
win = 0;
player1.choice = 0;
player2.choice = 0;
}
$(document).ready(function() {
$(document).keydown(function(event) {
if (event.which === 81) {
player1.choice = 1;
} else if (event.which === 87){
player1.choice = 2;
} else if (event.which === 69){
player1.choice = 3;
} else if (event.which === 37){
player2.choice = 1;
} else if (event.which === 40){
player2.choice = 2;
} else if (event.which === 39){
player2.choice = 3;
}
})
if (player1.choice > 0 && player2.choice > 0) {
battle();
if (win === 1) {
$('.winner').append('<p>player1 wins!</p>')
} else if (win === 2) {
$('.winner').append('<p>player2 wins!</p>')
} else if (win === 3) {
$('.winner').append('<p>It is a draw!</p>')
}
}
})
My html has the div with class 'winner' in it.
Additional question
How do I cancel the keydown function after both players have chosen their options.
Are you giving your player a choice in the Player class you created? It should look like this:
function Player(number, choice) {
this.number = number;
this.choice = choice;
}
I want to optimise and reduce my code to increase performance and correct-ability of it. With those two different functions below I can successfuly move a Google Map Marker on a map forward and backward using a pathIndex, calcuted on an array of GPS coordinates [I didn't include this section of code since I think it's not releated to this question but I can and will post it if needed].
This is my code:
1st function:
function animate() {
if (pathIndex < coord.length && mapAnimationStatus != PLAY_PAUSED) {
googleMapsMarker.setPosition(coord[pathIndex]);
googleMap.panTo(coord[pathIndex]);
pathIndex += 1;
if (pathIndex == coord.length) {
pause();
pathIndex = 0;
mapAnimationStatus = NOT_PLAY;
return;
}
timerHandler = setTimeout("animate(" + pathIndex + ")", 1000);
}
}
2nd function:
function animateRewind() {
if (pathIndex >= 0 && mapAnimationStatus != PLAY_PAUSED) {
googleMap.panTo(coord[pathIndex]);
googleMapsMarker.setPosition(coord[pathIndex]);
if (pathIndex == 0) {
pause();
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex -= 1;
timerHandler = setTimeout("animateRewind(" + pathIndex + ")", 1000);
}
}
As you can see those two functions shares a lot of portions of code and it think that they can be replaced with a single one for this reason but I can't figure out how to do this.
So, is it possible to create a single function to manage those two different animations?
I hope I didnt miss something...
function animate(pathIndex, dir) {
var animateDir = (pathIndex < coord.length
&& mapAnimationStatus != PLAY_PAUSED && dir == 'f')
? dir
: (pathIndex >= 0
&& mapAnimationStatus != PLAY_PAUSED && dir == 'r')
? dir : "error";
if (animateDir === "r") { googleMap.panTo(coord[pathIndex]); }
if (animateDir !== 'error') { googleMapsMarker.setPosition(coord[pathIndex]); }
if (animateDir === "f") {
googleMap.panTo(coord[pathIndex]);
pathIndex += 1;
}
if (animateDir !== 'error') {
if (pathIndex == coord.length || pathIndex == 0) {
pause();
pathIndex = animateDir === "f" ? 0 : pathIndex;
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex = animateDir === "f" ? pathIndex - 1 : pathIndex;
timerHandler = setTimeout("animate(" + pathIndex + "," + animateDir + ")", 1000);
}
}
You can try this :
function ConcatenateFunctions() {
if(mapAnimationStatus != PLAY_PAUSED){
googleMap.panTo(coord[pathIndex]);
googleMapsMarker.setPosition(coord[pathIndex]);
if (pathIndex < coord.length) {
pathIndex += 1;
if (pathIndex == coord.length) {
pause();
pathIndex = 0;
mapAnimationStatus = NOT_PLAY;
return;
}
}else if (pathIndex >= 0) {
if (pathIndex == 0) {
pause();
mapAnimationStatus = NOT_PLAY;
return;
}
pathIndex -= 1;
}
timerHandler = setTimeout("ConcatenateFunctions(" + pathIndex + ")", 1000);
}
}
Hope it will help !
Below is my code. It is supposed to filter a table. It functions great in everything but IE. Can you help?
Perhaps there is a missing tag or something. I've been over it a number of times and could really do with someone's help please!
<script type="text/javascript">
function hasPath(element, cls) {
return (' ' + element.getAttribute('pathway')).indexOf(cls) > -1;
}
function hasLevel(element, cls) {
return (' ' + element.getAttribute('level')).indexOf(cls) > -1;
}
function hasBody(element, cls) {
return (' ' + element.getAttribute('body')).indexOf(cls) > -1;
}
function QualificationSearch() {
var imgdiv = document.getElementById("Chosen_Pathway_img");
var p = document.getElementById("PathwaySelect");
var pathway = p.options[p.selectedIndex].value;
if (pathway == "ALLPATHS") {
pathway = "";
imgdiv.src = "/templates/superb/images/QualChecker/pic_0.png"
}
if (pathway == "ES") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_1.png"
}
if (pathway == "HOUSING") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_2.png"
}
if (pathway == "PLAYWORK") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_3.png"
}
if (pathway == "SC") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_4.png"
}
if (pathway == "YW") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_5.png"
}
var a = document.getElementById("AwardingBodySelect");
var awardingBody = a.options[a.selectedIndex].value;
if (awardingBody == "ALLBODIES") {
awardingBody = "";
}
var levelGroup = document.getElementsByName("LevelGroup");
var chosenLevel = ""
for (var g = 0; g < levelGroup.length; g++) {
if (levelGroup[g].checked) {
chosenLevel += levelGroup[g].value + " ";
}
}
if (chosenLevel == undefined) {
var chosenLevel = "";
} else {
var splitLevel = chosenLevel.split(" ");
var levelA = splitLevel[0];
var levelB = splitLevel[1];
var levelC = splitLevel[2];
var levelD = splitLevel[3];
if (levelA == "") {
levelA = "NOLVL"
}
if (levelB == "") {
levelB = "NOLVL"
}
if (levelC == "") {
levelC = "NOLVL"
}
if (levelD == "") {
levelD = "NOLVL"
}
}
var fil = document.getElementsByName("QList");
for (var i = 0; i < fil.length; i++) {
fil.item(i).style.display = "none";
if ((hasBody(fil.item(i), awardingBody) == true || awardingBody == "") && (hasPath(fil.item(i), pathway) == true || pathway == "") && ((hasLevel(fil.item(i), levelA) == true || hasLevel(fil.item(i), levelB) == true || hasLevel(fil.item(i), levelC) == true || hasLevel(fil.item(i), levelD) == true) || chosenLevel == "")) {
fil.item(i).style.display = "block";
}
}
}
</script>
Check your semicolons. IE is far more strict on that kind of stuff than FF.