JavaScript Coding Challenge 1

JavaScript Coding Challenge 1

For a long time, JavaScript was a programming language I tried to stay away from. It’s notorious for being insecure, but maybe a lot of that is due to sloppy coding by some of the people who use it. These days, however, it’s nearly everywhere, so it’s hard to escape. When creating websites, it’s considered as essential to know as HTML and CSS. Recently, I noticed Udemy had a sale on virtually all classes, so I signed up for The Complete JavaScript Course: Build a Real-World Project. I’ve only been doing it a few days, so I’ve got a long way to go. Of the 113 lectures, some of them are called “Coding Challenges”, where the student tries to write a project based on what has been taught already.

Lecture 14 is Coding Challenge 1. The challenge is a simple game between two players. Each player takes their height in centimeters and adds it to five times their age, and the winner is the one with the highest number. To make the game a bit more complex, a third player later joins the game. The code below is my solution.

// simple game
// highest value of height (in cm) and five times age wins

var playerOneHeight = 180;
var playerOneAge    = 26;
var playerTwoHeight = 190;
var playerTwoAge    = 22;

var p1Score = playerOneHeight + playerOneAge * 5;
var p2Score = playerTwoHeight + playerTwoAge * 5;

/*
if (p1Score > p2Score) {
    console.log('Player One wins');
} else if (p1Score < p2Score) {
    console.log('Player Two wins');
} else {
    console.log('Players One and Two are tied');
}
*/

// make it more complex
var playerThreeHeight   = 176;
var playerThreeAge      = 54;

var p3Score    = playerThreeHeight + playerThreeAge * 5;

if (p1Score > p2Score && p1Score > p3Score) {
    alert('Player 1 wins!');
} else if (p2Score > p1Score && p2Score > p3Score) {
    alert('Player 2 wins!');
} else if (p3Score > p1Score && p3Score > p2Score) {
    alert('Player 3 wins!');
} else if (p1Score === p2Score && p1Score > p3Score) {
    alert('Players 1 and 2 have tied!');
} else if (p1Score === p3Score && p1Score > p2Score) {
    alert('Players 1 and 3 have tied!');
} else if (p2Score === p3Score && p2Score > p1Score) {
    alert('Players 2 and 3 have tied!');
} else {
    alert('All players have tied');
}
    
 console.log('Player 1: ' + p1Score + ' Player 2: ' + p2Score + ' Player 3: ' + p3Score);

I’ll post more of the coding challenges later.

JavaScript Coding Challenge 1 For a long time, JavaScript was a programming language I tried to stay away from. It’s notorious for being insecure, but maybe a lot of that is due to sloppy coding by some of the people who use it. These days, however, it’s nearly everywhere, so it’s hard to escape. When…

Leave a Reply

Your email address will not be published. Required fields are marked *