Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

javascript - How to generate a random starting position for the Game of Life?

ERROR:

SyntaxError: pathToFiles/Board.jsx: Unexpected token, expected , (32:20) while parsing file: pathToFiles/Board.jsx

CODE:

Board.jsx

generateRandomBoard() { 
        for (var i = 0; i < this.state.cells.length ; i++) { 
           var currentAlive;
           if(Math.random() < 0.5) {
               currentAlive = false;
           } 
           else {
               currentAlive = true;
           }
           this.setState({
               cells[i].alive : currentAlive 
           })
        }
    },

QUESTION:

How to generate a random starting position for the Game of ife ?

I tried the code above, but it did not work.

lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum


FULL CODE:

Game

var Game = createReactClass({

    getInitialState() {
        return {
            start: false
        }                    
    },

    handleStartClick() {
        this.setState({
            start: true
        })
    },

    handleStopClick() {
        this.setState({
            start: false
        })
    },

    render() {
        return (
            <div>
                <h1>React.js Game of Life</h1>
                <div className="buttons">
                    <button className="btn btn-danger" onClick={this.handleStopClick}>Stop</button>
                    <button className="btn btn-success" onClick={this.handleStartClick}>Start</button>
                </div>
                <Board start={this.state.start}/>
            </div>
        )
    }

});

Board

var Board = createReactClass({

getInitialState() {
    var array = [];
    for (var i = 0; i < 400; i++) {
        array.push(<Cell key={i} id={i} cells={array} />);
    }

    return {
        cells: array ,
        started: false,
        generations: 0
    };            

    this.generateRandomBoard();
},

 generateRandomBoard() {
    for (var i = 0; i < this.state.cells.length ; i++) {
       var currentAlive;
       if(Math.random() < 0.5) {
           currentAlive = false;
       }
       else {
           currentAlive = true;
       }

      cells[i].setState({
         alive: currentAlive
      })
    }
},

componentWillReceiveProps(nextProps) {

    var evolution;

    if(nextProps.start && this.state.started == false) {

      let evolution = setInterval(() => {
        this.state.cells.forEach( cell => cell.life() );
        this.state.cells.forEach( cell => cell.nextLife() );
        this.setState({
            generations: this.state.generations + 1
        });
      }, 500);

      this.setState({
        started: true,
        evolution
      });
    }

    else {
      clearInterval(this.state.evolution);
      this.setState({
        started: false
      })
      if (nextProps.delete) {
          this.state.cells.forEach( cell => cell.setState({alive: false}));
          this.state.cells.forEach( cell => cell.setState({nextAlive: false}));
          nextProps.stopClear();
          this.setState({
            generations: 0
          });
      }
    }

},

render() {

    var that = this;

    return (
        <div>
            <div className="board">
                {
                    this.state.cells.map(function(item, i) {
                        return <Cell key={i} id={i} cells={that.state.cells} start={that.props.start}/>
                    })
                } 
            </div>
            <div className="generations">Generations: {this.state.generations}</div>
        </div>
    );
}

});

Cell

var Cell = createReactClass ({

getInitialState() {
    return {
        alive: false,
        nextAlive: false,
    }                      
},

isAlive(r, c){

    var size = Math.sqrt(this.props.cells.length)

    if (r == -1) {
        r = size - 1
    }
    if (r == size) {
        r = 0
    }
    if (c == -1) {
        c = size - 1
    }
    if (c == size) {
        c = 0
    }
    var id = r * size + c
    return this.props.cells[id].state.alive

},

life() {

    var neighbours = 0
    var size = Math.sqrt(this.props.cells.length)
    var row = Math.floor( this.props.id / size )
    var col = this.props.id - row * size 

    if (this.isAlive(row - 1, col)) {
        neighbours++
    }
    if (this.isAlive(row - 1, col + 1)) {
        neighbours++
    }
    if (this.isAlive(row - 1, col - 1)) {
        neighbours++
    }
    if (this.isAlive(row, col + 1)) {
        neighbours++
    }
    if (this.isAlive(row, col - 1)) {
        neighbours++
    }
    if (this.isAlive(row + 1, col)) {
        neighbours ++
    } 
    if (this.isAlive(row + 1, col + 1)) {
        neighbours ++
    }   
    if (this.isAlive(row + 1, col - 1))  {
        neighbours ++   
    }

    this.state.nextState = false 

    if (this.state.alive){
      if( neighbours < 2) {
          this.setState ({
             nextAlive: false 
          })
      }
      if (neighbours > 3) {
          this.setState ({
             nextAlive: false 
          })    
      }
      if (neighbours == 3 || neighbours == 2) {
          this.setState ({
             nextAlive: true 
          })
      }
    }
    else{
      if (neighbours == 3) {
          this.setState ({
             nextAlive: true 
          })   
      }
    }
},

nextLife () {
    this.setState({
        alive: this.state.nextAlive
    })     
},

componentDidMount() {
    this.props.cells[this.props.id] = this;
},

toggleLife() {
    this.setState({
        alive: !this.state.alive
    })
},

render() {
    return (
       <div className={this.state.alive ? "cell alive" : "cell"} onClick={this.toggleLife}></div>
    );
} 

});

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like you have a syntax error in the function generateRandomBoard() of the Board component:

generateRandomBoard() {
  for (var i = 0; i < this.state.cells.length ; i++) {
    var currentAlive;
    if(Math.random() < 0.5) {
      currentAlive = false;
    }
    else {
       currentAlive = true;
    }

    // Buggy code from here ...
    //  this.setState({
    //      cells[i].alive : currentAlive
    //  })
    // ... to here

    // correct code from here ...
    cells[i].setState({
       alive: currentAlive
    })
    // ... to here
  }
}

Bellow is the complete correct code for the board:

var Board = React.createClass({

    getInitialState() {
        var array = [];
        for (var i = 0; i < 400; i++) {
            array.push(<Cell key={i} id={i} cells={array} start={this.props.start} />);
        }

        return {
            cells: array
        };
    },

    generateRandomBoard() {
        for (var i = 0; i < this.state.cells.length ; i++) {
           var currentAlive;
           if(Math.random() < 0.5) {
               currentAlive = false;
           }
           else {
               currentAlive = true;
           }

          cells[i].setState({
             alive: currentAlive
          })
        }
    },

    render() {

        var that = this;

        return (
            <div className="board">
                {
                    this.state.cells.map(function(item, i) {
                        return <Cell key={i} id={i} cells={that.state.cells} start={that.props.start}/>
                    })
                }
            </div>
        );
    }

});

The error you report is not very clear:

SyntaxError: pathToFiles/Board.jsx: Unexpected token, expected , (32:20) while parsing file: pathToFiles/Board.jsx

Yet (32:20) likely means line 32 column 20.

Maybe your current environment is not optimal. I personally use Webpack (for server-side compilation) with source maps (so that it tells me the location of my error): it's some hours to configure the first time, but it's very convenient once it works...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...