Comparing Items within an Array in Javascript

Forgive me if this comes across as quite basic, but I am a complete beginner when it comes to coding (though I am determined to improve!)

I am working on creating a straightforward higher or lower card game using JavaScript where the user has to guess whether the next card will be higher or lower than the current card shown.

Currently, I have an array of 52 cards and I am utilizing Math.random to select a random card from the array.

My goal is to compare the values of two cards, but I am uncertain about the approach I should take. I suspect that indexOf might be involved, but I am not certain.

Thank you very much, and I apologize if this question is off-topic or has been asked before!

If it helps, here is my array:

function randomCard()
{
var cardArray = ["Club0.jpg","Club1.jpg","Club3.jpg","Club3.jpg","Club4.jpg","Club5.jpg","Club6.jpg","Club7.jpg","Club8.jpg","Club9.jpg","Club10.jpg","Club11.jpg","Club12.jpg","Diamond0.jpg","Diamond1.jpg","Diamond2.jpg","Diamond3.jpg","Diamond4.jpg","Diamond5.jpg","Diamond6.jpg","Diamond7.jpg","Diamond8.jpg","Diamond9.jpg","Diamond10.jpg","Diamond11.jpg","Diamond12.jpg","Heart0.jpg","Heart1.jpg","Heart2.jpg","Heart3.jpg","Heart4.jpg","Heart5.jpg","Heart6.jpg","Heart7.jpg","Heart8.jpg","Heart9.jpg","Heart10.jpg","Heart11.jpg","Heart12.jpg","Spade0.jpg","Spade1.jpg","Spade2.jpg","Spade3.jpg","Spade4.jpg","Spade5.jpg","Spade6.jpg","Spade7.jpg","Spade8.jpg","Spade9.jpg","Spade10.jpg","Spade11.jpg","Spade12.jpg"];

var pickCard = cardArray[Math.floor(Math.random() * cardArray.length)];
document.getElementById("card").src = pickCard;
}

Answer №1

In my opinion, the issue lies not in your understanding of arrays and looping, but in how you structure your question before diving in. Currently, you have an array setup as follows:

var cardArray = ["Club0.jpg","Club1.jpg","Club3.jpg"...];

This approach may be complicating things unnecessarily for you, especially if you plan on performing numerical comparisons on these array elements. Instead, consider framing your problem statement more clearly like this:

"I am dealing with 4 suits of cards, each containing values from 1 to 13 (with Jack as 11, Queen as 12, King as 13, and Aces treated as low)."

To better tackle this scope, let's begin by creating a deck comprising four suits with 14 cards each.

var deck = {
  heart: [1,2,3,4,5,6,7,8,9,10,11,12,13],
  club: [1,2,3,4,5,6,7,8,9,10,11,12,13],
  spade: [1,2,3,4,5,6,7,8,9,10,11,12,13],
  diamond: [1,2,3,4,5,6,7,8,9,10,11,12,13]
};

We will also need an array to store the suit names for easy access to the object.

var suits = ['heart','club','spade','diamond'];

Next, we introduce memo, which is crucial for avoiding duplicates when drawing cards. It serves as a record of selected cards that we can refer back to.

var memo = [];

The key function here is drawRandomCard. It randomly selects a suit from our array of suits and a number from the corresponding suit's array. If the chosen card is found in memo, a new card is drawn; otherwise, it is added to memo and returned as an array with suit and value being its elements.

function drawRandomCard() {
  var suit = suits[Math.floor(Math.random() * suits.length)];
  var number = deck[suit][Math.floor(Math.random() * 13)];
  if (memo[suit + number]) drawRandomCard();
  memo.push(suit + number)
  return [suit, number];
}

For instance:

var card1 = drawRandomCard();
var card2 = drawRandomCard();

You can then compare the values of these cards:

console.log(card1[1] > card2[1]); // true or false

If needed, you can match these values with relevant images using join to merge the card array elements together.

var img = new Image();
img.src = card1.join('') + '.jpg'; // e.g., diamond4.jpg

Or update the image source directly:

document.getElementById("card").src = card1.join('') + '.jpg';

Try it out yourself!

Answer №2

To create a card game with JavaScript, you can start by defining a Card object that has properties like suit and number. Here is an example implementation:

function Card(suit, number) {
    this.suit = suit;
    this.number = number;
}
Card.prototype.image = function() {
    return this.suit + this.number + '.jpg';
};
Card.compare = function(a, b) {
    /* Define how you want to compare cards. For example, based on the numbers */
    return a.number < b.number;
};
Card.prototype.compareTo = function(other) {
    return Card.compare(this, other);
};

var suits = ['Club', 'Diamond', 'Heart', 'Spade'],
    cardArray = [];
for (var i = 0; i < suits.length; ++i) {
    for (var j = 0; j <= 12; ++j) cardArray.push(new Card(suits[i], j));
}
var currentCard = cardArray[0]; /* Setting initial card */

function randomCard() {
    var pickCard = cardArray[Math.random() * cardArray.length | 0];
    if(currentCard.compareTo(pickCard)) {
        /* Implement logic when the picked card matches the current card */
    } else {
        /* Implement logic when the picked card doesn't match the current card */
    }
    document.getElementById("card").src = pickCard.image();
    currentCard = pickCard;
}

If you need to ensure that a card is only picked once, modify the picking mechanism as follows:

var pickCard = cardArray.splice(Math.random() * cardArray.length | 0, 1)[0];

This code snippet removes the picked card from the array so that it cannot be selected again.

Answer №3

If the card's image is Club10.jpg, you can extract the value using the following code:

card.match(/\d+/g)

This code will output:

10

Here is an example of how this code can be used:

var cardArray = ["Club0.jpg","Club1.jpg","Club3.jpg",...,"Spade12.jpg"];

var pickCard1 = cardArray[Math.floor(Math.random() * cardArray.length)];
var pickCard2 = cardArray[Math.floor(Math.random() * cardArray.length)];
if(parseInt(pickCard1.match(/\d+/g)) === parseInt(pickCard2.match(/\d+/g))){
    /*Do something here if the first equals the second card*/
} else if(parseInt(pickCard1.match(/\d+/g)) > parseInt(pickCard2.match(/\d+/g))){
    /*Do something here if the first card is greater than the second card*/
}else{
    /*Do something here if the first card is less than the second card*/
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...

How to transform an image into a base64 string using Vue

I am having trouble converting a local image to base64. The function reader.readAsDataURL is not working for me. Instead of the image data, I always get 'undefined' assigned to the rawImg variable. The file variable contains metadata from the upl ...

Deciphering a JSON Array in JavaScript to extract specific components

I have a brief snippet for a JSON array and a JavaScript function that currently returns a single argument: <!DOCTYPE html> <html> <body> <h2>JSON Array Test</h2> <p id="outputid"></p> <script> var arrayi ...

Unable to load JavaScript file twice dynamically in Internet Explorer

I recently created this page where users can click on rows in a table to load data via an ajax request and dynamically generate a graph. While this functionality works smoothly in Chrome and Firefox, I'm experiencing issues with Internet Explorer 8. S ...

Developing an observer for the onChange event in a React component

I am currently working on the following code snippet: handleChange: function(e) { this.setState({[e.target.name]: e.target.value}); }, ................ ...............<input type="text".... onChange={this ...

Using React to Identify the Chosen Option on a Custom Toggle Button

I have successfully implemented a toggle switch using HTML and CSS in my React app. I am now looking for a way to detect the selected option whenever it changes. For instance, if OR is chosen, I would like it to be saved in the selectedOption state, and if ...

Vuejs - Display multiple dates within one component

I have developed various components (such as tables, selects, etc) that all rely on the same methods to access API information. The main objective is to be able to use these components across different pages of the application in a way that allows for fle ...

Stop the page from refreshing following the submission of a form in node.js (without using ajax)

Hey there, I've got a form set up to send fields as well as a file to a node.js server. The server then parses the data using Formidable. Everything is functioning correctly, but once the form is submitted, it loads a page with a response. I'm w ...

``KnockoutJS offers a variety of options for handling options, including optionsText

I am curious about the functionality of data-bind, options, optionsText, and optionsValue in this code snippet: <div class="header dropdown"> <select data-bind=" value: locale.selected_locale, options: [{ value: 'en-CA&ap ...

Slide your finger upwards to shut down the mobile navbar in bootstrap

Hey there, I'm currently developing a website using Bootstrap framework v3.3.4. I have a mobile navbar that opens when I click a toggle button, but I would like it to slide up to close the navigation instead. Here is an image showing the issue Do y ...

Instructions for using Selenium to access the "stats for nerds" option on a YouTube video by right-clicking

I am currently working on a program that has the ability to block YouTube ads and keep track of the blocked Ad Video IDs. To achieve this, our selenium program needs to simulate a right click on the video to open the video menu and then select "stats for ...

Testing Vue watcher that observes a computed property in VueX: Tips and Tricks

Consider the code snippet below: import { mapState } from 'vuex'; import externalDependency from '...'; export default { name: 'Foo', computed: { ...mapState(['bar']) }, watch: { bar () { exter ...

Encountered an issue while attempting to connect MongoDB to Node.js

``const timeoutError = new error_1.MongoServerSelectionError(Server selection timed out after ${serverSelectionTimeoutMS} ms, this.description); .MongoServerSelectionError: connect ECONNREFUSED ::1:27017 const {MongoClient}=require('mongodb'); c ...

Exploring the world of pagination using AJAX (jQuery) - managing large datasets

Would it be wise to implement ajax pagination for large databases? I have a fast jQuery live search filter, but I'm concerned that I won't be able to use it alongside PHP pagination because the page content is typically generated from the databa ...

Using vanilla JavaScript to close a modal in Bootstrap 5 is a great way

Hello, I recently came across a tutorial which discusses how to show a modal in Bootstrap 5 using JavaScript. The tutorial can be found at the following link: https://getbootstrap.com/docs/5.0/components/modal/#via-javascript. In the tutorial, they demonst ...

Validating date and time picker pairs using JavaScript

I am looking to implement start and end date validation using datetimepicker. My current code is not functioning as expected. I need the end date to be greater than or equal to the start date, and vice versa. If anyone has a solution for this issue, plea ...

Encountering a problem with the state error while trying to modify an input field during onChange event

Whenever I pass state down from a parent component, the setState function keeps triggering an error that says setEmail is not a valid function on change event. Is there a simple solution to fix this issue? Every time I type a string into the email input f ...

Expanding the Number of Arguments Sent to a Callback Function

I have a scenario where I am using a method that sends a POST request and then triggers a specific callback function to manage the response: myService.verify(id, verificationCallback); function verificationCallback(err, response) { ... } My query is two ...

The occurrence of an unhandled promise rejection is triggered by the return statement within the fs

In my code, I have a simple fs.readFile function that reads data from a JSON file, retrieves one of its properties (an array), and then checks if that array contains every single element from an array generated by the user. Here is the snippet of code: co ...

Transitions in Vue do not function properly when used in conjunction with a router-view containing a

Recently, I developed a component where I implemented router-view exclusively to facilitate route-based changes. It's worth mentioning that this is the second instance of router-view, with the first one residing in the App.vue component. Interestingly ...