Skip to content

Instantly share code, notes, and snippets.

@cdelaorden
Created December 8, 2015 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdelaorden/1a4e6ba20eb3a55383ac to your computer and use it in GitHub Desktop.
Save cdelaorden/1a4e6ba20eb3a55383ac to your computer and use it in GitHub Desktop.
Space React
<body>
<div id="app">Hey you!</div>
`
</body>
function getRnd(min, max){
let n = Math.round(Math.random()*max);
if(n < min) return min;
return n;
}
function nextFrame(){
window.requestAnimationFrame(Store.update.bind(Store));
}
const Bola = (props) => (
<ellipse rx={ props.rx } ry={props.ry} fill="#def" cx={ props.x} cy={props.y} />
);
const Store = {
__listeners: [],
__balls: [],
addListener(cb){
this.__listeners.push(cb);
},
emitChange(){
this.__listeners.forEach(cb => cb());
},
getBalls(){
return this.__balls;
},
init(max){
for(var i=0; i < max; i++){
this.__balls.push(Immutable.Map({
x: getRnd(0, 1024),
y: getRnd(0, 400),
speed: getRnd(0.5, 4)
}));
}
},
update(){
this.__balls = this.__balls.map(b => {
let x = b.get('x');
if(x > 1024)
x = 0
else
x += b.get('speed');
return b.set('x', x);
});
this.emitChange();
nextFrame();
}
}
const Game = React.createClass({
componentDidMount(){
Store.init(50);
Store.addListener(() => this.forceUpdate());
nextFrame();
},
render(){
const balls = Store.__balls.map((b,index) => (
<Bola key={ index } x={ b.get('x') } y={ b.get('y') } rx="4" ry="4" />
));
return (
<svg width={ 1024 } height={ 400 }>
{ balls }
</svg>
)
}
});
window.onload = React.render(<Game />, document.getElementById('app'));
<script src="//cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.5/immutable.min.js"></script>
#app {
background: #000;
color: #fff
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment