用 React18 构建点击计分小游戏-编写 ClickGame 组件

src/ClickGame.js 文件中,编写如下代码:

import React, { useState, useEffect } from "react";

function ClickGame() {
  const [score, setScore] = useState(0);
  const [timeLeft, setTimeLeft] = useState(10); // 游戏时长为 10 秒
  const [isGameRunning, setIsGameRunning] = useState(false);

  useEffect(() => {
    let timer;
    if (isGameRunning && timeLeft > 0) {
      timer = setInterval(() => {
        setTimeLeft((prevTime) => prevTime - 1);
      }, 1000);
    } else if (timeLeft === 0) {
      setIsGameRunning(false);
    }
    return () => clearInterval(timer);
  }, [isGameRunning, timeLeft]);

  const startGame = () => {
    setScore(0);
    setTimeLeft(10);
    setIsGameRunning(true);
  };

  const handleClick = () => {
    if (isGameRunning) {
      setScore((prevScore) => prevScore + 1);
    }
  };

  return (
    <div style={styles.container}>
      <h1 style={styles.title}>点击计分游戏</h1>
      <p>剩余时间: {timeLeft} 秒</p>
      <p>得分: {score}</p>
      {isGameRunning ? (
        <button style={styles.gameButton} onClick={handleClick}>
          点我得分!
        </button>
      ) : (
        <button style={styles.startButton} onClick={startGame}>
          开始游戏
        </button>
      )}
      {!isGameRunning && timeLeft === 0 && <p>游戏结束!最终得分:{score}</p>}
    </div>
  );
}

const styles = {
  container: {
    textAlign: "center",
    fontFamily: "Arial, sans-serif",
    marginTop: "50px",
  },
  title: {
    fontSize: "2rem",
    color: "#333",
  },
  gameButton: {
    padding: "10px 20px",
    fontSize: "1.5rem",
    backgroundColor: "#4CAF50",
    color: "white",
    border: "none",
    borderRadius: "5px",
    cursor: "pointer",
  },
  startButton: {
    padding: "10px 20px",
    fontSize: "1.5rem",
    backgroundColor: "#008CBA",
    color: "white",
    border: "none",
    borderRadius: "5px",
    cursor: "pointer",
  },
};

export default ClickGame;
上一篇:R语言基础入门详解


下一篇:Vue 3与TypeScript集成指南:构建类型安全的前端应用