skip to Main Content

heres a pure js project here, a grid-less snake game and i try to rewrite it on react js.
grid-less snake game, pure html,js
im new to react and front end btw

i just dont know where to start

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

For example this piece of code, what should be state(useStae, useRef) and what should be just a let variable?
Also an issue with accessing DOM, like document.addEventListener(‘keydown’, changeDirection); or canv.getContext(‘2d’)

2

Answers


  1. First to capture keys:
    https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code

    For React you should capture keys like this (If you want, you can use a ready hook, see)

        const changeDirection = (e) => {
            // some code
        }
    
        useEffect(() => {
    
            window.addEventListener('keydown', changeDirection)
    
            return () => {
                window.removeEventListener('keydown', changeDirection)
            }
    
        }, [])
    

    You can make state assignments for continuously variable ones. For example velocity

    const [velocity, setVelocity] = useState({ x: 0, y: 0 })
    

    Loop

        const loop = () => {
            // some code
        }
    
        useEffect(() => {
    
            const interval = setInterval(loop, 1000 / 60)
    
            return () => {
                clearInterval(interval)
            }
    
        }, []);
    

    I think it would be useful for me to tell you this much. I think it will handle the rest 🙂

    Login or Signup to reply.
  2. to be upfront, I don’t know how suitable such a project for learning react is. I would suggest that you build a simple to-do app, all of the key concepts can be explored easily by that. Also, I would suggest that you, read the React docs, they are known to be fantastic and will spare you major headaches / possible footguns.

    –> https://react.dev/learn

    They have a nice little Tutorial on there with Tic-Tac-Toe!

    To give you still some general hints regarding your question:

    1. React treats state in a special rendering model. Those hooks that you described: "useState" and "useRef" both preserve the state. Still, they essentially behave differently when being changed. "useState" will trigger a rerender of all components consuming that state, whereas "useRef" will not trigger a rerender. When we think in terms of the Tic-Tac-Toe game, we might need to useState for our different Fields on which the user can click. Once clicked we can set for example our state to "Cross" and inside that Field we can either display a Cross icon or a Circle icon depending on the state we now read. When we think about forms, on the other hand, we often only need to preserve the state for an API call. In this case, we don’t need any rerenders for the UI, but only the access to the state in our function that will be triggered by submitting the form with its various inputs. I again encourage you strongly to read about those hooks on the official Docs!

    2. When it comes to DOM interaction: React introduces a new syntax that is referred to JSX. It allows to write HTML markup inside JS Files and provides very handy wrappers for attaching event listeners. Usually, we would create a dom node and attach a listener to it, in many cases we would have to append this node logically to the parent to bring it into its place.

    Say we want to add a container as a sibling to our button in this markup:

      <div id="container">
        <button id="myButton">Click me</button>
      </div>
    

    In order for this to work in plain JS we would need to do this:

    
    document.getElementById('myButton').addEventListener('click', function() {
        // Create a new container element
        const newContainer = document.createElement('div');
        newContainer.textContent = 'New Container';
    
        // Append the new container to the app container
        document.getElementById('app').appendChild(newContainer);
      });
    
    

    The same can be achieved in react in much less and easier to reason about code:

    const App = () => {
      const [showNewContainer, setShowNewContainer] = useState(false);
    
      const handleClick = () => {
        // Toggle the state to show/hide the new container
        setShowNewContainer(!showNewContainer);
      };
    
      return (
        <div id="container">
          <button onClick={handleClick}>Click me</button>
          // use short circuit evaluation to show or hide the container
          {showNewContainer && <div id="newContainer">New container</div>}
        </div>
      );
    };
    

    I hope that gives you a general hint where this will lead, again please take time to read the docs, after that things will get much easier 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search