我正在尝试在React中构建一个乒乓球比分跟踪器。规则是你可以看到两个名字,和他们的分数。有一个加号按钮和一个减号按钮来纠正两个玩家的分数。
当一名球员得到21分后,它应该显示该球员是赢家。获胜的球员总是要以2分的优势获胜。当它是20-20时,获胜点将是22,等等。会不会太乱了?
import { useState } from "react";
import "./App.css";
import Player from "./components/Player";
function App() {
const [winner, setWinner] = useState(null);
const [gameStatus, setGameStatus] = useState(true);
const [currentPlayer, setCurrentPlayer] = useState("1");
const [score, setScore] = useState([0, 0]);
// function gamestatusHandler() {
// setGameStatus(false);
// }
function inchandler(id) {
const scoreCpy = score.slice();
// console.log(scoreCpy);
if (scoreCpy[0] >= winningscore || scoreCpy[1] >= winningscore) {
return;
}
if (gameStatus) {
const scorearr = score.map((el, i) => {
if (i === +id) return el + 1;
else return el;
});
setScore(scorearr);
checkWinner();
setCurrentPlayer(`${id === "0" ? "2" : "1"}`);
}
}
function dechandler(id) {
const scoreCpy = score.slice();
if (scoreCpy[0] === 0 || scoreCpy[1] === 0) {
return;
}
if (id === "0") {
setScore([scoreCpy[0] - 1, scoreCpy[1]]);
} else if (id === "1") {
setScore([scoreCpy[0], scoreCpy[1] - 1]);
}
}
let winningscore;
function checkWinner() {
winningscore = score[0] >= 10 && score[1] >= 10 ? 12 : 11;
console.log(winningscore);
if (score[0] >= winningscore - 1 && score[0] - score[1] > 1) {
setWinner("Player 1");
setGameStatus(false);
}
if (score[1] >= winningscore - 1 && score[1] - score[0] > 1) {
setWinner("Player 2");
setGameStatus(false);
}
}
// function winnerHandler() {
// setWinner("player 1");
// }
return (
<>
{gameStatus && <div>Current Player {+currentPlayer}</div>}
{gameStatus && (
<>
{" "}
<Player
id="0"
score={score[0]}
Oninchandler={inchandler}
Ondechandler={dechandler}
/>
<Player
id="1"
score={score[1]}
Oninchandler={inchandler}
Ondechandler={dechandler}
/>
</>
)}
{!gameStatus && <div>Winner is {winner}</div>}
</>
);
}
export default App;
玩家
const Player = (props) => {
// console.log(props.score[+props.id])
return (
<>
<div>
Player {`#${+props.id + 1}`} {props.score}
</div>
<button onClick={() => props.Oninchandler(props.id)}>+</button>
<button onClick={() => props.Ondechandler(props.id)}>-</button>
</>
);
};
export default Player;
1条答案
按热度按时间2skhul331#
我觉得你写的有些东西根本不需要。你只需要检查一下比赛现在是否正在进行。返回如果游戏不进行。然后根据按钮进行递增或递减,并在单击按钮后执行简单的检查是否有赢家。
我还假设,如果参与人1有21分,参与人2有20分,如果你把参与人2的分数减1,参与人1应该是赢家。如果您不希望这样,请从
decrementHandler(id)
函数中删除该checkWinner()