Subscribe

Public Solving: Earth, Fire, Snow game

โœ๏ธ

How to make a rock paper scissor game in JavaScript

25 Dec, 2021 ยท 2 min read

The elves love making up games, and they have their own version of Rock, Paper, Scissor.

Their version includes Earth, Fire, and Snow. Let me quickly tell you how you can win with this game:

  • Fire melts snow
  • Snow covers earth
  • Earth extinguishes fire

Alright, let's get right into coding this fun game for the elves ๐Ÿ‘

Click here to view the puzzle.

Thinking about a solution permalink

I think it's safe to say there are only three options that win for this game.

Then there is a tie (both the same)

That's actually all there is, and it makes our program a bit easier to create.

Let me show you how:

Building the earth, fire, snow game in JavaScript permalink

Let's first define an object with the winning combinations.

const winMatchUp = {
  fire: 'snow',
  snow: 'earth',
  earth: 'fire',
};

There is no need to define the other way around as we can abstract it, seeing we only have two players.

First, let's look at a draw. This means both players picked the same element.

export const selectWinner = (user1, user2) => {
  if (user1.choice === user2.choice) return null;
};

Then we can check if user1's choice match up is equal to user2's choice. This would mean user 1 one.

Let's me check an example to explain a bit more:

  • user one picked snow
  • user two picked earth

We then query our match-up table and say give us the matchup object for snow. This will return earth.

So if we now compare this to user two choice, we won!

In our code we can do it like so:

if (winMatchUp[user1.choice] === user2.choice) return user1;

This automatically means, if user 1 did not win, user 2 must have won!

export const selectWinner = (user1, user2) => {
  if (user1.choice === user2.choice) return null;
  if (winMatchUp[user1.choice] === user2.choice) return user1;
  return user2;
};

And there you go!

A super simple game, but yet so much fun.

I've run the test as a sanity check, and they turn green โœ….

All test green

Let me know what you think of my solution and how you would do differently.

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

Public Solving: Find the missing presents

3 Jan, 2022 ยท 2 min read

Public Solving: Find the missing presents

Public Solving: Caesar decipher in JavaScript

2 Jan, 2022 ยท 4 min read

Public Solving: Caesar decipher in JavaScript

Join 1365 devs and subscribe to my newsletter