Categories
Vue 3 Projects

Create a Memory Game with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a memory game with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create memory-game

and select all the default options to create the project.

We also need the uuid package to let us generate unique IDs for the tiles.

To do this, we run:

npm i uuid

Create the Memory Game

To create the memory game, we write:

<template>
  <div class="container">
    <div v-for="a of answer" :key="a.id" class="tile" @click="onClick(a.id)">
      <div v-if="a.open">
        {{ a.value }}
      </div>
      <div v-else>&nbsp;</div>
    </div>
  </div>
</template>

<script>
import { v4 as uuidv4 } from "uuid";
const answer = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
  .map((n) => {
    return {
      id: uuidv4(),
      open: false,
      value: n,
    };
  })
  .sort(() => Math.random() - 0.5);

export default {
  name: "App",
  data() {
    return {
      answer,
      itemIds: []
    };
  },
  methods: {
    onClick(id) {
      if (!this.itemIds.length < 2 && !this.itemIds.includes(id)) {
        this.itemIds.push(id);
      }
      const index = this.answer.findIndex((a) => a.id === id);
      this.answer[index].open = true;
      if (this.itemIds.length === 2) {
        const item1Index = this.answer.findIndex(
          (a) => a.id === this.itemIds[0]
        );
        const item2Index = this.answer.findIndex(
          (a) => a.id === this.itemIds[1]
        );
        if (this.answer[item1Index].value !== this.answer[item2Index].value) {
          this.answer[item1Index].open = false;
          this.answer[item2Index].open = false;
        }
      }
      if (this.itemIds.length === 2) {
        this.itemIds = [];
      }
    },
  },
};
</script>

<style scoped>
.container {
  display: flex;
}

.tile {
  border: 1px solid black;
  width: 20vw;
  height: 50px;
}
</style>

We have a div with the class container which is a flex container.

Inside it, we have the tiles that we can click.

If 2 tiles have the same value, then they stay displayed.

Otherwise, we make them both blank again.

If a.open is true , we display the value.

Otherwise, we show an empty div.

In the script tag, we create the answer array with the number array.

We mao them to objects with the map method.

Each object has an id and the open value.

And then we sort them randomly with the sort method with a callback that returns a random number between -0.5 and 0.5.

In the data method, we return an object with the reactive properties.

answer is made reactive so that we can render it in the template.

itemId has the IDs of the tile object we clicked on.

Next, we add the onClick method which takes an id that we put into the itemIds reactive array if we have less than 2 items and the item isn’t already in the itemIds array.

Next, we get the index of the item with the given id value and set its open property to true to flip it.

If we have 2 items as indicated by this.itemIds.length === 2 , then we compare both items to see if they have the same value.

If they don’t, then we set open for each item back to false .

And in the last if statement, we set itemIds back to an empty if we already have 2 items in itemIds .

Now when we click on 2 tiles that match, we see them stay displayed with the value.

Otherwise, we see the tile going back to an empty tile.

Conclusion

We can create a memory game easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Magic 8 Ball App with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a magic 8 ball app with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create 8-ball

and select all the default options to create the project.

Create the Magic 8 Ball

To create the magic 8 ball app, we write:

<template>
  <form @submit.prevent="getAnswer">
    <div>
      <label>question</label>
      <input v-model="question" />
    </div>
    <button type="submit">get answer</button>
  </form>
  <div class="circle">
    <p>{{ answer }}</p>
  </div>
</template>

<script>
const answers = [
  "It is certain",
  "It is decidedly so",
  "Without a doubt",
  "Yes - definitely",
  "You may rely on it",
  "As I see it, yes",
  "Most likely",
  "Outlook good",
  "Yes",
  "Signs point to yes",
  "Don't count on it",
  "My reply is no",
  "My sources say no",
  "Outlook not so good",
  "Very doubtful",
  "Reply hazy, try again",
  "Ask again later",
  "Better not tell you now",
  "Cannot predict now",
  "Concentrate and ask again",
];
export default {
  name: "App",
  data() {
    return {
      question: "",
      answer: "",
    };
  },
  methods: {
    getAnswer() {
      if (!this.question) {
        return;
      }
      const index = Math.floor(Math.random() * answers.length);
      this.answer = answers[index];
    },
  },
};
</script>

<style scoped>
.circle {
  border: 1px solid black;
  border-radius: 50%;
  width: 150px;
  height: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>



We have a form with a text input to let us enter a question into the box.

We bind the inputted value to the question reactive property with v-model .

And we listen to the submit event on the form with the @submit directive.

prevent lets us prevent server-side submission and do client-side submission instead.

Below that we have a div with class circle to create the 8 ball.

We’ll make it a circle and center the answer text inside in the style tag.

Next, we have the answers array with the standard answers for the magic 8 ball.

In the data method, we return an object with the initial values of the question and answer reactive properties.

The getAnswer method lets us get the value of the answer reactive property from the answers array by generating a random index to get the answer.

Before that, we check if we entered a question or not.

In the style tag, we make the div a circle by setting the border-radius and the border for the circle.

We also set the width and height to be the same to make it a circle.

display is set to flex so we can use justify-content to center align the text horizontally.

And we center align the text vertically with align-items .

Conclusion

We can create a magic 8 ball app easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Typing Test with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a typing test with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create typing-test

and select all the default options to create the project.

Create the Typing Test

To create the typing test, we write:

<template>
  <div v-if="parts.unmatchedPart.length > 1">
    <div>
      <b>
        {{ parts.matchedPart }}
      </b>
      {{ parts.unmatchedPart }}
    </div>
    <button @click="start">start</button>
    <textarea
      :disabled="!started"
      v-model="typedText"
      style="width: 90vw; height: 300px"
    ></textarea>
  </div>
  <div v-else>
    Your words per minute is {{ wpm }}
    <button @click="restart">restart</button>
  </div>
</template>

<script>
const textToType =
  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sit amet tellus tortor. ";
export default {
  name: "App",
  data() {
    return {
      textToType,
      typedText: "",
      timer: undefined,
      elapsedMs: 0,
      wpm: 0,
      started: false,
    };
  },
  computed: {
    parts() {
      const { textToType } = this;
      const splitTextToType = textToType.split("");
      let endIndexMatch = 0;
      for (const [index, s] of splitTextToType.entries()) {
        if (s !== this.typedText[index]) {
          endIndexMatch = index;
          break;
        }
      }
      return {
        matchedPart: textToType.slice(0, endIndexMatch),
        unmatchedPart: textToType.slice(endIndexMatch),
      };
    },
  },
  methods: {
    start() {
      this.timer = setInterval(() => {
        this.elapsedMs++;
        if (!this.started) {
          this.started = true;
        }
      }, 1000);
    },
    restart() {
      this.started = false;
      this.elapsedMs = 0;
      this.typedText = "";
    },
  },
  watch: {
    parts(val) {
      if (val.unmatchedPart.length === 1) {
        clearInterval(this.timer);
        this.wpm =
          textToType.split(" ").length / (this.elapsedMs / (60 * 1000));
      }
    },
  },
};
</script>



We check if the typing test is completed with the parts.unmatchedPart.length > 1 expression.

parts.unmatchedPart has the part that we haven’t typed into the text area.

Inside the div, we display the text. The part that’s typed is displayed in bold with the b tag.

And the remaining part is stored in the parts.unmatchedPart property.

Below that, we have the start button that calls start when we click it to start the game.

The textarea is where we type in the text to complete the typing test.

In the div with the v-else directive, we display the stuff that we want to display when the test is done.

We show the wpm to the user.

And we have a restart button to call restart when we click on it.

In the script tag, we have the textToType with the text that we want to type.

In the data method, we return an object with the reactive properties.

typedText has the text we’re typing.

elapsedMs is the time that’s elapsed after we start the test.

wpm has the words per minute result.

started indicates whether we started the typing test.

We also have the parts computed property to get the textToType .

We split that so that we can check easily where the part that we typed in ends.

endIndexMatch has the index of the last character that matches what we’re supposed to type in.

At the end of the method, we return an object with the matchedPart , which is the string with the parts of the textToType string that we typed in.

unmatchedPart has the part of the textToType string that we haven’t typed in.

The start starts the typing test by calling sertInterval with a callback to increment this.elaspedMs to start counting the elapsed time.

And we set this.started to true if it’s false .

The restart method resets the values to their initial values.

Conclusion

We can create a typing test easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Dice Game with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a dice game with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create dice-game

and select all the default options to create the project.

Create the Dice Game

To create the dice game, we write:

<template>
  <div>
    <button @click="roll">roll</button>
    <p>rolled dice value: {{ rolledValue }}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      rolledValue: 1,
    };
  },
  methods: {
    roll() {
      this.rolledValue = Math.ceil(Math.random() * 5 + 1);
    },
  },
};
</script>

We have the roll button that calls roll when we click on it.

The rolledValue is displayed below it.

In the script tag, we have the data method that returns an object with the rolledValue reactive property.

The roll method sets the rolledValue to a random number between 1 and 6.

Math.random returns a number between 0 and 1, so we’ve to multiply the returned value by 5 and add 1 to get a value between 1 and 6.

Math.ceil returns a number rounded up to the nearest integer.

Conclusion

We can create a dice game easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Rock Paper Scissors Game with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a rock paper scissors game with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create rock-paper-scissors

and select all the default options to create the project.

Create a Rock, Paper, Scissors Game

To create the rock, paper, scissors game, we write:

<template>
  <div>
    <button @click="selected = 'rock'">rock</button>
    <button @click="selected = 'paper'">paper</button>
    <button @click="selected = 'scissors'">scissors</button>
  </div>
  <button @click="play">play</button>
  <p>your choice: {{ selected }}</p>
  <p>computer's choice: {{ computedSeletced }}</p>
  <div>{{ result }}</div>
</template>

<script>
const choices = ["rock", "paper", "scissors"];
export default {
  name: "App",
  data() {
    return {
      selected: "",
      computedSeletced: "",
    };
  },
  computed: {
    result() {
      const { computedSeletced, selected } = this;
      if (computedSeletced === selected) {
        return `it's a tie`;
      } else {
        if (
          (computedSeletced === "rock" && selected === "scissors") ||
          (computedSeletced === "paper" && selected === "rock") ||
          (computedSeletced === "scissors" && selected === "paper")
        ) {
          return "computer won";
        }
        return "player won";
      }
    },
  },
  methods: {
    play() {
      if (!this.selected) {
        return;
      }
      const computerChoiceIndex = Math.floor(Math.random() * choices.length);
      this.computedSeletced = choices[computerChoiceIndex];
    },
  },
};
</script>

In the template, we have a few buttons.

The top 3 buttons lets the player choose between rock, paper, and scissors.

Below, that we have the play button that calls play when we click the button.

The play method makes the computer pick a choice by setting the computedSelected reactive property to a random choice.

Next, we have 2 p elements to show the choices of the player and the computer.

And then we have a div to display the result.

In the script tag, we have the choices array with the choices.

data returns an array with the reactive properties and their initial values.

Then we add the result computed property to return the game’s result.

We get the computedSelected and selected reactive properties which have the computer and player choices respectively.

If they’re the same, then it’s a tie.

Then in the else block, we check according to the rules of the game.

Rock beats scissors, paper beats rock, and scissors beat paper.

So we check all those conditions to return who won.

Then finally, we have the play method which we mentioned earlier to let the computer pick a choice.

We check that the player picked a choice before letting the computer pick a choice.

Conclusion

We can create a rock, paper, scissors game easily with Vue 3 and JavaScript.