I'm a novice programmer and I've been using JavaScript to make a simple game of Bulls and Cows that updates with the amount of Bulls and Cows you have in a paragraph with each guess. I've been using "'1234'" in place of "arr.join("")" to test it out, and it's almost there, but it's adding one bull by default and not taking into account the first digit of the number being submitted. When I submit the correct number, everything comes up fine. I just wanted to know why I don't seem to be getting the proper amount of bulls and cows.
// This is our click counter that tells you how many times you've guessed in the game.
var clicks = 0;
$("#submit").click(function() {
clicks++;
$("#guesses").html(clicks);
});
// Generates a non-repeating, random number and stores it in a global variable known as "secret".
$("#start").click(function() {
var arr = [];
while (arr.length < 4) {
var randomnumber = Math.ceil(Math.random() * 9);
var found = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i] === randomnumber) {
found = true;
break;
}
}
if (!found) arr[arr.length] = randomnumber;
}
secret = "1234";
});
// When you click the "Hide Rules" button, it hides the Rules form and shows the "Show Rules" button.
$("#hide").click(function() {
$("#rulesform").hide();
$("#show").show();
$("#hide").hide();
});
// When you click the "Show Rules" button, it shows the rules form and the "Hide Rules" button and hides the "Show Rules" button.
$("#show").click(function() {
$("#rulesform").show();
$("#show").hide();
$("#hide").show();
});
// When you click "Start playing!", it hides the button, shows the game, sets guesses equal to 0, and generates the number for the game.
$("#start").click(function() {
$("#game").show();
$("#start").hide();
$("#submit").show();
$("#guesses").html("0");
});
// When you hit the "Stop playing." button, it clears the results of the game and guess input box, in addition to hiding the game functions and showing the "Start playing!" button.
$("#stop").click(function() {
$("#game").hide();
$("#start").show();
$("#results").html("");
$("#guess").val("");
clicks = 0;
});
function game() {
// Stores your guess in a variable
var guess = $("#guess").val();
// Makes sure the number is 4 digits
if (guess.length != 4) {
alert("This number is too long or short to be valid.");
}
// Makes sure the numbers are non-repeating if they're 4 digits.
else if (guess.charAt(1) === guess.charAt(2) || guess.charAt(1) === guess.charAt(3) || guess.charAt(1) === guess.charAt(4) || guess.charAt(2) === guess.charAt(3) || guess.charAt(2) === guess.charAt(4) || guess.charAt(3) === guess.charAt(4)) {
alert("This game doesn't have any repeating digits.");
}
// This is the actual game.
else {
// These two variables will be updated with each guess the user inputs.
var bulls = 0;
var cows = 0;
// This is where JavaScript checks the bulls and cows and adds them up accordingly.
if (guess !== secret) {
if (guess.charAt(1) === secret.charAt(1)) {
bulls += 1;
} else if (guess.charAt(1) === secret.charAt(2) || guess.charAt(1) === secret.charAt(3) || guess.charAt(1) === secret.charAt(4)) {
cows += 1;
}
if (guess.charAt(2) === secret.charAt(2)) {
bulls += 1;
} else if (guess.charAt(2) === secret.charAt(1) || guess.charAt(2) === secret.charAt(3) || guess.charAt(2) === secret.charAt(4)) {
cows += 1;
}
if (guess.charAt(3) === secret.charAt(3)) {
bulls += 1;
} else if (guess.charAt(3) === secret.charAt(1) || guess.charAt(3) === secret.charAt(2) || guess.charAt(3) === secret.charAt(4)) {
cows += 1;
}
if (guess.charAt(4) === secret.charAt(4)) {
bulls += 1;
} else if (guess.charAt(4) === secret.charAt(1) || guess.charAt(4) === secret.charAt(2) || guess.charAt(4) === secret.charAt(3)) {
cows += 1;
}
$("#results").html("Bulls: " + bulls + " & Cows: " + cows + "");
} else if (guess === secret) {
$("#results").html("<strong>Congrats, you won! <a href='images/cookie.gif'>Here's a picture</a> of a cookie.</strong>");
$("#submit").hide();
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<h1>Want to play a game?</h1>
<div id="rules">
<form id="rulesform">
<h2>Rules:</h2>
<p>The computer will generate a random 4-digit number without any of them repeating. You will do your best to guess the number in the input field provided. If a digit you entered is not used, you will not get any bulls or cows. If it's in the correct
spot, then you'll get 1 bull. If it's in the wrong spot, it will be a cow. The game ends when you guess the number. The amount of guesses it takes for you to figure it out will be provided.</p>
</form>
<input type="button" id="hide" value="Hide Rules">
<input type="button" id="show" value="Show Rules">
<br>
<input type="button" id="start" value="Start playing!">
</div>
<!--closes rules-->
<div id="game">
<input type="number" id="guess" placeholder="Your Guess">
<input type="button" id="submit" value="Submit your guess." onclick="game()">
<br>
<p id="guesstext">Guesses:</p>
<p id="guesses"></p>
<p id="results"></p>
<input type="button" id="stop" value="Stop playing.">
</div>
<!--closes game-->
</div>
<!--closes wrapper-->
The first character in a string is charAt(0) in that string, not charAt(1). Reduce all your charAt references by one and see if that works.
Here's what it should look like:
// This is our click counter that tells you how many times you've guessed in the game.
var clicks = 0;
$("#submit").click(function() {
clicks++;
$("#guesses").html(clicks);
});
// Generates a non-repeating, random number and stores it in a global variable known as "secret".
$("#start").click(function() {
var arr = [];
while (arr.length < 4) {
var randomnumber = Math.ceil(Math.random() * 9);
var found = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i] === randomnumber) {
found = true;
break;
}
}
if (!found) arr[arr.length] = randomnumber;
}
window.secret = "1234";
});
// When you click the "Hide Rules" button, it hides the Rules form and shows the "Show Rules" button.
$("#hide").click(function() {
$("#rulesform").hide();
$("#show").show();
$("#hide").hide();
});
// When you click the "Show Rules" button, it shows the rules form and the "Hide Rules" button and hides the "Show Rules" button.
$("#show").click(function() {
$("#rulesform").show();
$("#show").hide();
$("#hide").show();
});
// When you click "Start playing!", it hides the button, shows the game, sets guesses equal to 0, and generates the number for the game.
$("#start").click(function() {
$("#game").show();
$("#start").hide();
$("#submit").show();
$("#guesses").html("0");
});
// When you hit the "Stop playing." button, it clears the results of the game and guess input box, in addition to hiding the game functions and showing the "Start playing!" button.
$("#stop").click(function() {
$("#game").hide();
$("#start").show();
$("#results").html("");
$("#guess").val("");
clicks = 0;
});
window.game = function() {
// Stores your guess in a variable
var guess = $("#guess").val();
// Makes sure the number is 4 digits
if (guess.length != 4) {
alert("This number is too long or short to be valid.");
}
// Makes sure the numbers are non-repeating if they're 4 digits.
else if (guess.charAt(0) === guess.charAt(1) || guess.charAt(0) === guess.charAt(2) || guess.charAt(0) === guess.charAt(3) || guess.charAt(1) === guess.charAt(2) || guess.charAt(1) === guess.charAt(3) || guess.charAt(2) === guess.charAt(3)) {
alert("This game doesn't have any repeating digits.");
}
// This is the actual game.
else {
// These two variables will be updated with each guess the user inputs.
var bulls = 0;
var cows = 0;
// This is where JavaScript checks the bulls and cows and adds them up accordingly.
if (guess !== secret) {
if (guess.charAt(0) === secret.charAt(0)) {
bulls += 1;
} else if (guess.charAt(0) === secret.charAt(1) || guess.charAt(0) === secret.charAt(2) || guess.charAt(0) === secret.charAt(3)) {
cows += 1;
}
if (guess.charAt(1) === secret.charAt(1)) {
bulls += 1;
} else if (guess.charAt(1) === secret.charAt(0) || guess.charAt(1) === secret.charAt(2) || guess.charAt(1) === secret.charAt(3)) {
cows += 1;
}
if (guess.charAt(2) === secret.charAt(2)) {
bulls += 1;
} else if (guess.charAt(2) === secret.charAt(0) || guess.charAt(2) === secret.charAt(1) || guess.charAt(2) === secret.charAt(3)) {
cows += 1;
}
if (guess.charAt(3) === secret.charAt(3)) {
bulls += 1;
} else if (guess.charAt(3) === secret.charAt(0) || guess.charAt(3) === secret.charAt(1) || guess.charAt(3) === secret.charAt(2)) {
cows += 1;
}
$("#results").html("Bulls: " + bulls + " & Cows: " + cows + "");
} else if (guess === secret) {
$("#results").html("<strong>Congrats, you won! <a href='images/cookie.gif'>Here's a picture</a> of a cookie.</strong>");
$("#submit").hide();
}
}
}
I know it is not really on the topic, but I had to do the same task and found your code a really useful example. I kinda edited it and suggest you, something, that is far better option in my opinion(It is not necessary to be the better option, just my point of view)
for (var i = 0; i < length; i++) {
if(String(guess).charAt(i) == String(number).charAt(i)){
bulls++;
}else{
for (var j = 0; j < length; j++) {
if ((String(guess).charAt(i) == String(number).charAt(j)) && (i !== j)) {
cows++;
};
};
}
};
Where guess is your guess and number is the generated number.
The above code might be put instead of
if (guess.charAt(0) === secret.charAt(0)) {
bulls += 1;
} else if (guess.charAt(0) === secret.charAt(1) || guess.charAt(0) === secret.charAt(2) || guess.charAt(0) === secret.charAt(3)) {
cows += 1;
}
if (guess.charAt(1) === secret.charAt(1)) {
bulls += 1;
} else if (guess.charAt(1) === secret.charAt(0) || guess.charAt(1) === secret.charAt(2) || guess.charAt(1) === secret.charAt(3)) {
cows += 1;
}
if (guess.charAt(2) === secret.charAt(2)) {
bulls += 1;
} else if (guess.charAt(2) === secret.charAt(0) || guess.charAt(2) === secret.charAt(1) || guess.charAt(2) === secret.charAt(3)) {
cows += 1;
}
if (guess.charAt(3) === secret.charAt(3)) {
bulls += 1;
} else if (guess.charAt(3) === secret.charAt(0) || guess.charAt(3) === secret.charAt(1) || guess.charAt(3) === secret.charAt(2)) {
cows += 1;
}
I hope, I helped.
Related
Hello I have a simple script:
var play = true;
var correct = false;
var number = 0;
var guess = 0;
while (play) {
// random number between 1 and 10.
number = Math.floor(Math.random() * 10 - 1);
if (number == 0) number = 1;
while (!correct) {
guess = window.prompt("What is the number?");
if (guess < number) {
alert("Guess higher ;)");
} else if (guess > number) {
alert("Guess lower ;)");
} else if (guess == number) {
correct = true;
alert("You got it!");
}
}
if (window.prompt("Do you want another game?", "yes") != "yes") {
play = false;
}
}
When I get the number right and prompted to "Do you want another game?" and enter "yes", the program redisplays and stuck at "Do you want another game?".
You need to reset the state of correct on every play loop:
let play = true;
while (play) {
let number = Math.floor(Math.random() * 10 + 1);
let guess = 0;
let correct = false;
while (!correct) {
guess = window.prompt("What is the number?");
if (guess < number) {
alert("Guess higher ;)");
} else if (guess > number) {
alert("Guess lower ;)");
} else if (guess == number) {
correct = true;
alert("You got it!");
}
}
if (window.prompt("Do you want another game?", "yes") != "yes") {
play = false;
}
}
Forgive me if this question has already been asked; I've searched the site for this question and haven't stumbled upon it yet.
I'm creating a word-guessing game, and I'm having trouble with the last of my functions. The function arguments are a user-inputted character ("character"), a randomly generated word ("word"), and a scrambled version of that word ("scrmbldword"). As an example, the word could be "chilly", and the scrambled version would have a corresponding number of underscores "______". The role of this function is to take the user input, scan the "word" for that letter, and if it finds that letter in the word, to replace an underscore of the "scrmbldword" with the corresponding letter.
For instance, the word would be "chilly", and the user input would be the character "l"; I need the scrmbldword to become "___ll_".
function unscrambledWord(character, scrmbldword, word) {
for (k = 0; k < word.length; k++) {
if (character == word[k]) {
var tempLetter = word[k];
console.log(tempLetter)
tempWord = scrmbldword.replace(scrmbldword[k], character);
console.log(tempWord);
}
}
}
Thank you for all the answers, but when I copy and paste them into my code, they are not working. I'm trying to understand the code behind your various answers so I can edit them myself, but for the most part I don't get it. Perhaps it would help you all if I gave more context, so here's my file entirely...
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Word Guess Game</title>
</head>
<body>
<div>
<p id="directions-text">Type any letter to start playing</p>
<p id="userchoice-text"></p>
<p id="userguesslist-text"></p>
<p id="unscrambledword-text"></p>
</div>
<script type="text/javascript">
var userGuesses = [];
var unknownWord = "";
function wordGenerator() {
var computerChoices = ["lowly", "start", "chilly", "bun", "bead", "friend", "return", "view", "cloth", "frogs", "celery", "basin", "stand", "special", "broad", "abaft", "plead", "quartz", "mark", "tempt", "shop", "stone", "scorch", "taboo", "hoax", "spiffy", "insure"];
var cpuWord = computerChoices[Math.floor(Math.random() * computerChoices.length)];
console.log(cpuWord);
return cpuWord;
};
var computerWord = wordGenerator();
function scrambledWord(string) {
var knownWord = ""
if (string.length == 3) {
knownWord = "___"
} else if (string.length == 4) {
knownWord = "____"
} else if (string.length == 5) {
knownWord = "_____"
} else if (string.length == 6) {
knownWord = "______"
} else if (string.length == 7) {
knownWord = "_______"
}
return knownWord;
}
var unknownWord = scrambledWord(computerWord);
var directionsText = document.getElementById("directions-text");
var userChoiceText = document.getElementById("userchoice-text");
var userGuessList = document.getElementById("userguesslist-text");
var unscrambledWordText = document.getElementById("unscrambledword-text");
document.onkeyup = function (event) {
var userGuess = event.key;
if ((userGuess === "a") || (userGuess === "b") || (userGuess === "c") || (userGuess === "d") || (userGuess === "e") || (userGuess === "f") || (userGuess === "g") || (userGuess === "h") || (userGuess === "i") || (userGuess === "j") || (userGuess === "k") || (userGuess === "l") || (userGuess === "m") || (userGuess === "n") || (userGuess === "o") || (userGuess === "p") || (userGuess === "q") || (userGuess === "r") || (userGuess === "s") || (userGuess === "t") || (userGuess === "u") || (userGuess === "v") || (userGuess === "w") || (userGuess === "x") || (userGuess === "y") || (userGuess === "z")) {
userGuesses.push(userGuess);
directionsText.textContent = "";
userChoiceText.textContent = "You chose: " + userGuess;
userGuessList.textContent = "You have guessed: " + userGuesses;
unscrambledWordText.textContent = "The word is: " + unknownWord;
wordChecker(userGuess)
} else {
alert("You did not enter an alphabetical character.")
}
};
function wordChecker(input) {
if (computerWord.includes(input)) {
alert("You guessed a correct character")
unscrambledWord(input, unknownWord, computerWord)
} else {
alert("You guessed an incorrect character")
}
}
function unscrambledWord(character, scrmbldword, word) {
for (k = 0; k < word.length; k++) {
if (character == word[k]) {
var tempLetter = word[k];
console.log(tempLetter)
tempWord = scrmbldword.replace(scrmbldword[k], character);
console.log(tempWord);
}
}
}
As per my understanding, you can try this
function unscrambledWord(character, word, scrmbldword = "_".repeat(word.length)) {
return [...scrmbldword].map((d, i) => d == '_' && word[i] == character ? character : d).join('')
}
console.log(unscrambledWord('l', 'chilly'))
I think Nitish Narang is really a nice answer, but if you really want to use your existing function, you can try to define and use a replaceAt function, like this :
function unscrambledWord(character, scrmbldword, word) {
for (k = 0; k < word.length; k++) {
if (character == word[k]) {
var tempLetter = word[k];
console.log(tempLetter)
tempWord = scrmbldword.replaceAt(k, character);
console.log(tempWord);
}
}
}
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
unscrambledWord("l", "______", "chilly")
You can use the replace method with a RegExp that has the global flag, which tells us to replace all instances of that RegExp.
RegExp(`[^${character}]`, "g")
We're making a regex that matches any character except the provided character.
function unscrambledWord(character, word) {
const notCharacter = RegExp(`[^${character}]`, "g")
return word.replace(notCharacter, "_")
}
I'm making a pomodoro clock with a break timer and a session timer. I'm using a single numpad to input the data into each clock by trying to nest the o'clock event to set each clock. To make it happen you click the display for the clock and then start inputting the buttons. There is 0-9 a delete button and an enter button. I haven't been able to get it to even display anything for either function. So I'm starting to wonder if what I'm trying to do would even work? Just looking for whether you can nest on click events and if so what I'm doing wrong. Or another method for what I'm looking to do. Made a fiddle to view it minimize the js and css windows. https://jsfiddle.net/zackluckyf/jhe98j05/1/
$(".session-time-clock").click(function(){
// changes the color to make it flash, add a duration and then change it back
$(".num-button").css("background-color", "#BCC6CC");
function myFunction() {
myVar = setTimeout(changeBackground, 500);
}
function changeBackground() {
$(".num-button").css("background-color", "#575e62");
}
myFunction();
sessionTimeClock = "00:00";
counter = 4;
/*
Will this work?
*/
$("button").click(function(){
// gets button text label
var input = $(this).text();
// if, else if chain for calculator functions
if(input !== "Start" && input !== "Pause" && input !== "Reset" && input !== "X" && input !== "Enter" && counter > -1)
{
if(counter === 4)
{
sessionTimeClock = sessionTimeClock.slice(0,counter-1) + input;
}
if(counter === 3)
{
sessionTimeClock = "00:" + input + sessionTimeClock.slice(4);
}
if(counter === 1)
{
sessionTimeClock = "0" + input + sessionTimeClock.slice(2);
}
if(counter === 0)
{
sessionTimeClock = input + sessionTimeClock.slice(1);
}
counter--;
if(counter === 2)
{
counter--;
}
}
else if(input === "X")
{
if(counter === 3)
{
sessionTimeClock = "00:0" + sessionTimeClock.slice(4);
}
else if(counter === 1)
{
sessionTimeClock = "00:" + sessionTimeClock.slice(3);
}
else if(counter === 0)
{
sessionTimeClock = "0" + sessionTimeClock.slice(1);
}
}
else if(input === "Enter")
{
return;
}
$(".session-time-clock").text("hello");
});
});
$(".break-time-clock").click(function(){
$(".num-button").css("background-color", "#BCC6CC");
function myFunction() {
myVar = setTimeout(changeBackground, 500);
}
function changeBackground() {
$(".num-button").css("background-color", "#575e62");
}
myFunction();
breakTimeClock = "00:00";
counter = 4;
$("button").click(function(){
// gets button text label
var input = $(this).text();
// if, else if chain for calculator functions
if(input !== "Start" && input !== "Pause" && input !== "Reset" && input !== "X" && input !== "Enter" && counter > -1)
{
if(counter === 4)
{
breakTimeClock = breakTimeClock.slice(0,counter-1) + input;
}
if(counter === 3)
{
breakTimeClock = "00:" + input + breakTimeClock.slice(4);
}
if(counter === 1)
{
breakTimeClock = "0" + input + breakTimeClock.slice(2);
}
if(counter === 0)
{
breakTimeClock = input + breakTimeClock.slice(1);
}
counter--;
if(counter === 2)
{
counter--;
}
}
else if(input === "X")
{
if(counter === 3)
{
breakTimeClock = "00:0" + breakTimeClock.slice(4);
}
else if(counter === 1)
{
breakTimeClock = "00:" + breakTimeClock.slice(3);
}
else if(counter === 0)
{
breakTimeClock = "0" + breakTimeClock.slice(1);
}
}
else if(input === "Enter")
{
return;
}
$(".break-time-clock").text(breakTimeClock);
});
});
The supplied code is not identical to the jsfiddle. I will relate to the jsfiddle:
You have this code:
$("button").click(function(){
if(input === "Start")
{
// start clock code
}
else if(input === "Pause")
{
// pause clock code
}
else if(input === "Reset")
{
sessionTimeClock = "00:00";
breakTimeClock = "00:00";
}
return true;
});
This is the first time you assign a click handler to "button" and therefore it gets called first.
The "input" variable is not defined, and therefore the other handlers are not called. (You can see an error in the Dev Tools console).
Task is simple write numbers from 1 to 99 and replace all numbers where: num (mod 3) =0 with each num (mod 5) =0 -> mat, num ( mod 3=0 && mod 5=0 ) with each mat, all others remains the same. That is easy but the formatting is horrible so I want to do this: insert a space between every number and place every "special" word (dividable by 3,5 or both) on a separate line. I know I have to use string.prototype.format but how exactly? here is my current code:
<html>
<body>
<p>Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = [];
var res = " ";
for (i=1; i<100; i++){
if (i%3 == 0 && i%5 == 0){
text[i]= "SachMat ";
}
else if (i%3 == 0){
text[i]= 'sach ';
}
else if (i%5 == 0){
text[i]= 'mat ';
}
else {
text[i]= i;
}
var res = res.concat(text[i]);
}
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Try this
function myFunction() {
var text = [];
var res = " ";
for (i=1; i<100; i++){
if (i%3 == 0 && i%5 == 0){
text[i]= "<br/>SachMat<br/>";
} else if (i%3 == 0) {
text[i]= 'sach ';
} else if (i%5 == 0){
text[i]= 'mat ';
} else {
text[i]= i;
}
res = res.concat(' ' + text[i]);
}
document.getElementById("demo").innerHTML = res;
}
I am new to JavaScript, I have been learning and practicing for about 3 months and hope I can get some help on this topic. I'm making a poker game and what I'm trying to do is determine whether i have a pair, two pairs, three of a kind, four of a kind or a full house.
For instance, in [1, 2, 3, 4, 4, 4, 3], 1 appears one time, 4 appears three times, and so on.
How could I possibly ask my computer to tell me how many times an array element appears?
Solved, here's the final product.
<script type="text/javascript">
var deck = [];
var cards = [];
var convertedcards = [];
var kinds = [];
var phase = 1;
var displaycard = [];
var options = 0;
var endgame = false;
// Fill Deck //
for(i = 0; i < 52; i++){
deck[deck.length] = i;
}
// Distribute Cards //
for(i = 0; i < 7; i++){
cards[cards.length] = Number(Math.floor(Math.random() * 52));
if(deck.indexOf(cards[cards.length - 1]) === -1){
cards.splice(cards.length - 1, cards.length);
i = i - 1;
}else{
deck[cards[cards.length - 1]] = "|";
}
}
// Convert Cards //
for(i = 0; i < 7; i++){
convertedcards[i] = (cards[i] % 13) + 1;
}
// Cards Kind //
for(i = 0; i < 7; i++){
if(cards[i] < 13){
kinds[kinds.length] = "H";
}else if(cards[i] < 27 && cards[i] > 12){
kinds[kinds.length] = "C";
}else if(cards[i] < 40 && cards[i] > 26){
kinds[kinds.length] = "D";
}else{
kinds[kinds.length] = "S";
}
}
// Card Display //
for(i = 0; i < 7; i++){
displaycard[i] = convertedcards[i] + kinds[i];
}
// Hand Strenght //
var handstrenght = function(){
var usedcards = [];
var count = 0;
var pairs = [];
for(i = 0, a = 1; i < 7; a++){
if(convertedcards[i] === convertedcards[a] && a < 7 && usedcards[i] != "|"){
pairs[pairs.length] = convertedcards[i];
usedcards[a] = "|";
}else if(a > 6){
i = i + 1;
a = i;
}
}
// Flush >.< //
var flush = false;
for(i = 0, a = 1; i < 7; i++, a++){
if(kinds[i] === kinds[a] && kinds[i] != undefined){
count++;
if(a >= 6 && count >= 5){
flush = true;
count = 0;
}else if(a >= 6 && count < 5){
count = 0;
}
}
}
// Straight >.< //
var straight = false;
convertedcards = convertedcards.sort(function(a,b){return a-b});
if(convertedcards[2] > 10 && convertedcards[3] > 10 && convertedcards[4] > 10){
convertedcards[0] = 14;
convertedcards = convertedcards.sort(function(a,b){return a-b});
}
alert(convertedcards);
if(convertedcards[0] + 1 === convertedcards[1] && convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4]){
straight = true;
}else if(convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5]){
straight = true;
}else if(convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5] && convertedcards[5] + 1 === convertedcards[6]){
straight = true;
}
// Royal Flush, Straight Flush, Flush, Straight >.< //
var royalflush = false;
if(straight === true && flush === true && convertedcards[6] === 14){
royalflush = true;
alert("You have a Royal Flush");
}
else if(straight === true && flush === true && royalflush === false){
alert("You have a straight flush");
}else if(straight === true && flush === false){
alert("You have a straight");
}else if(straight === false && flush === true){
alert("You have a flush");
}
// Full House >.< //
if(pairs[0] === pairs[1] && pairs[1] != pairs[2] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}else if(pairs[0] != pairs[1] && pairs[1] === pairs[2] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}else if(pairs[0] != pairs[1] && pairs[1] != pairs[2] && pairs[2] === pairs[3] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}
// Four of a kind >.< //
else if(pairs[0] === pairs[1] && pairs[1] === pairs[2] && pairs.length > 0){
alert("You have four of a kind");
}
// Three of a kind >.< //
else if(pairs[0] === pairs[1] && flush === false && straight === false && pairs.length === 2){
alert("You have three of a kind");
}
// Double Pair >.< //
else if(pairs[0] != pairs[1] && flush === false && straight === false && pairs.length > 1){
alert("You have a double pair");
}
// Pair >.< //
else if(pairs.length === 1 && flush === false && straight === false && pairs.length === 1 ){
alert("You have a pair");
}
alert(pairs);
};
while(endgame === false){
if(phase === 1){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 2){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 3){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 4){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + " " + displaycard[6] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}
switch(options){
case 1:
if(phase === 5){
handstrenght();
endgame = true;
}else{
phase++;
}
break;
case 2:
endgame = true;
break;
default:
endgame = true;
break;
}
}
</script>
Keep a variable for the total count
Loop through the array and check if current value is the same as the one you're looking for, if it is, increment the total count by one
After the loop, total count contains the number of times the number you were looking for is in the array
Show your code and we can help you figure out where it went wrong
Here's a simple implementation (since you don't have the code that didn't work)
var list = [2, 1, 4, 2, 1, 1, 4, 5];
function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}
countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3
countInArray could also have been implemented as
function countInArray(array, what) {
return array.filter(item => item == what).length;
}
More elegant, but maybe not as performant since it has to create a new array.
With filter and length it seems simple but there is a big waste of memory.
If you want to use nice array methods, the appropriate one is reduce:
function countInArray(array, value) {
return array.reduce((n, x) => n + (x === value), 0);
}
console.log(countInArray([1,2,3,4,4,4,3], 4)); // 3
Well..
var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
if (typeof acc[curr] == 'undefined') {
acc[curr] = 1;
} else {
acc[curr] += 1;
}
return acc;
}, {});
// a == {2: 5, 4: 1, 5: 3, 9: 1}
from here:
Counting the occurrences of JavaScript array elements
Or you can find other solutions there, too..
When targeting recent enough browsers, you can use filter(). (The MDN page also provides a polyfill for the function.)
var items = [1, 2, 3, 4, 4, 4, 3];
var fours = items.filter(function(it) {return it === 4;});
var result = fours.length;
You can even abstract over the filtering function as this:
// Creates a new function that returns true if the parameter passed to it is
// equal to `x`
function equal_func(x) {
return function(it) {
return it === x;
}
}
//...
var result = items.filter(equal_func(4)).length;
Here's an implementation of Juan's answer:
function count( list, x ) {
for ( var l = list.length, c = 0; l--; ) {
if ( list[ l ] === x ) {
c++;
}
}
return c;
}
Even shorter:
function count( list, x ) {
for ( var l = list.length, c = 0; l--; list[ l ] === x && c++ );
return c;
}
Here's an implementation that uses the Array Object Prototype and has an extra level of functionality that returns the length if no search-item is supplied:
Array.prototype.count = function(lit = false) {
if ( !lit ) { return this.length}
else {
var count = 0;
for ( var i=0; i < this.length; i++ ) {
if ( lit == this[i] ){
count++
}
}
return count;
}
}
This has an extremely simple useage, and is as follows:
var count = [1,2,3,4,4].count(4); // Returns 2
var count = [1,2,3,4,4].count(); // Without first parameter returns 5