What did I do wrong with this code for SImon game? - javascript

everyone! My name is Kate and I am a beginner in developing. Currently I am working on my test project, called "Simon game". I finished it but it doesn't work in a proper way. I checked the code million times, but can't find any errors. Please, look through it and if you can, please, help me to correct it.
var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];
var userClickedPattern = [];
var started = false;
var level = 0;
$(document).keypress(function() {
if (!started) {
$("#level-title").text("Level " + level);
nextSequence();
started = true;
}
});
$(".btn").click(function() {
var userChosenColor = $(this).attr("id");
userCLickedPattern.push(userChosenColor);
playSound(userChosenColor);
animatePress(userChosenColor);
checkAnswer(userClickedPattern.length-1);
});
function checkAnswer(currentLevel) {
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
if (userClickedPattern.length === gamePattern.length) {
setTimeOut(function () {
nextSequence();
}, 1000);
}
} else {
playSound("wrong");
$("body").addClass("game-over");
$("#level-title").text("Game over, Press Any Key To Restart");
setTimeout(function () {
$("body").removeClass("game-over");
}, 200);
startOver();
}
}
function nextSequence() {
userClickedPattern = [];
level++;
$("#level-title").text("Level " + level);
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber];
gamePattern.push(randomChosenColor);
$("#" + randomChosenColor).fadeIn(100).fadeOut(100).fadeIn(100);
playSound(randomChosenColor);
}
function playSound(name) {
var audio = new Audio("sounds/" + name + ".mp3");
audio.play();
}
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
setTimeout(function () {
$("#" + currentColor).removeClass("pressed");
}, 100);
}
function startOver() {
level = 0;
gamePattern = [];
started = false;
}
I don't understand why the website doesn't react to a click on a button.
I check the button section, everything seems fine 🤷‍♀️

Related

Reset Valuable and repeated action

I am building a game, where the computer makes a patter of four colors and you have to remember the pattern and repeat it.
And it works almost fine, but there is one error which i cant figure out.
When i played a round and lost and the game restarts the level value goes to 2 instead of 1.
And when the new game starts the first two buttons get pressed at the same time.
At the first round everything works fine but the next round not.
var gamePattern = [];
var playerPattern = [];
var buttonColors = ["red", "blue", "green", "yellow"]
var level = 0;
$(".btn").click(function () {
if (patternDone) {
pressButton(this.id);
playerPattern.push(this.id);
checkAnswer();
}
});
function resetGame() {
gamePattern = [];
playerPattern = [];
gamePattern.length = 0;
playerPattern.length = 0;
patternDone = false;
level = 0;
$("h1").html("Press A Key to Start")
$(document).keypress(startGame);
}
//start
$(document).keypress(startGame);
//start Game
function startGame() {
level = level + 1;
console.log("level " + level);
console.log(level);
gamePattern = [];
playerPattern = [];
createLevel();
console.log(gamePattern)
playPattern();
patternDone = true;
$("h1").html("Level " + level)
}
//play the patter
async function playPattern() {
for (k = -1; k < level; k++) {
d = level - k;
// console.log(gamePattern);
abcColor = gamePattern[gamePattern.length - d];
console.log(abcColor);
await delay(1000);
pressButton(abcColor);
d = 0;
}
}
//create the level
function createLevel() {
for (y = 0; y <= level; y++) {
var randomColor = buttonColors[Math.floor(Math.random() * buttonColors.length)];
gamePattern.push(randomColor);
}
}
//update h1
function h1Level() {
levelCopy = level + 1;
$("h1").html("level " + levelCopy);
}
//pressButton
function pressButton(colord) {
// console.log(colord);
animatePress(colord);
playSound(nameSound = colord);
}
// Sound
function playSound(nameSound) {
var audio = new Audio("sounds/" + nameSound + ".mp3");
audio.play();
}
// animateClick
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
// console.log(currentColor);
setTimeout(function () {
$("#" + currentColor).removeClass("pressed");
}, 100);
}
//delay
const delay = millis => new Promise((resolve, reject) => {
setTimeout(_ => resolve(), millis)
});
//Button click and deciding if its right
async function checkAnswer() {
if (playerPattern.length === gamePattern.length) {
if (playerPattern.join(',') === gamePattern.join(',')) {
$("h1").html("Correct!");
console.log("correct");
await delay(1000);
startGame();
} else if (playerPattern.join(',') !== gamePattern.join(',')) {
$("h1").html("Wrong!");
level = 0;
console.log("wrong");
await delay(3000);
resetGame();
}
}
}

passing a simon game from jQuery to vanilla JS

Long story short, I made this Simon Game in a bootcamp a month ago in jQuery, but the days pass and I started to feel the necesity of translate it to pure vanilla javaScript.
the thing is that I feel stuck in the last part, when I have to check the answers of the game and add that to the gamePatern array and userChosenPattern.
here is the main part in jQuery
var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];
var userClickedPattern = [];
var started = false;
var level = 0;
$(document).keypress(function () {
if (!started) {
$("#level-title").text("level " + level);
nextSequence();
started = true;
}
});
function nextSequence() {
userClickedPattern = [];
level++;
$("#level-title").text("level " + level);
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColour = buttonColors[randomNumber];
gamePattern.push(randomChosenColour);
$("#" + randomChosenColour)
.fadeIn(100)
.fadeOut(100)
.fadeIn(100);
playSound(randomChosenColour);
}
$(".btn").click(function () {
var userChosenColor = $(this).attr("id");
userClickedPattern.push(userChosenColor);
playSound(userChosenColor);
animatePress(userChosenColor);
checkTheAnswer(userClickedPattern.length - 1);
});
function checkTheAnswer(currentLevel) {
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
console.log("success");
if (userClickedPattern.length === gamePattern.length) {
setTimeout(function () {
nextSequence();
}, 1000);
}
} else {
$("body").addClass("game-over");
setTimeout(function () {
$("body").removeClass("game-over");
}, 200);
gameOverAudio();
$("#level-title").text("Game Over, Press Any Key to Restart");
$("#level-title").css("font-size", "2rem");
startOver();
}
}
function startOver() {
level = 0;
gamePattern = [];
started = false;
}
function playSound(name) {
var audio = new Audio("sounds/" + name + ".mp3");
audio.play();
}
function gameOverAudio() {
var gameOver = new Audio("sounds/wrong.mp3");
gameOver.play();
}
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
setTimeout(function () {
$("#" + currentColor).removeClass("pressed");
}, 100);
}
and here is the same part and the whole code but in vanilla JS
const buttonColors = ["red", "blue", "green", "yellow"];
const gamePattern = [];
const userClickedPattern = [];
const started = false;
const level = 0;
const body = document.querySelector("body");
const levelTitle = document.getElementById("level-title");
// to start the game
document.addEventListener("keypress", () => {
if (!started) {
levelTitle.innerHTML = `level ${level}`;
nextSequence();
sarted = true;
}
});
// generete the next sequence
function nextSequence() {
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColour = buttonColors[randomNumber];
gamePattern.push(randomChosenColour);
let animationBtn = document.querySelector("#" + randomChosenColour);
animationBtn.classList.add("FadeInFadeOut");
setTimeout(() => {
animationBtn.classList.remove("FadeInFadeOut");
}, 50);
playSound(randomChosenColour);
}
// here we detect which button is pressed by the user
var bTn = document.getElementsByClassName("btn");
document.querySelectorAll(".btn").forEach((bt) => {
bt.onclick = () => {
let userChosenColor = bt.id;
userClickedPattern.push(userChosenColor);
playSound(userChosenColor);
animatePress(userChosenColor);
checkTheAnswer(userClickedPattern.length - 1);
};
});
// check the answer and dynamic of the game
const checkTheAnswer = (currentLevel) => {
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
console.log("succes");
if (userClickedPattern.length === gamePattern.length) {
setTimeout(() => {
nextSequence();
}, 1000);
}
} else {
body.classList.add("game-over");
setTimeout(() => {
body.classList.remove("game-over");
}, 200);
gameOverAudio();
levelTitle.innerHTML = `Game Over, Press Any Key to Restart`;
levelTitle.style.fontSize = "2rem";
startOver();
}
};
const startOver = () => {
level = 0;
gamePattern = [];
started = false;
};
// adudio stuff
const playSound = (name) => {
let audio = new Audio("sounds/" + name + ".mp3");
audio.play();
};
function gameOverAudio() {
var gameOver = new Audio("sounds/wrong.mp3");
gameOver.play();
}
//animation in button
const animatePress = (currentColor) => {
const buttons = document.querySelector(`#${currentColor}`);
buttons.classList.add("pressed");
setTimeout(() => {
buttons.classList.remove("pressed");
}, 100);
};
console.log(gamePattern);
console.log(userClickedPattern);
Also here is the game in my codepen, it’s without the sounds for obvious reasons.
Simon Game

Uncaught TypeError: in JS this.changeRoundScore is not a function at HTMLButtonElement.roll (app.js:35)

I'm relatively new to JS and I'm getting an error when trying to write a simple 'pig game'. I have tried a variety of things, but I haven't figured out exactly what is going on.
If I roll the dice dice.roll(); in my JS file there is no error. It is only erroring with the addEventListener when I click on the button from Chrome.
This is the error I am getting:
Uncaught TypeError: this.changeRoundScore is not a function at HTMLButtonElement.roll (app.js:35)
EDIT: I just changed the start function to the following and it worked...can someone explain why?
let start = function() {
console.log(playerOne);
console.log(playerTwo);
console.log(dice);
document.querySelector('.btn-roll').addEventListener('click', function() {
dice.roll();
});
}
Original code:
class Player {
constructor(active) {
this.score = 0;
this.roundScore = [];
this.active = active;
}
changeActive(active) {
this.active = active;
}
addRoundScore(score) {
this.roundScore.push(score);
}
}
class Dice {
constructor(playerOne, playerTwo) {
document.querySelector('.dice').style.display = 'none';
this.playerOne = playerOne;
this.playerTwo = playerTwo;
}
roll() {
let roll = Math.floor(Math.random()*6) + 1;
// document.querySelector('.dice').style.display = 'visible';
this.changeRoundScore(roll);
}
changeRoundScore(score) {
document.querySelector('#current-' + activePlayer).textContent = score;
document.querySelector('.dice').src = 'dice-' + score + '.png';
if (activePlayer === 0) {
playerOne.addRoundScore(score);
} else if (activePlayer === 1) {
playerTwo.addRoundScore(score);
}
}
}
let activePlayer = 0;
let playerOne = new Player(1);
let playerTwo = new Player(0);
let dice = new Dice(playerOne, playerTwo);
let start = function() {
console.log(playerOne);
console.log(playerTwo);
console.log(dice);
document.querySelector('.btn-roll').addEventListener('click', dice.roll);
}
start();

How to execute this function without clicking on a button

So this is a part of greasemonkey userscript. It's an adviser for an online game. At the end of it i've got this:
function do_login() {
// var loc = reg2.exec(document.location.href);
//Auto backing to login page
if (document.location.href.search("logout") != -1) {
window.setTimeout(function () {
document.location.href = "http://www" + gamepage;
}, 100);
}
else {
//login
try {
var logindata = explode(GM_getValue("logindata", "[]"));
}
catch (err) {
var logindata = new Array;
}
unsafeWindow.showDiv("login_div");
$("login_div").style.zIndex = "20";
$("login_div").getElementsByClassName("kh_btn")[0].addEventListener("click", function () {
var currServer = $("l_server").value;
var currUser = $("l_loginname").value.toLowerCase();
GM_setValue(lng + "_" + currServer + "_username", currUser);
}, false);
function submit_login(currUserNr) {
$("l_server").value = logindata[currUserNr][1];
$("l_loginname").value = logindata[currUserNr][2];
$("l_password").value = logindata[currUserNr][3];
$("login_div").getElementsByClassName("kh_btn")[0].click();
}
var newdiv = createElement("div", {style: "position:absolute;top:0px;left:0px;width:412px;padding:10px;background-color:#999;-moz-border-radius:10px;"}, $("login_div"));
for (var v = 0; v < logindata.length; v++) if (logindata[v][1] != "0") {
var newbutton = createElement("button", {type: "button", class: "cursorclickable", id: "autologin" + v, style: "width:200px;height:20px;margin:3px;"}, newdiv, texte["server"] + " " + logindata[v][1] + "." + logindata[v][0] + ": " + logindata[v][2]);
newbutton.addEventListener("click", function () {
submit_login(this.id.replace("autologin", ""));
}, false);
}
newdiv = null;
newbutton = null;
}
}
It's executed when script finds "logout" in the url.
Now, everything works, it's entering main-page, creating a button, the button itself works, but now i would like to execute "onlick" automatically.
You could select the element and then invoke the .click() method:
document.querySelector('#myElement')[0].click();

How to load first video in playlist using javascript

I am using the tubeplayer plugin to generate video playlists for my hot 100 music chart website http://beta.billboard.fm.
I pull playlist data and generate video playlists based on that data. The problem is that I currently am manually entering the youtube video ID for initial video load video on the home page, where I would like to create a variable that dynamically pulls the first youtube video id and inserts after initialVideo
So I am trying to create a variable that pulls track #1 from the hot 100 year playlist that I can place in the standard plugin parameters:
I will define it as var initialVideoID =
<script>
// IE workaround
function JSONQuery(url, callback) {
if ($.browser.msie && window.XDomainRequest) {
// alert('ie');
// var url = "http://gdata.youtube.com/feeds/api/videos?q=cher&category=Music&alt=json";
// Use Microsoft XDR
var xdr = new XDomainRequest();
xdr.open("get", url);
xdr.onerror = function () {
console.log('we have an error!');
}
xdr.onprogress = function () {
// console.log('this sucks!');
};
xdr.ontimeout = function () {
console.log('it timed out!');
};
xdr.onopen = function () {
console.log('we open the xdomainrequest');
};
xdr.onload = function () {
// XDomainRequest doesn't provide responseXml, so if you need it:
var dom = new ActiveXObject("Microsoft.XMLDOM");
dom.async = true;
dom.loadXML(xdr.responseText);
// alert(xdr.responseText);
callback(jQuery.parseJSON(xdr.responseText));
// alert(data.feed.entry[0].media$group.media$content[0].url);
// alert("ie");
};
xdr.send();
} else {
$.getJSON(url, callback);
}
};
var yearMap = [];
createYearMap();
function createYearMap() {
yearMap["1940"] = [1946, 1947, 1948, 1949];
yearMap["2010"] = [2010, 2011, 2012];
for (var i = 195; i < 201; i++) {
var curDecade = i * 10;
yearMap[curDecade.toString()] = [];
for (var j = 0; j < 10; j++) {
yearMap[curDecade][j] = curDecade + j;
}
}
}
// console.log(yearMap["2010"]);
(function ($) {
$(window).ready(function () {
// alert("before get");
// $.get("test.htm", function(data) {
// // var fileDom = $(data);
// // alert("get callback");
// $("#jqueryTest").html(data);
// });
// setInterval(function(){alert("Hello")},3000);
$(".song-description").mCustomScrollbar();
// var url = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=26178ccca6d355d31b413f3d54be5332&artist=" +"pink floyd" + "&track=" + "money" + "&format=json";
// JSONQuery(url, function(data) {
// if (data.track) {
// if (data.track.wiki) {
// $("#song-info").html(data.track.wiki.summary);
// } else {
// $("#song-info").html("No song info found");
// }
// } else {
// $("#song-info").html("No song info found");
// console.log("artist not found");
// }
// $(".song-description").mCustomScrollbar("update");
// });
// $("#example tbody tr").click(function() {
// selectPlaying(this, true);
// });
jQuery(".youtube-video").tubeplayer({
width: 300, // the width of the player
height: 225, // the height of the player
allowFullScreen: "true", // true by default, allow user to go full screen
initialVideo: var initialvideoID, // the video that is loaded into the player
preferredQuality: "default", // preferred quality: default, small, medium, large, hd720
showinfo: true, // if you want the player to include details about the video
modestbranding: true, // specify to include/exclude the YouTube watermark
wmode: "opaque", // note: transparent maintains z-index, but disables GPU acceleratio
theme: "dark", // possible options: "dark" or "light"
color: "red", // possible options: "red" or "white"
onPlayerEnded: function () {
videoEnded();
},
onPlayerPlaying: function (id) {
setIconToPause();
}, // after the play method is called
onPlayerPaused: function () {
setIconToPlay();
}, // after the pause method is called
onStop: function () {}, // after the player is stopped
onSeek: function (time) {}, // after the video has been seeked to a defined point
onMute: function () {}, // after the player is muted
onUnMute: function () {} // after the player is unmuted
});
setInterval(function () {
updateProgressBar()
}, 1000);
loadPlaylist("hot100", true);
});
})(jQuery);
var initialvideoID = "yyDUC1LUXSU"
function videoEnded() {
nextVideo();
}
var intervalTimer;
function startPlayer() {
jQuery(".youtube-video").tubeplayer("play");
playing = true;
clearInterval(intervalTimer);
intervalTimer = setInterval(function () {
updateProgressBar()
}, 1000);
setIconToPause();
}
function setIconToPause() {
var button = $(".icon-play");
if (button) {
button.removeClass("icon-play")
button.addClass("icon-pause");
}
}
function setIconToPlay() {
var button = $(".icon-pause");
if (button) {
button.removeClass("icon-pause")
button.addClass("icon-play");
}
}
function pausePlayer() {
jQuery(".youtube-video").tubeplayer("pause");
playing = false;
clearInterval(intervalTimer);
setIconToPlay();
}
function selectPlaying(item, autoStart) {
var nowPlayingItem = $(".nowPlaying");
if (nowPlayingItem) {
nowPlayingItem.removeClass("nowPlaying");
}
$(item).addClass("nowPlaying");
var aPos = $('#example').dataTable().fnGetPosition(item);
var aData = $('#example').dataTable().fnGetData(aPos);
if (aData[3]) {
// $("#song-info").html("Loading song info...");
$("#song-info").html("");
var url = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=26178ccca6d355d31b413f3d54be5332&artist=" + aData[1] + "&track=" + aData[2] + "&format=json";
JSONQuery(url, function (data) {
if (data.track) {
if (data.track.wiki) {
$("#song-info").html(data.track.wiki.summary);
} else {
$("#song-info").html("No song info found");
}
} else {
$("#song-info").html("No song info found");
console.log("artist not found");
}
// $(".song-description").mCustomScrollbar("update");
});
$(".info-rank").html("#" + aData[0]);
$(".info-artist").html(aData[1]);
$(".info-song").html(aData[2]);
$(".info-year").html($("#navYear").html());
var ytId = aData[3];
if (autoStart) {
jQuery(".youtube-video").tubeplayer("play", ytId);
setIconToPause();
} else {
jQuery(".youtube-video").tubeplayer("cue", ytId);
setIconToPlay();
}
clearInterval(intervalTimer);
intervalTimer = setInterval(function () {
updateProgressBar()
}, 1000);
playing = true;
// alert("youtube video id is: " + ytId);
} else {
alert("no youtube id");
}
}
function previousVideo() {
var curPlaying = $(".nowPlaying")[0];
var nextItem;
if (curPlaying) {
nextItem = $('#example').dataTable().fnGetAdjacentTr(curPlaying, false);
if (!nextItem) {
nextItem = $('#example').dataTable().fnGetNodes($('#example').dataTable().fnSettings().fnRecordsTotal() - 1);
}
} else {
nextItem = $('#example').dataTable().fnGetNodes(0);
}
selectPlaying(nextItem, true);
}
function nextVideo() {
var curPlaying = $(".nowPlaying")[0];
var nextItem;
if (curPlaying) {
nextItem = $('#example').dataTable().fnGetAdjacentTr(curPlaying, true);
if (!nextItem) {
nextItem = $('#example').dataTable().fnGetNodes(0);
}
} else {
nextItem = $('#example').dataTable().fnGetNodes(0);
}
selectPlaying(nextItem, true);
}
function updateProgressBar() {
// console.log("update bar");
myData = jQuery(".youtube-video").tubeplayer("data");
// console.log("update progress bar: " + (myData.currentTime / myData.duration * 100) + "%");
$(".bar").width((myData.currentTime / myData.duration * 100) + "%");
}
var playing = false;
function playPauseClick() {
if (playing) {
pausePlayer();
} else {
startPlayer();
}
}
function loadPlaylist(year) {
loadPlaylist(year, false);
}
function loadPlaylist(year, cueVideo) {
$.get("playlist/" + year + "playlist.txt", function (data) {
// var fileDom = $(data);
// alert("get callback");
// $("#playlistContents").html(data);
// $('#example').dataTable().fnAddData(data);
// var obj = eval("[[1,2,3],[1,2,3]]");
// obj = eval(data.toString());
obj = $.parseJSON(data);
// console.log(obj);
$('#example').dataTable().fnClearTable();
$('#example').dataTable().fnAddData(obj);
// $("#example tbody tr").click(function() {
// selectPlaying(this, true);
// });
if (year == "hot100") {
$("#navYear").html("Weekly Hot 100");
$("#navYearLabel").hide();
} else {
$("#navYear").html(year);
$("#navYearLabel").show();
}
if (cueVideo) {
selectPlaying($('#example').dataTable().fnGetNodes(0), false);
}
// $('#example').dataTable().fnAddData(data);
});
}
function modalDecadeClick(decade) {
var string = "";
if (decade == 'hot100') {
loadPlaylist("hot100");
$('#modal-example-decade').modal('hide');
$('#modal-year').modal('hide');
} else {
for (var i = 0; i < yearMap[decade].length; i++) {
string += '<li>' + yearMap[decade][i] + '</li>';
}
$('#modal-example-decade').modal('hide');
$('#specific-year-list').empty();
$('#specific-year-list').html(string).contents();
}
}
function modalYearClick(node) {
var year = parseInt($(node).children("li").html());
// console.log($(node).children("li").html());
$('#modal-year').modal('hide');
loadPlaylist(year);
}
function progressBarClick(e) {
var seekPercent = (e.pageX - $(".progress:first").offset().left) / $(".progress:first").width();
var seekTime = jQuery(".youtube-video").tubeplayer("data").duration * seekPercent;
jQuery(".youtube-video").tubeplayer("seek", seekTime);
}
var minYear = 1946;
var maxYear = 2012;
function nextYear() {
var year = $("#navYear").html();
if (year == "Weekly Hot 100") {
alert("Max year is " + maxYear);
return;
}
year = parseInt($("#navYear").html());
year++;
if (year > maxYear) {
loadPlaylist("hot100");
return;
}
loadPlaylist(year);
}
function prevYear() {
var year = $("#navYear").html();
if (year == "Weekly Hot 100") {
loadPlaylist(2012);
return;
}
year = parseInt($("#navYear").html());
year--;
if (year < minYear) {
alert("Min year is " + minYear);
return;
}
loadPlaylist(year);
}
function closeFilter() {
toggle_visibility('toggle-filter');
var oTable = $('#example').dataTable();
// Sometime later - filter...
oTable.fnFilter('');
}
</script>

Categories

Resources