Mechanism for enhancing and modifying capabilities of an object through a design pattern

TL:DR design pattern for objects that temporarily modify each other in a game scenario. Functionality is added and then removed dynamically.

As a database developer delving into front-end development, I am exploring new techniques to stay informed about various layers of the technology stack. While I am not well-versed in object-oriented programming, I possess a basic understanding of problem-solving with objects. However, I lack knowledge about different design patterns and their applicable scenarios. In my journey to learn AngularJS, I have chosen to replicate the board game Small World to outline my project requirements swiftly. Here is the foundation I aim to establish:

The game revolves around Powers and Races, each having unique ways of altering game rules. These Power/Race combinations are used to conquer Regions for points, with modifications activating at different phases:

  1. First Turn (Wealthy: gain 7 points, occurs only once)
  2. Start Turn (Amazons: receive 4 extra tokens)
  3. Enter Decline (Ghouls: Ghouls function like an active race in decline; Stout: immediately select your next race upon entering decline)
  4. Conquest (Commando: require 1 fewer token to conquer a region)
  5. Redeploy (Amazons: lose 4 tokens; Fortress: Place a fortress in an occupied region for +1 defense and +1 point)
  6. End Turn (Hill: gain 1 extra point on a hill region; Orcs: +1 point for each region conquered this turn)
  7. Multi Player/Totally Unique(Diplomat: select a player not attacked this turn, rendering them unable to attack until your next turn)

Furthermore, some regions can possess special attributes:

  1. Mine: dwarves receive +1 point from this region even in decline
  2. Magic Source: wizards gain +1 point from this region
  3. Underworld: races with the underworld power consider all underworld regions adjacent
  4. Mountain: requires 1 extra token to conquer, with +1 defense

During gameplay, race/power combos will appear and disappear, replaced by new combinations. Managing numerous attributes while races exist is essential (e.g. tracking attacked players for diplomat). While it's feasible to define attributes for known scenarios, my aim is to allow addition of new race/powers in the config file, enabling the game to comprehend and implement rule modifications. I propose a general object called a Modifier to structure my objects:

{
  event:'endTurn',
  modify:{
     points: 1,
     strength: -4,
     strength: -1,
     actions:[function(gameState, region, gameRace){
        //conditional logic or advanced modifiers
     }]
  }
}


SWGame 
+--+Player[]
|  |
|  +--+GameRace[]
|     |
|     +--+Race 
|     |  
|     |  +---Modifier[]
|     |
|     +--+Power
|        |
|        +---Modifier[]
+--+GameMap 
   |
   +--+Region[] 
      |
      +---Modifier[] 

The challenge I face is managing Races that modify regions (e.g. Giants: if you occupy a mountain, adjacent regions to the mountain cost 1 fewer tokens to conquer). Applying a "strength: -1" modifier to adjacent regions, and later removing the Giants' modifiers at the end of a turn before applying new player modifiers, is becoming cumbersome. The tracking of modifiers is becoming convoluted. Any suggestions for a better-suited design pattern for this scenario would be highly appreciated.

Answer №1

If you want to enhance your knowledge on constructor functions and the usage of object.defineProperty, here's a suggestion for you. Create an object to manage factors that might be carried over, in the following manner:

function example(obj){
    this.strengthEffects = obj.strengthEffects;
    this.healthEffects = obj.healththEffects;
}

Alternatively, you can consider:

function example(obj){
    this.amazon = obj.amazon; //boolean value
    //similar approach for other factors
}

Next, evaluate them in a constructor function like this:

function changeRace(new example(myObj));

changeRace(carryOver){
    for (var i in carryOver) {
        this.prop = i;
        this.propVal = carryOver[i];
    }
}

By incorporating this code structure, you can employ object.defineProperty alongside a switch statement to adjust points for specific attributes or modifications dynamically.

Hopefully, this explanation proves beneficial to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on testing a function with a dependency in Angular through unit testing

Attempting to dive into unit testing, I have grasped some of the basics. However, my current challenge lies in testing a method within my code. This particular method involves calling a function from oidc-client.js that handles user sign-ins. My spec fi ...

Strings that automatically adjust to fit the content from a JSON object

I have a JSON object with a long string that I want to display. The string looks like this: "String":"<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever si ...

The optimal method for computing the Fibonacci sequence using JavaScript

Improving my skills in optimizing algorithms and understanding big-o notation is a priority for me. I devised the following function to compute the n-th Fibonacci number. It works well for higher inputs, but I wonder how I can enhance it. What are the dow ...

Possible conflict between CSS and JavaScript on Magento website

Problem Description: Visit this link for more details I am facing an issue with the product upload process when using certain attributes. It appears to be related to a positioning problem. Despite trying various solutions, such as removing the position at ...

A stylish flyout menu with a sleek li background in jquery

Experimenting with http://tympanus.net/Tutorials/CufonizedFlyOutMenu/, I decided to remove the fly-in descriptions and am now attempting to load the extra li with a style that will "highlight" the li.current-menu-item element. An object is set up as follo ...

Is it possible to include a div above a centered image?

Currently I am working with ImageFlow and I would like to overlay a div on top of the image when it is clicked, sliding it into the center. I have been looking through the JavaScript file but the function MoveIT() seems to be called multiple times and I am ...

What is the process for changing proxy settings through the command line when using Create React App?

I recently created a React project using Create React App and set up the development server to proxy API requests through the proxy setting in my package.json: ... "proxy": "https://dev-backend.example.com" ... However, I am looking ...

When creating nested objects, the defineproperty function on the object prototype does not trigger

Exploring and experimenting to unravel the workings of this feature, but I find myself puzzled by this particular scenario. Object.defineProperty(Object.prototype, 'a', {set: function() {console.log("Set!");} }); Based on my understanding, when ...

Customize each Picker.Item element in React Native with unique styles

How can I style individual Picker.Items beyond just changing the text color? Additionally, what other props can be used for a Picker.Item? I am aware of "key", "value", "label", and "color". Are there any additional props available? I want to customize o ...

Creating subdocuments with input types in MERN stack using Apollo Sandbox and MongoDB mutations

These questions are specific to a Node server application built in JavaScript using express, apollo-server-express, mongoose, and graphql. Below is the content of the package.json file: { "name": "dimond-media-mern-app", "vers ...

Do you know of a solution to fix the Stylelint error regarding semicolons when using CSS variables?

React.js Css in JS(Emotion) The components above are part of this setup. Here is the configuration for Stylelint: module.exports = { extends: [ "stylelint-config-standard", "./node_modules/prettier-stylelint/config.js", ], ...

Is there a way to seamlessly transition between images in a slider every 3 seconds using javascript?

<!DOCTYPE html> <html> <head> <title>Hello</title> <meta http-equiv="Content-Type" type="text/html" charset="UTF-8"/> <style> *{margin:0; padding:0;} .mySlides{ position:relative; width:1000px; ...

Tips for utilizing the window object in Angular 7

To implement the scrollTo() function of the window object directly, we can use window.scrollTo(0,0). However, when researching how to do this in Angular, I found that many people create a provider as shown below: import {InjectionToken, FactoryProvider} f ...

Understanding the proper way to enclose JSX components and exhibit JSON based on user input

I'm currently working on a university administration website using React that needs to support multiple languages. I have successfully built the Login page, which you can see here: https://i.stack.imgur.com/cIiaU.png Now, my next task is to allow us ...

The inline style in Angular 2 is not functioning as expected when set dynamically

Having a small dilemma... I'm trying to apply an inline style within a div like this: div style="background: url(..{{config.general.image}})"></div Oddly enough, it was functioning in beta 16 but ever since the RC1 upgrade, it's no longer ...

Solving an object in ui-router state using ui-sref

Dealing with a large JSON object in an Angular controller and wanting to pass it to the controller of a template that will be displayed in a ui-view. I am aware that parameters can be passed to states using ui-sref, but I do not want this object to be visi ...

Using the Mousetrap binding on a nuxt.js page may not be effective

Hey there! I'm trying to achieve a certain functionality where I want to redirect to a different page once a specific sequence is typed. Although I can see the message "It works" in my console, the redirection is not happening and instead, I am gettin ...

Verify the placement within the text box

Are there methods available in JavaScript or any JavaScript framework to determine the position within a textbox? For example, being able to identify that figure 1 is at position 2 and figure 3 is at position 3. Figure 1 Figure 2 ...

The issue at hand is that one of the JavaScript buttons is functioning properly, while the other is not playing the video as intended. What steps can

I've been working on a script for my school project website that should make buttons play videos, but I'm running into an issue where it only works for the first button (btn). Programming isn't my strong suit, and I put this together based o ...

How can I prevent clearQueue() from removing future queues?

In my code, I have a button that triggers the showing of a div in 500ms when clicked. After the div is shown, a shake class is added to it after another 500ms. The shake class is then removed after 2 seconds using the delay function. However, if the user c ...