aimgame/src/App.jsx

105 lines
2.7 KiB
JavaScript

import React, { useState, useEffect } from "react"
import './Target.css';
function randomNumber() {
const num = Math.floor(Math.random() * 80);
return num;
}
function Header(props) {
return (
<header>
<span>Targets hit: {props.count} <br></br> Seconds left: {props.seconds}</span>
</header>
);
}
function Target(props) {
const [style, setStyle] = useState({
position: 'absolute',
top: '50%',
right: '50%'
});
return (
<button onClick={() => {
props.setCount(props.count + 1)
setStyle({
...style,
top: `${randomNumber()}%`,
right: `${randomNumber()}%`
})
}} style={style} className="target">PRESS</button>
);
}
function GameOver(props) {
return (
<div className="intro">
<h1>Finish!</h1>
<p>You hit {props.count} targets in the span of 30 seconds!</p>
<button onClick={() => props.setShow(false)}>Try again</button>
</div>
);
}
function Game(props) {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setTimeout(() => {
if (props.seconds > 0) {
props.setSeconds(props.seconds - 1);
} else {
clearTimeout(timer);
}
}, 1000);
});
if (props.seconds !== 0) {
return (
<div className="game">
<Header count={count} seconds={props.seconds} />
<div className="targets">
<Target count={count} setCount={setCount} />
</div>
</div>
);
}
return (
<GameOver setShow={props.setShow} count={count}/>
);
}
function Intro(props) {
const [temp, setTemp] = useState(30);
return (
<div className="intro">
<h1>Welcome to Aim Test</h1>
<p>Try to hit as many targets in the time limit</p>
<p><strong>Good Luck</strong></p>
<label>Enter time limit:
<input type="number" value={temp} onChange={(e) => setTemp(e.target.value)}/>
</label>
<br></br>
<button className="next-btn" onClick={() => {
props.setSeconds(temp);
props.setShow(true);
}}>Start Game</button>
</div>
);
}
export default function App() {
const [show, setShow] = useState(false);
const [seconds, setSeconds] = useState(30);
if (show) {
return <Game
setShow={setShow}
seconds={seconds}
setSeconds={setSeconds}
/>
}
return <Intro setSeconds={setSeconds} setShow={setShow}/>
}