开满天机
人类玩家选择一步棋后,不要立即让 CPU 选择一步棋。实现componentDidUpdate生命周期函数并将CPU的选择逻辑移到那里。这也需要移动对获胜逻辑的检查。/*function that handles the user choice*/handleClick = ( choiceName, choiceImage, choiceBorderColor, choiceExtraBorderColor) => () => { this.setState({ onScreen: false, choiceName, choiceImage, choiceBorderColor, choiceExtraBorderColor });};一旦人类玩家选择了一个动作,就获得房子的随机动作,但不要立即将状态更新排入队列,而是稍后使用进入setTimeout更新状态。仅当两个玩家都选择了移动但结果尚未计算并存储在状态中时才检查胜利。componentDidUpdate(prevProps, prevState) { if ( prevState.choiceName !== this.state.choiceName && this.state.choiceName ) { function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } const index = getRandomInt(3); setTimeout(() => { this.setState({ houseChoice: index }); }, 2000); } if ( this.state.choiceName && [0, 1, 2].includes(this.state.houseChoice) && // We want 0 to be truthy :) !this.state.results ) { const results = this.getResults( this.state.choiceName, this.state.houseChoice ).toUpperCase(); this.setState({ results: results }); /*****************calling setScore()********************/ if (results === "WIN") { this.props.setScore(1); } else if (results === "LOSE") { this.props.setScore(-1); } else { this.props.setScore(0); } }}有条件地渲染“等待 CPU”UI<h4 className="result-title"> {this.state.houseChoice === "" ? "THE HOUSE CHOOSING" : "THE HOUSE PICKED"}</h4>{this.state.houseChoice === "" ? ( <div>...</div>) : this.state.houseChoice === 0 ? ( /*1*/ <div className="elem-container result-container" style={{ borderColor: "hsl(230, 89%, 62%)", color: "hsl(230, 89%, 65%)" }} > <img src={paper} className="choice-image" alt="img" /> </div>) : this.state.houseChoice === 1 ? ( /*2*/ <div className="elem-container result-container" style={{ borderColor: "hsl(39, 89%, 49%)", color: "hsl(40, 84%, 53%)" }} > <img src={scissors} className="choice-image" alt="img" /> </div>) : ( /*3*/ <div className="elem-container result-container" style={{ borderColor: "hsl(349, 71%, 52%)", color: "hsl(349, 70%, 56%)" }} > <img src={rock} className="choice-image" alt="img" /> </div>)}有条件地渲染结果并重试按钮。<div className="final-result-container"> {this.state.results && ( <> <h1 className="bold">YOU {this.state.results}</h1> <TryAgain onClick={this.handleTryAgainClick} /> </> )}</div>再次玩时不要忘记重置所有状态handleTryAgainClick() { this.setState({ onScreen: true, choiceName: "", choiceImage: "", choiceBorderColor: "", choiceExtraBorderColor: "", houseChoice: "", results: "" });}