Creating a game using Food Images API

Creating a game using Food Images API

ยท

6 min read

While surfing Twitter mindless at 1 a.m., I came across a tweet by Scrimba. I had heard about them for the first time. It is a learning platform where we can directly interact with the code the instructor is teaching.

They host weekly challenges and this week's criteria was to create anything using the Foodish API. I liked how it is open ended and everyone from beginner to advanced developers can participate. There's a slight chance of winning swags too. Now who doesn't like that?

giphy-downsized.gif

After thinking a while, I decided to create a simple game to compare whether two dishes are same or not. I will be sharing the process with some snippets below but you can check out the complete code here.

I used CSS grid to divide the page into a 2x2 table. There would be the heading text in first cell and option buttons in the last one. That leaves the other two diagonal cells for the images.

<body>
    <div id="title">
        <p>Let's taste your FoodSense ๐Ÿ•</p>
        <p>Are these dishes same or different?</p>
    </div>
    <div id="image1">
        <img class="bottom" />
    </div>
    <div id="image2">
        <img class="bottom" />
    </div>
    <div id="subscribe">
        <button id="same">Same โœ…</button>
        <button id="different">Different โŒ</button>
    </div>
</body>
body {
    display: grid;
    grid-template-columns: 50% 50%;
    grid-template-rows: 50% 50%;
    background: #ffeca4;
    height: 100vh;
    margin: 0px;
}

I will not delve deep in the styling part here. The next challenge was to populate those two image tags with the result of calling the API. I achieved it by setting their src attribute using JavaScript. I used axios library but the normal fetch command would also work. Axios is simpler and also parses JSON out of the box.

let img1bot = document.querySelector('#image1').querySelector('.bottom');
let img2bot = document.querySelector('#image2').querySelector('.bottom');

async function reset() {
    let res1 = await axios.get('https://foodish-api.herokuapp.com/api/');
    let res2 = await axios.get('https://foodish-api.herokuapp.com/api/');
    f1 = res1.data.image;
    f2 = res2.data.image;
    img1bot.setAttribute('src', f1);
    img2bot.setAttribute('src', f2);
    f1 = f1.slice(41);
    f2 = f2.slice(41);
    f1 = f1.slice(0, f1.indexOf('/'));
    f2 = f2.slice(0, f2.indexOf('/'));
}
reset();

Here reset is an asynchronous function. I am also keeping track of two variables f1 and f2. They store the food item category (string). We will use them later to compare whether user selected the right choice. There may be better ways to extract this, probably using regular expressions but this is what I came up with.

The background was looking a little dull so I added some particle animations using particles.js library. It was not as hard as I expected. We just need to add a canvas element and some javascript.

window.onload = function () {
    Particles.init({
        selector: '.background',
        connectParticles: true,
        color: '#ffa500'
    });
};

Now let's make sure something happens when the user clicks the same or different button. I wanted to display the result as an overlay with some text and a button to try again. We achieve so by calling the location.reload() function. To create the overlay we add a div with fixed position and width & height of 100%. It is hidden by default and shown only when the user makes a choice.

I also added two audio files to play for correct and wrong guess. Playing audio requires just 2 lines of JavaScript. A simple if else clause take cares of determining win or loss. The categories of food available is quite small so there's a decent chance that same photos will appear.

function btnClicked(e) {
    if (e.srcElement === same && f1 == f2) {
        console.log('Yeahhh!');
        winsound.play();
    } else if (e.srcElement === different && f1 != f2) {
        console.log('Yeahhh!');
        winsound.play();
    } else {
        console.log('Boo!');
        endtext.innerHTML = 'Not Expected from you ๐Ÿ‘Ž';
        losesound.play();
    }
    document.getElementById("overlay").style.display = "block";
}

And that's it for the challenge. It was my first time making something like this. The challenge took whole one day to complete but it was time well spent and I learnt a lot. Ending with some screenshots of my solution. Can you find the pun in them? ๐Ÿ˜œ

Screenshot_2021-02-09_00-03-08.png

Screenshot_2021-02-09_00-03-33.png