Simon game mechanism (Javascript) -- Sequence input - javascript

Essentially I have the following:
1) Game will randomly pre-choose 20 random sequence
2) Game will turn off click event listener
3) Game will display the light sequence for each level(starting level 1)
4) Game will turn on click event listener so that user can input via .buttons
5) Game will evaluate user's input
I am having trouble on the 5th step...
How do evaluate user's input while the game is still running? I thought about using while loop but it seems that doesn't work quite nicely...
Board.prototype.getUserInput = function(){
board.userInput = []; //reset the user input
$(".button").click(function(){
var currentLevel = board.sequence.slice(0,board.index);
var color = $(this).attr('id');
board.userInput.push(color)
board.evaluateInput(currentLevel);
})
}
heres my codepen: http://codepen.io/neotriz/pen/RRxOJb

This is an old implementation i had done of the game.
http://codepen.io/antoniskamamis/pen/pJAxq?editors=0010#0
Basically since you have predefined the order all you have to do is increase a counter with each click on a color and check if the color clicked is the one in the nth position of your predefined colors
pseudocode for the solution
var predefinedColors = ['red', 'yellow',...]
var turn = 0;
buttons.addEventListener("click", ev => {
if(ev.target.classList.contain(predefinedColors[turn]){
//right guess
turn++
} else {
// wrong guess reset game
}
})

Related

Setting a limit on the number of times a note is created

I am currently working on a postIt for my website where pressing the plus button would create an editable post it/sticky notes. I am done with that part now but I am struggling with the next part which is limiting the number of sticky notes to just 4. I tried having a global variable that would serve as a counter so when the counter is 3, it should stop creating more sticky notes but unfortunately, it is not working.
Here is the link to my workable code:
Sticky note
And this is my futile attempt at limiting the number of sticky notes to 4.
$("#create").click(function(){
var count = 0;
if( count < 4){
$("#create").click(function() {
$(this).before("<textarea></textarea>");
});
count++;
}
}
Can anyone please give me pointers as to how to limit the notes to 4? I have been working on this forever now.
Just move var count = 0; outside the event listener and remove the inner event listener:
var count = 0; // outside the scope of the event listener function bellow so it won't get destroyed/recreated each time the function get called (ie when a clicks happen)
$("#create").click(function() {
if(count < 4) { // we haven't yet exceeded the limits
$(this).before("<textarea></textarea>"); // don't attach another click event listener on #create (we are already in one) so just create the note.
count++;
}
});
Everytime you click create, count the number of textarea elements then determine if you should create a new one:
$("#create").click(function() {
var count = $("textarea");
if (count.length < 4) {
$(this).before("<textarea></textarea>");
}
});
You can even add a class in the newly created textarea to ensure that you only count the ones created by this function.
HTML:
<textarea>This is not part of the group.</textarea>
<textarea class="sticky">This is a sticky note you can type and edit.</textarea>
<div id="create">+</div>
JS:
$("#create").click(function() {
var count = $("textarea.sticky");
if (count.length < 4) {
$(this).before("<textarea class='sticky'></textarea>");
}
});
The problem is that you are defining your count variable inside of your click event handler. As such, every time you click the element, the counter gets reset. You also shouldn't make use of a secondary click handler inside the main one.
To resolve this, bring the count variable outside of the click handler:
var count = 0;
$("#create").click(function() {
if (count < 3) {
$(this).before("<textarea></textarea>");
count++;
}
});
Note that the conditional should check that the count is less than 3, because it increases the count after creation. If it is set to check if the count is less than 4, five notes would be created.
In order to also hide the + after creating the fourth element, you would use:
if (count == 3) {
$(this).hide();
}
After increasing the count.
This can be seen working here.
Hope this helps! :)

onclick event in a for loop certain amount of times

I thought that this onClick event in a For loop would help me but when I tried it, it still didn't work.
I am making a simple Battleship game, and while I'm trying to have the user click on only 4 squares to place on ship, the loop keeps going and doesn't stop after 4 tries. I have my onclick even handler in a for loop, but after 4 tries it doesn't stop. I've tried adding a count variable after the end, and even tried adding a break statement but can't get it to work.
Here's my code:
function placeShips() {
var playerTable = document.getElementById("mainPlayer");
var playerCells = playerTable.getElementsByTagName("td");
var count = 1;
alert("Please place the first ship. Click on 4 squares.");
while (count <= 4) {
for (i = 0; i < playerCells.length; i++) {
playerCells[i].onclick = placeBattleship;
}
count++;
}
}
The placeBattleship function contains the code to change the grid square to a background color of red to mark it. My problem is that once the user clicks 4 squares, you can keep going and click on more and more. I can't get the above for loop that calls the placeBattleship function to stop after the user clicks on 4 squares. I've tried putting it in a while loop, and even the solution in the above link, as well as moving the assignment of count, but can't get it to stop after x amount of times (in this case, 4).
Any ideas on what I'm doing wrong, or a better way to do it?
Wouldn't you consider to use jQuery?
Look your function much shorter:
function placeShips() {
$("td:lt(4)").click(placeBattleship);
}
You can testify on the code below:
<table>
<tr>
<td>1.1</td><td>2.1</td>
</tr>
<tr>
<td>1.2</td><td>2.2</td>
</tr>
<tr>
<td>1.3</td><td>2.3</td>
</tr>
</table>
<div id="console"></div>
<script>
$("td:lt(4)").each(function(){
$("#console").append("Content of "+ $(this).html() + "<br/>");
});
$("td:lt(4)").click(function(){
$("#console").append("Clicking "+ $(this).html() + "<br/>");
});
</script>
...or on my Plunker: https://plnkr.co/edit/yNZw6ZhkNfA9E0NdQg7V
So, now we have a solution that stop for 4th click on the squares:
function placeBattleship() {
var $shipDisplay = $("#shipDisplay");
var counter = $shipDisplay.data("counter");
if(counter++ < 4) {
$(this).css("background-color", "red");
$shipDisplay.data("counter", counter);
}
}
function placeShips() {
$("td").click(placeBattleship);
}
$(document).ready(function(){
placeShips();
});
I use a div with id shipDisplay to store a data-attribute for count the clicks.
Look at the plunker: http://plnkr.co/edit/PEba15PSLv2LK6qjY7AD?p=preview
You should separate priorities in your logic and removeEventListener when counter hits 4 , hopefully this helps you :
//defined outside the function
var counter = 0;
playerCells.addEventListener("click" , placeShips );
Then
function placeShips() {
if(counter <= 4){
//Move ship
placeBattleship();
//add to counter
counter++
}else{
//Remove click event if counter reaches 4 .
playerCells.removeEventListener("click" , doSomethingElse)
}
}
You question needs a bit clarification. To my current understanding, you need to move the checking of count to placeBattleship.
What you are doing is binding click to same tds 4 times, not limiting the number of event triggering to 4 times.
// pseudo code
var count = 4; // this is global
var currentCount = 0;
initFunc() {
// bind click events ONCE
}
startPlacing() {
// accept user click and place ship
// set currentCount to zero
}
placeShip() {
// the callback of user `click`
// check for currentCount == count then move on (no more placement)
// increase currentCount by 1
// place ship
}
Note that after an event is triggered, the listener will not be removed. Until you removeEventListener() from it, it will always be listening.

Javascript word count price calculator

Everything works fine, except the problem with a pricing plan selection. What I want is that whenever user clicks on a specified price (even while the text is already present in textarea), it should immediately update the final Price. But it won't change at first click.
I should click twice on it instead. Any one got an idea what's wrong ?
So here how it looks like:
And here comes the javascript code:
function __textCalculatorCounter(){
var value = $('#calculateText').val();
var spanWords = $('#calculatedWordsTotal'),
spanChars = $('#calculatedCharsTotal'),
spanPrice = $('#calculatedPriceTotal');
if (value.length == 0) {
spanWords.html(0);
spanChars.html(0);
return;
}
var selectedPricing = $("input[name=calculatePrice]:checked").val();
var wordCount = value.trim().replace(/\s+/gi, ' ').split(' ').length;
var totalChars = value.length;
var totalPrice = (wordCount * parseFloat(Math.round(selectedPricing * 100) / 100));
spanWords.html(wordCount);
spanChars.html(totalChars);
spanPrice.html(totalPrice.toFixed(2));
}
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(__textCalculatorCounter);
textblock.keydown(__textCalculatorCounter);
textblock.keypress(__textCalculatorCounter);
textblock.keyup(__textCalculatorCounter);
textblock.blur(__textCalculatorCounter);
textblock.focus(__textCalculatorCounter);
$('label', '#pricesGroup').click(__textCalculatorCounter);
}
==== UPDATED ====
I don't know why, but it works fine in jsfiddle... it's exactly the same code extracted from html and javascript.
JSFIDDLE
So, since no one had an answer, I post mine, which solved the issue.
The problem is in Twitter's Bootstrap 3 radio button styles which is actually common issue when using along with javascript.
I've changed a click handler for radio buttons:
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(_textCalculatorTrigger);
textblock.keydown(_textCalculatorTrigger);
textblock.keypress(_textCalculatorTrigger);
textblock.keyup(_textCalculatorTrigger);
textblock.blur(_textCalculatorTrigger);
textblock.focus(_textCalculatorTrigger);
// Fixing bootstrap 3 radio buttons
$("#pricesGroup label").on('click', function(){
// Once clicked, mark current radio as checked
$('input:radio', this).prop("checked", true);
// Then call a function to calculate the price
_textCalculatorTrigger();
});
}
As it already commented, it assigns a property "checked" to radio button first once it's parent label tag is clicked, and then it calls a function to calculate the price.
Thanks to everyone

Disable holding the up and down buttons on a jQueryUI spinner

I'm using jQuery 1.7.1 and jQueryUI 1.9.1.
I have a spinner, and every time it changes, a text field will be created or removed to match the number on the spinner. Holding the button will cause the number to change very rapidly, causing a ton of fields to be created or removed.
Not a huge problem since it's client-side, but I just don't like it. So I want to disable the rapid spinning when the user holds the spinner buttons.
I came up with a solution using a function for incremental, which looks like this:
var incrementalFunction = function(numOfSpins) {
if (numOfSpins == 1) {
return 1;
}
return 0;
};
This worked great at first, but caused another issue. Next to each newly created text box, I made a 'remove' button that would remove the element and decrement the spinner. But when I call the stepDown method, for some reason, this calls my incremental function, with an increasing numOfSpins every time it was called. So it would only decrement once.
Anyone have a more straightforward solution to preventing the user from holding the increment/decrement buttons (or the up/down arrows on the keyboard)?
If you upgrade to jQuery UI 1.10, the problem will go away. See https://github.com/jquery/jquery-ui/commit/0d53fbfd0b7651652601b3b8577225ab753aab44 which causes stepUp() and stepdDown() to behave as you'd expect.
If you use the stop event, instead of targeting each increment, you can detect when a selection has been made. Then, you can compare that number to how many are currently there, and determine what to do - remove or add more. Try this:
var targetArea = $("#target_area");
targetArea.on("click", ".remover", function () {
$(this).closest("div").remove();
$("#input1").spinner("stepDown");
});
$("#input1").spinner({
stop: function (event, ui) {
var $this = $(this);
var num = $this.val();
var newTargets = targetArea.find("div");
var difference = num - newTargets.length;
if (difference < 0) {
newTargets.slice(difference).remove();
} else if (difference > 0) {
for (var i = 0; i < difference; i++) {
var newTarget = $("<div><input type='text' /><span class='remover' title='Remove'>×</span></div>");
targetArea.append(newTarget);
}
}
}
});
DEMO: http://jsfiddle.net/PJpUC/1/

Making "next" button work

I am creating a simple numeracy game where by there is a grid populated with numbers. The numbers are hidden and when the game is run the grid space is highlighted. A div on the side produces a sum to help the user get the correct answer. The user then clicks the corresponding numbers that animate into position and signal whether they are right or wrong.
I have but in a next button ('.minibutton'), so that if the user gets the answer wrong 3 times they have a chance to move to the next question. The button also has a .trigger('click') function so that when a word is completed correctly it moves on automatically and keeps the game flowing.
My problem is the button has stopped working and I am clueless as to why. Here is the ".minibutton" function...
$('.minibutton').click(function() {
var sum = $('#answerlist li[data-answer="' + answer + '"]').data('sum');
$(right).val('');
$(wrong).val('');
$('td').removeClass('spellanswer');
score.wrong = 0;
var r = rndanswer;
while (r == rndanswer) {
rndanswer = Math.floor(Math.random() * (listOfanswers.length));
}
when I added this statement the button stopped working
//for (var x = 0; x < listOfanswers.length; x++) {
//if (eval(sum.replace("=", "").replace("x", "*")) == listOfanswers[x].name) {
// rndanswer = x;
// }
//}
$('td[data-answer="' + listOfanswers[rndanswer].name + '"]').addClass('spellanswer');
$('td[data-answer=' + answer + ']').removeClass('answerglow').removeClass('answerglow4').removeClass('answerglow3').css('color', 'transparent');
var noExist = $('td[data-answer=' + listOfanswers[rndanswer].name + ']').hasClass('answerglow2');
if (noExist) {
$('.minibutton').prop('disabled', false);
} else {
$('.sumstyle').text(sum);
sum.hide();
}
}).trigger("click");
http://jsfiddle.net/ZAfVZ/28/
Running the jsFiddle gives this error:
Object 1 + 2 = has no method 'hide'
You're trying to hide a string, which is obviously wrong. It's causing the script to stop executing after that point. Remove/comment out sum.hide(), and the 'next' button appears after three wrong guesses.
I've edited the JSFiddle to define sum (a text string containing the sum that the player is trying to answer) and seumElem (the HTML element containing the sum) at the top of the function: http://jsfiddle.net/ZAfVZ/30/

Categories