iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0

Day12 是要來做偵測鍵盤輸入的彩蛋遊戲

資料

const SECRET_CODE: string = "wesbos";

  const [pressedKeys, setPressedKeys] = useState<string[]>([]);
  const [showSecret, setShowSecret] = useState<boolean>(false);

按鍵事件

  • 只比較最新輸入的幾個字(跟密碼長度相同)有無符合密碼
  const handleKeyUp = useCallback((e: KeyboardEvent<HTMLDivElement>) => {
    setPressedKeys((prev: string[]) => {
      const updatedKeys: string[] = [...prev, e.key].slice(-SECRET_CODE.length);

      if (updatedKeys.join("").includes(SECRET_CODE)) {
        setShowSecret(true);
        console.log("SECRET CODE ACTIVATED!");
      }
      return updatedKeys;
    });
  }, []);

畫面結構

  return (
    <div
      className="flex flex-col items-center justify-center min-h-screen bg-gray-100"
      tabIndex={0}
      onKeyUp={handleKeyUp}
      autoFocus
    >
      <h1 className="text-3xl font-bold mb-4">Key Sequence Detection</h1>
      <p className="text-lg mb-4">Type the secret code: 'wesbos'</p>

      <div className="bg-white p-6 rounded-lg shadow-md">
        <p className="text-xl mb-2">Pressed keys:</p>
        <div className="flex flex-wrap gap-2 mb-4">
          {pressedKeys.map((key: string, index: number) => (
            <span key={index} className="bg-blue-200 px-2 py-1 rounded">
              {key}
            </span>
          ))}
        </div>
      </div>
      {showSecret && (
        <div
          className="mt-8 bg-green-100 border-l-4 border-green-500 text-green-700 p-4 flex items-center"
          role="alert"
        >
          <p>Secret code activated! You found the easter egg!</p>
        </div>
      )}
    </div>
  );
}

DEMO

https://codesandbox.io/p/devbox/day12-key-sequence-detection-vfvg9j


上一篇
[Day11]_Custom-Video-Player
下一篇
[Day13]_Slide-in-on-Scroll
系列文
React30——用 React 探索 JavaScript30 的魅力30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言