Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

JavaScript Objects and Simple Game Development

Tech 1

JavaScript Objects

Creating Objects in JavaScript

Literal Notation

The simplest method for creating an object involves using curly braces {} to define its properties and methods.

const person = {
  name: 'Zhang San',
  age: 20,
  greet: function() {
    console.log('Hello, I am ' + this.name);
  }
};

Object Constructor

Objects can also be created using the new Object() syntax, followed by property assignments via dot or bracket notation.

const person = new Object();
person.name = 'Zhang San';
person.age = 20;
person.greet = function() {
  console.log('Hello, I am ' + this.name);
};

Factory Functions

Factory functions encapsulate object creation logic and return new objects, enhancing code reusability.

function createPerson(name, age) {
  const person = new Object();
  person.name = name;
  person.age = age;
  person.greet = function() {
    console.log('Hello, I am ' + this.name);
  };
  return person;
}

const p1 = createPerson('Zhang San', 20);
const p2 = createPerson('Li Si', 22);

Constructor Functions

Constructor functions are specialized functions used to initialize newly created objects. They typically start with a capital letter and are invoked with the new keyword.

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    console.log('Hello, I am ' + this.name);
  };
}

const p1 = new Person('Zhang San', 20);
const p2 = new Person('Li Si', 22);

Accessing Object Properties

Dot Notation

The most common way to access object properties uses the dot operator.

const person = {
  name: 'Zhang San',
  age: 20
};

console.log(person.name); // Outputs: Zhang San
console.log(person.age);  // Outputs: 20

Bracket Notation

Bracket notation is useful when dealing with special characters, spaces, or reserved words in property names.

const person = {
  "first name": 'Zhang San',
  'age-years': 20
};

console.log(person['first name']); // Outputs: Zhang San
console.log(person['age-years']);  // Outputs: 20

const key = 'first name';
console.log(person[key]); // Outputs: Zhang San

Computed Property Names

In object literals, square brackets allow dynamic property names based on expressions.

const prefix = 'user_';
const id = 123;

const user = {
  [prefix + id]: 'Zhang San'
};

console.log(user.user_123); // Outputs: Zhang San

Using Object Methods

Methods like Object.keys(), Object.values(), and Object.entries() provide arrays of object elements for iteration and access.

const person = {
  name: 'Zhang San',
  age: 20
};

const keys = Object.keys(person);
const values = Object.values(person);
const entries = Object.entries(person);

console.log(keys[0]);       // Outputs: name
console.log(values[1]);     // Outputs: 20
console.log(entries[0][1]); // Outputs: Zhang San

The in Operator

The in operator checks weather an object has a specific property.

const person = {
  name: 'Zhang San',
  age: 20
};

if ('name' in person) {
  console.log(person.name); // Outputs: Zhang San
}

Developing a Simple Game with JavaScript

We will build a number guessing game.

Setting Up the Game Interface

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Guess Number Game</title>
</head>
<style>
  .game-container {
    box-sizing: border-box;
    width: 400px;
    height: 300px;
    border: 5px pink dashed;
    padding: 85px;
    margin-top: 150px;
    margin-left: 500px;
  }
</style>
<body>
  <div class="game-container">
    <span>Enter your guess:</span>
    <input type="text" id="guessInput">
    <input type="button" value="Submit Guess" id="submitBtn">
    <br>
    Result: <span class="result"></span>
    <br>
    <br>
    <input type="button" value="Restart Game" id="restartBtn">
  </div>
</body>
</html>

Implementing Game Logic

const inputField = document.querySelector('#guessInput');
const resultDisplay = document.querySelector('.result');
const submitButton = document.querySelector('#submitBtn');
const restartButton = document.querySelector('#restartBtn');

let attempts = 0;
let targetNumber = Math.floor(Math.random() * 100) + 1;

submitButton.onclick = function() {
  attempts++;
  const userGuess = parseInt(inputField.value);

  if (userGuess > targetNumber) {
    resultDisplay.innerHTML = "Too high!";
    resultDisplay.style.color = "red";
  } else if (userGuess < targetNumber) {
    resultDisplay.innerHTML = "Too low!";
    resultDisplay.style.color = "red";
  } else {
    resultDisplay.className = "correct";
    resultDisplay.innerHTML = "Correct!";
    resultDisplay.style.color = "green";
  }
};

restartButton.onclick = function() {
  targetNumber = Math.floor(Math.random() * 100) + 1;
  attempts = 0;
  resultDisplay.innerHTML = '';
  inputField.value = '';
};

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.