Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.

Svelte is a radical new JavaScript framework that is winning the hearts of developers. Its simple syntax makes it a great candidate for beginners who are looking to dive into the world of JavaScript frameworks. One of the best ways to learn, is by building, so in this guide, you will learn how to use the features Svelte offers to create a simple hangman game.

How Hangman Works

Hangman is a word-guessing game typically played between two people, where one player thinks of a word and the other player tries to guess that word letter by letter. The objective for the guessing player is to figure out the secret word before they run out of incorrect guesses.

When the game starts, the host selects a secret word. The length of the word is usually indicated to the other player (guesser) using dashes. As the guesser makes incorrect guesses, additional parts of the hangman are drawn, progressing from head, body, arms, and legs.

The guesser wins the game if they manage to guess all the letters in the word before the stickman figure drawing is complete. Hangman is a great way to test vocabulary, reasoning, and deduction skills.

Setting Up the Development Environment

The code used in this project is available in a GitHub repository and is free for you to use under the MIT license. If you want to have a look at a live version of this project, you can check out this demo.

To get Svelte up and running on your machine, it is advisable to scaffold the project with 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 your terminal and run the following command:

 npm create vite

This will start a new project with the Vite Command Line Interface (CLI). Name your project, select Svelte as the framework, and set the variant to JavaScript. Now cd into the project directory and run the following command to install the dependencies:

 npm install

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

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

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

 npm run dev

Defining the Logic of the Application

Open the App.svelte file and create a script tag that will hold most of the logic of the application. Create a words array to hold 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 variable userInput, a variable randomNumber, and another variable to hold a randomly selected word from the words array.

Assign the selectedWord to another variable initial. In addition to the other variables, create the following variables: match, message, hangmanStages, and output. Initialize the output variable with a string of dashes, depending on the length of the 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;

Adding the Necessary Functionalities

As the player makes a guess, you want to show the output to the player. This output will help the player know if they have made the right or wrong guess. Create a function generateOutput to handle the task of generating an 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 submits, the program will have to determine if it is the right guess. Create an evaluate function that will move the hangman drawing to the next stage if the player guesses wrong, or call the generateOutput function if the player makes a right guess.

 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 = "";
}

And with that, you have completed the logic of the application. You can now move on to defining the markup.

Defining the Markup of the Project

Create a main element that will house every other element in the game. In the main element, define an h1 element with the text Hangman.

 <h1 class="title">
    Hangman
</h1>

Create a tagline and render the hangman figure at the first stage only if the number of elements in the hangmanStages array is greater than 0.

 <div class="tagline">
  I'm thinking of a word. Could you guess the letters in that word?
</div>
{#if hangmanStages.length > 0}
  <pre class="hangman">
  {hangmanStages[0]}</pre>
{/if}

Afterward, implement the logic to show a message indicating whether the player has won or lost:

 {#if hangmanStages.length === 1}
  <div class="message" bind:this={message}>You Lose...</div>
{/if}
{#if selectedWord === match}
  <div class="message" bind:this={message}>You Win...</div>
{/if}

Next, render the output and a form to accept input from the user. The output and the form should only be displayed if the element with the class "message" is not on the screen.

 {#if !message}
  <div class="output">
    {#each output as letter}
      {#if letter !== "-"}
        <span class="complete box">{letter}</span>
      {:else}
        <span class="incomplete box" />
      {/if}
    {/each}
  </div>
  <form on:submit|preventDefault={() => evaluate()}>
    <input
      type="text"
      placeholder="Enter a letter"
      maxlength="1"
      bind:value={userInput}
    />
    <button type="submit">Submit</button>
  </form>
{/if}

Now, you can add the appropriate styling to the application. Create a style tag and in it, add the following:

   * {
    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 created a hangman game with Svelte. Great job!

Screenshot of the finished Hangman game

What Makes Svelte Amazing?

Svelte is a framework that is relatively easy to pick up and learn. Because Svelte's logic syntax is similar to Vanilla JavaScript, this makes it the perfect choice if you want a framework that can hold complex things like reactivity, while giving you the opportunity to work with Vanilla JavaScript. For more complex projects, you can use SvelteKit—a meta framework that was developed as Svelte's answer to Next.js.