"Incorporating a variety of images in a random order with

Wanting to create a fun game on my website using JavaScript, where hotdogs are added to a bowl in random positions forming a pyramid-shaped pile that eventually covers the entire page.

However, I'm facing some challenges with the implementation. The goal is to initially place 10 hotdogs in the bowl, then spill 50 more onto the 'game board,' and finally scatter them randomly across the webpage. At this stage, I'm particularly interested in figuring out how to incorporate image elements with randomized orientations using just HTML, CSS, and JavaScript. See the code snippet below:

HTML:
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Game</title>
        <link href="https://fonts.googleapis.com/css?family=Bungee|IBM+Plex+Sans:100,200,300i,500|Lato:300,300i,400,700&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="./resources/game.css">
    </head>

    <body>

        <!-- Title Section-->
        <h1>FEED THE PUP</h1>
        <p>Tap to give the dog some food, go for a high score or something!</p>

        <!-- Game Section-->
        <div id = 'gameSpace'>
            <img id = 'dog' src="./resources/images/png/dog.png" alt="">
            <img id = 'dogBowl' src="./resources/images/png/dogBowl.png" alt="">
            <img class = 'hotdog' src="./resources/images/png/hot-dog.png" alt="">
        </div>

        <div class = 'scoreBoard'>
            <p>SCORE:</p>
            <p id = 'gameScore'>0</p>
        </div>

        <div class = 'thanks'>
            <p class = 'attribute'>Dog icon made by <a href="https://www.flaticon.com/authors/photo3idea-studio" title="photo3idea_studio">photo3idea_studio</a> from <a href="https://www.flaticon.com/" title="Flaticon"> www.flaticon.com</a></p>
            <p class = 'attribute'>Dog bowl icon made by <a href="https://www.flaticon.com/authors/good-ware" title="Good Ware">Good Ware</a> from <a href="https://www.flaticon.com/" title="Flaticon"> www.flaticon.com</a></p>
            <p class = 'attribute'>Hotdog icon made by <a href="https://www.flaticon.com/authors/freepik" title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" title="Flaticon"> www.flaticon.com</a></p>
        </div>

        <script  src="game.js"></script>
    </body>

</html>
CSS:
body {
    background-color: #C5F4E0;
    user-select: none;
    -moz-user-select: none;
    -webkit-user-drag: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    height: fit-content;
}

h1 {
    color: white;
    text-align: center;
    font-family: 'Bungee';
    font-size: 4rem;
    text-shadow: #232835 0px 3px 4px;
    margin-bottom: 1rem;
}

p {
    text-align: center;
    color: #232835;
    font-family: 'IBM Plex Sans';
    font-weight: 200;
    font-size: 1.5rem;
    margin-top: 0rem;
}

#gameSpace {
    display: flex;
    flex-direction: row;
    border: #232835 2px ridge;
    height: 25rem;
    width: 25rem;
    margin: 0rem auto;
    background-color: #F0F5F2;
    align-items: flex-end;
    cursor: pointer;
}

#dog {
    max-width: 10rem;
    max-height: 10rem;
    justify-content: end;
    align-items: baseline;
    padding-left: 1rem;
    padding-bottom: 1rem;
}

#dogBowl {
    max-width: 8rem;
    max-height: 8rem;
    padding-right: 3rem;
    margin-left: auto;
}

.hotdog {
    display: none;
}

.scoreBoard {
    display: flex;
    height: 5rem;
    width: 20rem;
    margin: 2rem auto;
    background-color: #232835;
    border: #232835 1px ridge;
    align-items: center;
    color: #F0F5F2;
}

.scoreBoard p {
    font-family: 'Lato';
    font-weight: 500;
    font-size: 1rem;
    width: fit-content;
    padding-left: .5rem;
    margin: 0rem 0rem;
    color: #F0F5F2;
}

#gameScore {
    font-family: 'IBM Plex Sans';
    font-weight: 200;
    margin-left: auto;
    padding-right: 1rem;
    font-size: 4rem;
}

/* THANKS SECTION */
.thanks {
    height: 3rem;
    width: auto;
}

.attribute {
    font-size: .75rem;
    font-family: 'Lato';
    margin: 0rem auto;
}

/* MEDIA SECTION */
@media only screen and (max-width: 600px){
    #gameSpace {
        width: 75%;
    }

    h1 {
        font-size: 3rem;
    }

    p {
        font-size: 1rem;
    }
  }
JavaScript:
let food = 0;

function upDog() {
    food++;
    document.getElementById("gameScore").innerHTML = food;
}

gameSpace.onclick = upDog;

Answer №1

Hey there, @drewemerine!

I'm currently exploring how to dynamically add image elements in random orientations using just HTML, CSS, and JavaScript. It's a fun challenge!

Instead of hardcoding the hotdog image in the HTML, I've crafted a JavaScript function called makeHotDog() that generates a hotdog image on demand. This function leverages another method to produce random coordinates for placing the image. Hope this solution serves you well!

let food = 0;
let gameSpace = document.getElementById("gameSpace");

function getRandomPosition(element) {
  let x = gameSpace.offsetHeight-element.clientHeight;
  let y = gameSpace.offsetWidth-element.clientWidth;
  let randomX = Math.floor(Math.random()*x);
  let randomY = Math.floor(Math.random()*y);
  return [randomX,randomY];
}

function makeHotDog() {
  let img = document.createElement('img');
  let xy = getRandomPosition(img);
  img.setAttribute("src", "https://images.unsplash.com/photo-1515875976234-9d59c3ef288d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80");
  img.setAttribute("class", "hotdog");
  gameSpace.appendChild(img);
  img.style.top = xy[0] + 'px';
  img.style.left = xy[1] + 'px';
}

function upDog() {
  food++;
  document.getElementById("gameScore").innerHTML = food;  
  makeHotDog();
}

gameSpace.onclick = upDog;
// CSS styles
body {
    background-color: #C5F4E0;
    user-select: none;
    /* Additional styling properties */
}
...
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Game</title>
        <link href="https://fonts.googleapis.com/css?family=Bungee|IBM+Plex+Sans:100,200,300i,500|Lato:300,300i,400,700&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="./resources/game.css">
    </head>

    <body>
        <h1>FEED THE PUP</h1>
        <p>Tap to give the dog some food, go for a high score or something!</p>

        <div id='gameSpace'>
            <img id='dog' src="..." alt="">
            <img id='dogBowl' src="..." alt="">
        </div>

        <div class='scoreBoard'>
            <p>SCORE:</p>
            <p id='gameScore'>0</p>
        </div>

        <div class='thanks'>
            <p class='attribute'>Attribution details here.</p>
        </div>

        <script  src="game.js"></script>
    </body>
</html>

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

What is the process for uploading an HTML input file in segments?

Is it possible to upload the whole file at once like this: myInput.onchange = ({ target }) => { const file = target.files[0]; const formData = new FormData(); formData.append("fileData", file); // ...then I post "formData" ...

Toggling dropdown menus with conditional Jquery statements

I am experiencing some discomfort. :) I've been working on a calorie calculator that includes a dropdown for various dietary preferences. Currently, when a user clicks the button, the dropdown appears and disappears when clicking outside the button. ...

Don't waste time creating multiple popups for changing content - streamline your process

Challenge I've successfully extracted information from an array and displayed it dynamically in a tooltip/popup window above each photo on the page. However, with 56 different individuals at various locations, arranging them neatly in a grid poses a ...

What is the process for applying a filter to a background image within the body of a webpage?

I'm attempting to apply a filter to the background image of the body element. Currently, I have implemented the following code: body { background: url("/img/congruent_pentagon.png"); color: white; font-family: "Raleway"; -webkit-filte ...

Displaying data from a PostgreSQL database to users based on their login username in Flask

I am struggling with displaying specific data from a database table based on a user-entered username. The goal is for a user to enter their ID and access a page showcasing their corresponding data from the table. While I can show the username, I'm fac ...

The functionality of save() is not compatible with mongoose.Schema

const Information = require('./Models/Information'); ... let sampleData = new Information( dataSample ); sampleData.save( function ( error ){ console.log('testing); if ( error ) { console.log('Error occurred while saving Informa ...

Tips for showcasing HTML as code tailored to certain programming languages

While browsing the web, I stumbled upon a website that had SQL code displayed with specific classes and styles applied to it. For example, table names were colored blue when inspected. Here is a glimpse of what I encountered: https://i.sstatic.net/WAacj.p ...

Updating JavaScript files generated from TypeScript in IntelliJ; encountering issues with js not being refreshed

Struggling with a puzzling issue in IntelliJ related to the automatic deployment of changes while my server is running (specifically Spring Boot). I've made sure to enable the "Build project automatically" option in my IntelliJ settings. Whenever I ...

Tips for adjusting text color in a paragraph based on its content

I have a paragraph or h1 with phrases like "the color of this item is Magenta" or "this output is Red". These color-specific words (red, black, cyan, magenta or yellow) may appear within the paragraph or h1 tag. Here is my current code snippet: HTML < ...

PHP Header Redirect Not Redirecting Correctly

As a newcomer to PHP, I conducted some research and attempted to implement a solution found on Stack Overflow, but unfortunately, it did not work for me. My goal is to redirect users to another page after a specific code has been executed. Despite removing ...

Attempting to dynamically assign a nickname to a CSS element selector during runtime

I have been attempting to adjust the position of a font awesome icon within an input field dynamically. My goal was to have the style calculated at runtime, similar to how I've handled other stylesheet elements in the past. However, I am facing diffic ...

Mastering state transitions in Angular JS

Currently, I am developing code to display a simple list of users. Upon clicking on a user from the list, I aim to navigate to a view containing detailed information about that particular user. At this stage, I have successfully implemented the functionali ...

Is there a way to hide the borders between cells within these divs?

I am working on an application screen using Vue.js and facing an issue with the divisions between cells. I want to hide these divisions so that the lines of the items appear continuous. I attempted to modify the classes of the columns to "col-md" and "col ...

Design a custom screensaver using jQuery that includes a timed delay feature and an alert message

I am currently working on implementing a screensaver feature for my website. Here is the breakdown of what I am trying to achieve: When detecting the onload, clicks, and touches, I want to start a timer that counts 5 seconds. If any of these events are d ...

Is automatic login possible using JQuery Ajax?

Hey there, I'm trying to figure out how to create an auto login page using JQuery ajax. I want it to include a countdown feature as well. The goal is to speed up my testing process and eventually use these skills for other HTTP requests in various pro ...

Error: The $http variable in Vue Resource is not defined

I encountered an issue with the following code snippet inside my ready method: this.$http.get('url',{},{ headers: { "X-App-Token": "token" } }).then( (data) => this.$set('cdata',data.data)) ...

Tips for enhancing the flexibility of the owl carousel

I've been trying to make four items fit on a medium screen and two on a mobile device, but no matter what I do - adjusting widths, heights, columns, and responsive classes like col-6, col-md-3, col-lg-3 - nothing seems to work well. I could really use ...

Buttoned Up: The Troubling Tale of jQuery and

Seems like this question might be a duplicate, but I'm not bothered. Despite searching on Google, I haven't found a solution. What could be the mistake here? $(document).ready(function() { $("#foo").click(function() { $.ajax({ type ...

Best Practices for Handling URL-Encoded Form Data in the Latest Version of Next.js

Currently delving into Next.js 13, I've implemented a form within my application for submitting a username and password to the server. The form's action path is designated as /submit with a POST request method. Yet, I'm encountering difficul ...

What steps should I take to resolve the error message "Error: srcmain.ts is not found in the TypeScript compilation?"

I've exhausted all possible solutions on StackOverflow and have even gone as far as uninstalling both Node and Angular three times in the span of three days. I'm completely stumped as to why this issue keeps occurring specifically when using "ng ...