I’m developing a simple game fight animation using react. To start the fight, I’ve a button with onClick
event: onClick={this.fight.bind(this)}
. Now I want to update some state variable in the anytime something changes like this:
import React, { Component } from 'react';
import { ProgressBar, Row, Col } from 'react-bootstrap';
const playerA = {
_id: 1,
name: "playerA name",
life: 100,
speed: 50,
}
const playerB = {
_id: 1,
name: "playerB name",
life: 100,
speed: 40,
}
export default class App extends Compornent {
constructor() {
super();
this.state={
playerA : playerA ,
playerB : playerB ,
aLife: 100,
bLife: 100,
};
this.fight = this.fight.bind(this);
};
fight(a,b){
lifeA=this.state.playerA.live;
lifeB=this.state.playerB.live;
speedA=this.state.playerA.speed;
speedB=this.state.playerB.speed;
dmg = 10
while (lifeA>0 && lifeB>0) {
if (speedA > speedb) {
lifeA = lifeA - dmg;
setTimeout(() => {
this.setState({ aLife: lifeA });
}, 1000);
speedB = speedB + 10;
} else {
lifeB = lifeB - dmg;
setTimeout(() => {
this.setState({ bLife: lifeA });
}, 1000);
speedA = speedA + 10;
}
return;
}
render() {
return (
<Row>
<ProgressBar bsStyle="success" now={this.state.aLife} srOnly/>
<ProgressBar bsStyle="success" now={this.state.bLife} srOnly/>
</Row>
<Row>
<Button bsStyle="danger" bsSize="large" onClick={this.fight.bind(this)}>Start Fight</Button>
</Row>
);
}
}
My expectation is to see the progress bars beeing update every 1 second. But it only updates once. When the fight funtion has finisched beein executed.