我尝试使用 RxJS 来建模一些游戏。但我发现循环依赖存在一些问题。因此,我将游戏简化为简单的模拟(我只留下了“移动” Action )。你可以在下面找到代码(我省略了一些部分,你可以找到 the repo here )
const rx = require('rx')
const math = require('mathjs')
const _ = require('underscore')
const FIELD_SIZE = 10
const ctx = require('axel');
let getInitialState = () => {
return {
size: FIELD_SIZE,
people: [
{ x: 0, y: 0 },
{ x: 9, y: 9 },
{ x: 5, y: 5 }
]
}
}
var drawWorld = ({size, people}) => {
// draw world logic
}
let getMove = (index)=> {
let [xOffset, yOffset] = [[0,1], [1,0]][math.pickRandom([0, 1])]
let direction = math.pickRandom([-1, 1])
return (state) => {
let {people} = state
let p = people[index]
people[index] = {
x: math.max(
0,
math.min(p.x + xOffset * direction, FIELD_SIZE-1)),
y: math.max(
0,
math.min(p.y + yOffset * direction, FIELD_SIZE-1))
}
return _.extend({}, state, {people})
}
}
var POOL = []
var produceActions = (state) => {
_.range(state.people.length).forEach((i) => {
POOL.push(getMove(i))
})
}
var stateObservable = rx.Observable
.interval(100)
.timeInterval()
.map(()=> {
var x = POOL.slice()
POOL.splice(0, POOL.length)
return x
})
.scan(
(state, ops) => ops.reduce(
(st, o) => o(st),
state
),
getInitialState()
)
stateObservable.subscribe(drawWorld)
stateObservable.tap(produceActions).subscribe()
有没有办法重写这个依赖全局变量的丑陋的“productActions”部分? 就像 @user3743222 答案中建议的那样
最佳答案
这个问题已经在这里讨论过很多次了。
我可以提到的三种方式(可能是其他方式):
关于javascript - RxJS 的循环依赖。孢子建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35037305/