首页 \ 问答 \ 功能“实时”组合(Functional “real-time” composition)

功能“实时”组合(Functional “real-time” composition)

我最近发现了一篇很棒的文章,内容涉及对象组合VS传统继承的好处。

希望我的问题不会被标记为自以为是,但我想知道在对象基于用户的游戏交互进行更改时使用合成的好方法。

以文章代码为例:

const canCast = (state) => ({
    cast: (spell) => {
        console.log(`${state.name} casts ${spell}!`);
        state.mana--;
    }
})

const canFight = (state) => ({
    fight: () => {
        console.log(`${state.name} slashes at the foe!`);
        state.stamina--;
    }
})

const fighter = (name) => {
  let state = {
    name,
    health: 100,
    stamina: 100
  }

  return Object.assign(state, canFight(state));
}

const mage = (name) => {
  let state = {
    name,
    health: 100,
    mana: 100
  }

  return Object.assign(state, canCast(state));
}

scorcher = mage('Scorcher')
scorcher.cast('fireball');    // Scorcher casts fireball!
console.log(scorcher.mana)    // 99

slasher = fighter('Slasher')
slasher.fight();              // Slasher slashes at the foe!
console.log(slasher.stamina)  // 99

如何在运行时使用组合来更改Character对象的状态? 而不是已经存在的Mage对象,我希望Character对象基于游戏事件而改变,例如。 角色捡起一名工作人员,现在成为一名现在可以施法的“法师”。 我想到的第一件事就是在Character中有一个状态属性,它根据交互而变化,而Character则以某种方式“继承”现在施放并获得法术力状态属性的能力。


I recently came across a great article covering the benefits of object composition VS traditional inheritance.

Hopefully my question is not going to be flagged as opinionated but I'd like to know a good approach to using composition for when an object changes based on a user's game interaction.

Using the articles code as an example:

const canCast = (state) => ({
    cast: (spell) => {
        console.log(`${state.name} casts ${spell}!`);
        state.mana--;
    }
})

const canFight = (state) => ({
    fight: () => {
        console.log(`${state.name} slashes at the foe!`);
        state.stamina--;
    }
})

const fighter = (name) => {
  let state = {
    name,
    health: 100,
    stamina: 100
  }

  return Object.assign(state, canFight(state));
}

const mage = (name) => {
  let state = {
    name,
    health: 100,
    mana: 100
  }

  return Object.assign(state, canCast(state));
}

scorcher = mage('Scorcher')
scorcher.cast('fireball');    // Scorcher casts fireball!
console.log(scorcher.mana)    // 99

slasher = fighter('Slasher')
slasher.fight();              // Slasher slashes at the foe!
console.log(slasher.stamina)  // 99

How do I use composition to change the state of the Character object during run-time? Instead of the Mage object already existing I want the Character object to change based on a game event eg. Character picks up a staff and now becomes a "Mage" who can now Cast spells. First thing that comes to mind is to have a state property in Character that changes based on the interaction and the Character somehow "inherits" the ability to now Cast and gains a mana state property.


原文:https://stackoverflow.com/questions/50844719
更新时间:2022-05-20 20:05

最满意答案

尝试这个。 我必须通过转义每个的尾随引号来修复无效的JSON

\"Test Product 1" <<<<
\"Test Product 2" <<<<

var data = [
    {
        "product": "[{\"imgUrl\":\"/p/332401\",\"prodCartQty\":2,\"prodName\":\"Test Product 1\",\"productCode\":\"332401\"},{\"imgUrl\":\"/p/332388\",\"prodCartQty\":2,\"prodName\":\"Test Product 2\",\"productCode\":\"332388\"}]",
        "category": "gross_MAX_1",
        "totalCategory": 1
    },
    {
        "product": "[{\"imgUrl\":\"/p/332401\",\"prodCartQty\":2,\"prodName\":\"Test Product 1\",\"productCode\":\"332401\"},{\"imgUrl\":\"/p/332388\",\"prodCartQty\":2,\"prodName\":\"Test Product 2\",\"productCode\":\"332388\"}]",
        "category": "gross_MAX_1",
        "totalCategory": 1
    }
]



$.each(data,function(_,productArr) {
  var arr = JSON.parse(productArr.product.replace(/\//g,""));
  $.each(arr,function(_,productDetails) {
    // here is a product detail object
    $.each(productDetails,function(name,value) {
      console.log(name,value);
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


Try this. I had to fix the invalid JSON by escaping the trailing quote on each

\"Test Product 1" <<<<
\"Test Product 2" <<<<

var data = [
    {
        "product": "[{\"imgUrl\":\"/p/332401\",\"prodCartQty\":2,\"prodName\":\"Test Product 1\",\"productCode\":\"332401\"},{\"imgUrl\":\"/p/332388\",\"prodCartQty\":2,\"prodName\":\"Test Product 2\",\"productCode\":\"332388\"}]",
        "category": "gross_MAX_1",
        "totalCategory": 1
    },
    {
        "product": "[{\"imgUrl\":\"/p/332401\",\"prodCartQty\":2,\"prodName\":\"Test Product 1\",\"productCode\":\"332401\"},{\"imgUrl\":\"/p/332388\",\"prodCartQty\":2,\"prodName\":\"Test Product 2\",\"productCode\":\"332388\"}]",
        "category": "gross_MAX_1",
        "totalCategory": 1
    }
]



$.each(data,function(_,productArr) {
  var arr = JSON.parse(productArr.product.replace(/\//g,""));
  $.each(arr,function(_,productDetails) {
    // here is a product detail object
    $.each(productDetails,function(name,value) {
      console.log(name,value);
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

相关问答

更多
  • 你的问题出现在你的$.each你已经把它降低到data.results.image的水平,然后你正在寻找results.image 。 所以对于你的jQuery脚本,你正在寻找每一个data.results.image.results.image ,而这是不存在的。 要循环遍历每个results对象,您需要在$.each上执行$.each ,然后查找element.image 。 这是一个工作的JSFiddle,它演示了这个: http : //jsfiddle.net/7udv3uoh/4/ Your p ...
  • 只需创建一个新的JSONArray。 JSONArray otherJsonArray = new JSONArray(); 或者遍历数组并remove(int index)索引。 http://www.json.org/javadoc/org/json/JSONArray.html#remove(int) Just create a new JSONArray. JSONArray otherJsonArray = new JSONArray(); Or iterate through the arr ...
  • 首先你必须解码你的json数据 $json = json_decode($data[0]['json']); 然后你可以访问你的AfterParticipationHeader $json->Canvas[0]->MainObjects->{"After Participation"}->afterParticipationHeader First you have to decode your json data $json = json_decode($data[0]['json']); Then ...
  • 您可以尝试使用lodash方法来实现您的目标: - var _ = require('lodash'); socket.on('disconnect', function(){ _.pullAllWith(users, [{ user:socket.nick, userid:socket.id, socket:socket }], _.isEqual) }); }) ...
  • function filterOnPlayerStatSummary(myObject, filter) { var result = []; for(var i = 0; i < myObject.length; i++) { if (myObject[i].playerStatSummary == filter) { result.push(myObject[i]); } } retur ...
  • 我假设您需要在变量中获取json key名称 尝试这个: $.each(result, function(key, value){ console.log(key, value); }) result是json结构即 result = { 'Name':'anything'}; I am assuming you need to get the json key name in a variable try this: $.each(result, function(key, value){ conso ...
  • 尝试这个。 我必须通过转义每个的尾随引号来修复无效的JSON \"Test Product 1" <<<< \"Test Product 2" <<<< var data = [ { "product": "[{\"imgUrl\":\"/p/332401\",\"prodCartQty\":2,\"prodName\":\"Test Product 1\",\"productCode\":\"332401\"},{\"imgUrl\":\"/p/332388\",\"prod ...
  • // Define it where you want it to be accessible var people; $.getJSON("file.json", function (json) { // Store the data in people to make it accessible globally people = json.data; people.forEach(function(person){ console.log(person.Name); }); ...
  • 使用jQuery jQuery.getJSON() : $.getJSON('ajax/test.json', function(data) { console.log(data); //see your data ( works in Chrome / FF with firebug) console.log(data["Restoration"][0]["easy"]["value"]) //should output 1 }); using jQuery jQuery.get ...
  • 试试吧 foreach($jsonarray as $k=>$alldata) { foreach($alldata["Bestaende"] as $idx => $Bestaende) { echo '
    ';
           echo 'Print Menge: '.$Bestaende['Menge'];
           echo '
    '; } } Try it like this foreach($jsonarray as $k=>$alldata ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。