小能豆

如何将纯js翻译成react?

javascript

这是一个纯js项目,一个无网格的蛇游戏,我尝试在react js上重写它。 无网格贪吃蛇游戏,纯 html,js 我是新来的反应和前端顺便说一句

我只是不知道从哪里开始

var
  canv        = document.getElementById('mc'), // canvas
  ctx         = canv.getContext('2d'), // 2d context
  gs = fkp      = false, // game started && first key pressed (initialization states)
  speed = baseSpeed   = 3, // snake movement speed
  xv = yv       = 0, // velocity (x & y)
  px          = ~~(canv.width) / 2, // player X position
  py          = ~~(canv.height) / 2, // player Y position
  pw = ph       = 20, // player size
  aw = ah       = 20, // apple size
  apples        = [], // apples list
  trail       = [], // tail elements list (aka trail)
  tail        = 100, // tail size (1 for 10)
  tailSafeZone    = 20, // self eating protection for head zone (aka safeZone)
  cooldown      = false, // is key in cooldown mode
  score       = 0; // current score

例如这段代码,什么应该是 state(useStae, useRef) 而什么应该只是一个let变量?还有一个访问 DOM 的问题,比如document.addEventListener(‘keydown’,changeDirection);canv.getContext(‘2d’)


阅读 140

收藏
2024-02-27

共1个答案

小能豆

When converting the snake game to React, you’ll need to consider several factors, including managing state, handling user interactions, and rendering the game on the screen. Here’s a basic guideline on how to approach this:

  1. State Management: You’ll need to identify which variables represent the state of your game and manage them using React’s state management system (useState). Here’s a breakdown:
  2. gs and fkp: These variables control the game state. You can use a single state variable (gameState) to represent the game’s state, such as “running”, “paused”, or “game over”.
  3. speed, xv, yv, px, py, trail, tail, score: These variables represent various aspects of the game state, including the snake’s position, speed, trail, tail length, and score. You can manage them using state variables.
  4. apples: This represents the list of apples on the game board. You can manage it using a state variable.
  5. User Interactions: Handle user interactions, such as key presses, using React’s event handling system. You can use useEffect to add event listeners when the component mounts, and remove them when it unmounts.
  6. Rendering: Use React’s rendering system to render the game on the screen. You can use JSX to define the structure of your game’s UI, and update it dynamically based on the game state.

Here’s how you can refactor the provided code for use in a React component:

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

const SnakeGame = () => {
  const [gameState, setGameState] = useState('initialized');
  const [speed, setSpeed] = useState(3);
  const [xv, setXV] = useState(0);
  const [yv, setYV] = useState(0);
  const [px, setPX] = useState(Math.floor(canv.width) / 2);
  const [py, setPY] = useState(Math.floor(canv.height) / 2);
  const [trail, setTrail] = useState([]);
  const [tail, setTail] = useState(100);
  const [score, setScore] = useState(0);

  useEffect(() => {
    const handleKeyDown = (e) => {
      // Handle key presses
    };

    document.addEventListener('keydown', handleKeyDown);

    // Clean up event listener
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, []);

  // Other game logic and rendering code...

  return (
    // JSX for rendering the game
  );
};

export default SnakeGame;

In this refactored code:

  • Each game state variable is managed using useState.
  • The useEffect hook is used to add and remove event listeners for key presses.
  • Rendering logic and JSX would be placed in the return statement, where you define how the game should be displayed on the screen.

This is just a starting point, and you’ll need to fill in the logic for game mechanics, rendering, and user interactions based on the original JavaScript code. Additionally, you may want to break down the component into smaller components for better organization and reusability.

2024-02-27