import React, { Component } from "react";
import "./Game.css";
class Game extends Component {
static defaultProps = {
list: ["rock", "paper", "scissors"]
};
constructor(props) {
super(props);
this.state = {
play: false,
random: null,
user: null,
winner: false
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleSubmit(event) {
event.preventDefault();
this.setState({
play: !this.state.play
});
}
handleClick(event) {
//paper beats Rock
//scissors beats Paper
// rock beats scissors
// 1 > 0
// 2 > 1
//0 > 2
if (this.state.winner) {
return;
}
let hasWon;
let inputIndex = this.props.list.indexOf(event.target.value);
let ranIndex = this.props.list.indexOf(this.state.random);
if (
(inputIndex === 1 && ranIndex === 0) ||
(ranIndex === 1 && inputIndex === 0)
) {
hasWon = true;
// return this.props.list[1];
} else if (
(inputIndex === 2 && ranIndex === 1) ||
(ranIndex === 2 && inputIndex === 1)
) {
hasWon = true;
} else if (
(inputIndex === 0 && ranIndex === 2) ||
(ranIndex === 0 && inputIndex === 2)
) {
hasWon = true;
}
console.log(this.props.list.indexOf(this.state.random));
this.setState({
user: event.target.value,
random: this.props.list[
Math.floor(Math.random() * this.props.list.length)
],
winner: hasWon
});
}
render() {
let game;
if (this.state.play) {
game = (
<div className="Game-userButtons">
<button
onClick={this.handleClick}
name={this.state.user}
value="rock"
>
Rock
</button>
<button
onClick={this.handleClick}
name={this.state.user}
value="paper"
>
Paper
</button>
<button
onClick={this.handleClick}
name={this.state.user}
value="scissors"
>
Scissor
</button>
<button>Play Again! </button>
</div>
);
} else {
game = (
<div>
<form onSubmit={this.handleSubmit}>
<button>Play </button>
</form>
</div>
);
}
return (
<div>
<h1>Rock, paper, scissors </h1>
<div className="players">
<div className="user">
<i className={`fas fa-hand-${this.state.user}`}></i>
</div>
<div className="robot">
<i className={`fas fa-hand-${this.state.random}`}></i>
</div>
</div>
{game}
</div>
);
}
}
export default Game;
Я пытаюсь определить победителя игры «камень, ножницы, бумага», сравнивая индексы пользователя и случайно сгенерированный.В handleClick () я написал потенциальные условия для победы в игре и индексы, которые переводят в потенциальные выигрыши.Когда я console.log индексирует this.state.random, создается впечатление, что состояние, которое отображается, находится на один шаг от состояния, подлежащего консоли.Итак, условия работают, но визуальный не имеет никакого смысла.Как я могу это исправить?Спасибо за ваше время!