To create a simple "Guess the Number" game using the requirements you provided (an array, a loop, binary language, and an object), we can create a simple JavaScript program. This game allows the player to guess a number between 1 and 100 with five attempts.
Here is an example implementation:
// Create an object to hold the game logic
const NumberGuessingGame = {
// Properties of the game
secretNumber: Math.floor(Math.random() * 100) + 1, // Random number between 1 and 100
chances: 5,
guesses: [],
// Method to start the game
startGame: function() {
console.log("Welcome to the Number Guessing Game!");
console.log("You have " + this.chances + " chances to guess the number between 1 and 100.");
this.playGame();
},
// Method to handle the game logic
playGame: function() {
for (let i = 0; i < this.chances; i++) {
let guess = Number(prompt("Enter your guess:")); // Get user input
// Check if the input is valid
if (isNaN(guess) || guess < 1 || guess > 100) {
console.log("Please enter a number between 1 and 100.");
i--; // Do not decrement chances for invalid input
continue;
}
// Store the guess in the array
this.guesses.push(guess);
// Check the guess
if (guess === this.secretNumber) {
console.log("Congratulations! You've guessed the number correctly: " + this.secretNumber);
return;
} else if (guess < this.secretNumber) {
console.log("Your guess is too low.");
} else {
console.log("Your guess is too high.");
}
}
// After all chances are used up
console.log("Sorry, you've used all your chances. The correct number was: " + this.secretNumber);
console.log("Your guesses were: " + this.guesses.join(", "));
}
};
// Start the game
NumberGuessingGame.startGame();
Explanation of the Code:
-
Object: The game logic is encapsulated in the
NumberGuessingGame
object, which contains properties likesecretNumber
,chances
, andguesses
, as well as methods to start and play the game. -
Array: The
guesses
property is an array that stores all the player's guesses. -
Loop: A
for
loop is used to give the player five chances to guess the number. -
Binary Language Logic: The game compares the guessed number with the secret number and uses basic binary logic for the feedback — either too low, too high, or correct (using
if
,else if
, andelse
statements).
How to Run:
To run this code, you would typically need to execute it in a JavaScript environment that allows for user input, such as a web browser's console.
Note:
Make sure to adjust the way you get user input according to the environment you are running (for example, prompt()
won’t work in a Node.js environment without additional packages).