Browse Source

experimenting with a speed slider

Brandon Wong 8 years ago
parent
commit
86d8a8893f
1 changed files with 21 additions and 7 deletions
  1. 21 7
      src/main.js

+ 21 - 7
src/main.js

@@ -30,7 +30,7 @@ const Board = React.createClass({
         if( this.state.playing ) {
             this.setState({world: process(this.state.world)});
         }
-        setTimeout(this.preAdvance, 1000/this.state.speed);
+        setTimeout(this.preAdvance, 500/this.state.speed);
     },
     componentDidMount() {
         this.advance();
@@ -38,17 +38,32 @@ const Board = React.createClass({
     togglePlay() {
         this.setState({playing: !this.state.playing});
     },
+    changeSpeed(evt) {
+        try {
+            let newSpeed = parseInt(evt.target.value);
+            if( newSpeed ) {
+                this.setState({speed: newSpeed});
+            }
+            else {
+                this.setState({playing: false});
+            }
+        }
+        catch(e) {
+            console.log('could not set speed from slider', e, evt);
+        }
+    },
     render() {
         let ot = this.state.settings.offsetTop || 0,
             ol = this.state.settings.offsetLeft || 0,
-            size = this.state.settings.cellSize || 10;
-        let cells = this.state.world.flatMap(function (row, y) {
+            size = this.state.settings.cellSize || 10,
+            cells = this.state.world.flatMap(function (row, y) {
             return row.map(function eachCell(value, x) {
                 let xc = ((x * size) + ol) + 'px',
                     yc = ((y * size) + ot) + 'px';
                 return <Cell key={'cell'+x+'-'+y} x={xc} y={yc} size={size} occupied={value} />;
             });
         }).toJS();
+        let displaySpeed = this.state.playing ? this.state.speed : 0;
 
         return <div id="panel">
             <div id="board">
@@ -56,6 +71,7 @@ const Board = React.createClass({
             </div>
             <div id="controls">
                 <button onClick={this.togglePlay}>{this.state.playing ? "pause" : "play"}</button>
+                <input onChange={this.changeSpeed} type="range" min="0" max="100" value={displaySpeed} id="speedslider" />
             </div>
         </div>;
     },
@@ -68,11 +84,9 @@ let settings = {
     board: {
         offsetTop:40,
         offsetLeft:10,
-        width:50,
-        height:20,
         cellSize:10,
     },
-    speed:5,
+    speed:1,
 };
 function generateWorld(w = 10, h = 10) {
     let grid = [];
@@ -94,7 +108,7 @@ function populateRandomly(state) {
         });
     });
 }
-let world = populateRandomly(generateWorld(100, 20));
+let world = populateRandomly(generateWorld(75, 75));
 
 ReactDOM.render(
     <Board settings={settings} world={world} />,