How to create Hangman game using Svelte

Svelte is a brand new JavaScript framework that is winning the hearts of programmers. You can use Svelte to create an engaging Hangman game in a very simple way.

How to create Hangman game using Svelte Picture 1

Svelte's simple syntax makes it a great candidate for beginners diving into the world of JavaScript frameworks. One of the best ways to learn Svelte is to build a simple app or game like Hangman.

What is Hangman Game?

Hangman is a word guessing game usually played by 2 people. In it, one player will give a secret word, the other person needs to guess each letter in that word. The goal for the guesser is to find the secret word before all the wrong guesses run out.

When the game starts, the game master chooses a secret word. The length of a word is often expressed in terms of the number of dashes. When the person guesses the letter incorrectly, draw a part of the hangman, from head, torso, arms to feet.

The guesser wins if they correctly guess all the letters in the secret word before the stickman drawing process is completed. Hangman is a great way to test vocabulary, reasoning and reasoning skills.

Set up the development environment

To get Svelte up and running on your machine, you should build the project using Vite.js. To use Vite, make sure you have Node Package Manager (NPM) and Node.js installed on your machine. You can also use an alternative package manager like Yarn. Now open terminal and run the following command:

npm create vite

This action will launch a new project with Vite Command Line Interface (CLI). Name your project, choose Svelte as the framework, and set variables to JavaScript . Now cd in the project directory and run the following command to install the dependencies:

npm create vite

Now open the project, and in the src folder, create the hangmanArt.js file, delete the assets and lib  folders . Then delete the contents of the App.svelte , App.css files . In the App.css file , add:

:root{ background-color: rgb(0, 0, 0); color:green; font-family: monospace; } 

Copy the contents of hangmanArt.js from this project's GitHub repository, then paste it into the hangmanArt.js file . You can start the programming server with the following command:

npm run dev

Determine the logic of the application

Open the App.svelte file and create a tag script that will contain most of the application's logic. Create a words array to contain a list of words.

let words = [ "appetizer", "roommates", "shrinking", "freedom", "happiness", "development", ];

Next, import the hangmanArt array from the hangmanArt.js file . Then create a userInput variable, a randomNumber variable , and another variable to hold the randomly selected word from the words array .

Attach the selected word to a variable other than initial . In addition to other variables, create the following variables: match , message , hangmanStages , and output . Initialize the result variable with a string of dashes, depending on the length of selectedWord . Assign the hangmanArt array to the hangmanStages variable .

import { hangmanArt } from "./hangmanArt"; let userInput; let randomNum = Math.floor(Math.random() * (words.length - 1)); let selectedWord = words[randomNum].toUpperCase(); let initial = selectedWord; let match; let message; let hangmanStages = hangmanArt; let output = ""; [.selectedWord].forEach(() => (output += "-")); match = output;

 

Add necessary functions

When players guess a word, you want to display results showing whether they guessed correctly or incorrectly. Create a generateOutput function to handle the task of generating output.

function generateOutput(input1, input2) { output = ""; for (let i = 0; i < input1.length; i++) { if (input2[i] === "-") { output += input1[i]; } else { output += "-"; } } }

For each guess the player makes, the program must determine whether it is correct or incorrect. Create an evaluate function that moves the player's drawing to the next stage if the player guesses incorrectly, or call the generateOuput function if the player guesses correctly.

function evaluate() { let guess = userInput.toUpperCase().trim(); if (!guess) { return; } if (selectedWord.includes(guess)) { selectedWord = selectedWord.replaceAll(guess, "-"); generateOutput(initial, selectedWord); } else { hangmanStages.shift(); hangmanStages = hangmanStages; } userInput = ""; }

As a result, you have completed the application logic. Now you can move on to defining the markup.

Determine the project's markup

Create a main element that contains all the elements in the game. In the main element , define h1 with the text Hangman .

Hangman

Create tagline and display hangman in the first stage if the number of elements in the hangmanStages array is greater than 0.

 I'm thinking of a word. Could you guess the letters in that word? {#if hangmanStages.length > 0}
{hangmanStages[0]}
{/if}

Then, implement the logic that now tells the player whether they won or lost:

{#if hangmanStages.length === 1} You Lose. {/if} {#if selectedWord === match} You Win. {/if}

Next, display the results and a form that accepts user input. This result and form will only be displayed if the element containing the 'message' class is not on the screen.

{#if !message} {#each output as letter} {#if letter !== "-"} {letter} {:else} {/if} {/each} evaluate()}>  {/if}

Now you can add appropriate styles to your app. Create a style tag and add the following code inside it:

 * { color: green; text-align: center; } main { display: flex; width: 100%; flex-direction: column; justify-content: center; align-items: center; } input, button { text-transform: uppercase; background-color: transparent; border: solid 1.2px green; height:40px; font-size: 15px; } .box { display: flex; align-items: center; justify-content: center; width: 45px; height: inherit; border: dotted 1.2px green; } .output { display: flex; font-size: 23px; font-weight: 600; height: 45px; gap: 10px; justify-content: center; } .hangman { font-size: 32px; } form { margin-top: 50px; } .tagline, .message { font-size: 20px; }

You have successfully created the Hangman game with Svelte.

How to create Hangman game using Svelte Picture 2

4 ★ | 2 Vote

May be interested

  • Google Maps helps developers create real-world gamesGoogle Maps helps developers create real-world games
    pokémon go stormed in july 2016 when it debuted with game characters realized in the real world map. now google is making any game developer able to do the same with google maps through the unity game engine.
  • Answer game 2 Image 1 word: Guess the word, Track the songAnswer game 2 Image 1 word: Guess the word, Track the song
    with this set of answers, you will easily pass the difficult screen guessing game of 2-picture 1-word game - searching for the song. however, you remember to refer to the answer only when really deadlocked, do not abuse it, so will create attraction as well as create more dramatic.
  • How to make an apple picking game on PowerPointHow to make an apple picking game on PowerPoint
    the apple picking game on powerpoint is a familiar game for teachers to include in their lesson plans, creating a lively atmosphere for their classrooms.
  • How to create scrolling backgrounds in PygameHow to create scrolling backgrounds in Pygame
    this python game library is packed with features, including some simple tools you can use to create smooth, parallel scrolling backgrounds for your games.
  • How to Create a Racing Game in ScratchHow to Create a Racing Game in Scratch
    this wikihow teaches you how to create a basic racing game using mit's free scratch program. the main point of this racing game is to complete the track in as little time as possible without crashing. open scratch. go to...
  • 10 reasons to use Godot Engine for game development10 reasons to use Godot Engine for game development
    now it is easier than ever to develop a game thanks to many free game development tools and online tutorials, anyone can create a simple game.
  • How to create a camera system for 2D games in GodotHow to create a camera system for 2D games in Godot
    a well-designed camera system can appeal to players and give them a better perspective. creating a camera system in godot  is simple but effective. here are detailed instructions.
  • How to Get Some Minecraft Game TipsHow to Get Some Minecraft Game Tips
    this is an article showing how to play minecraft game on your computer, smartphone or tablet, or game console. after purchasing, downloading and/or installing minecraft, you can create a new world to begin exploring and experiencing the game's features.
  • How to build a game server on LinuxHow to build a game server on Linux
    current games can not only connect to the server but also run that server. learn about everything you need to build a linux server game through the following article.
  • How to play the virtual cat CryptoKitties gameHow to play the virtual cat CryptoKitties game
    the game of raising cryptokitties cats is storming these days. this is a cryptokitties game, a virtual cat game based on the blockchain technology that people are talking about.