DEV Community

Tetragius
Tetragius

Posted on • Updated on

Create Arkanoid on React and Raxy

Create Store in Raxy

const initStore: IGame = {
  game: { width: 660, height: 450 },
  bricks: [{ x: 0, y: 0 }],
  base: { x: 0, y: 0 },
  bat: { x: 150, y: 52, height: 8, width: 150 },
  ball: { x: 150, y: 60, stick: true, a: Math.PI / 4, r: 15, k: 1 }
};

const instanse = raxyReact(initStore);
export const { store, transaction, subscribe, useRaxy } = instanse;
Enter fullscreen mode Exit fullscreen mode

Create main game service for collision check

import { subscribe } from "./store";
subscribe("update", (e) => {}); // subscribe to store update
Enter fullscreen mode Exit fullscreen mode

in codesandbox

Create score counter

import React from "react";
import { useRaxy } from "./store";

export default function Score() {
  const { state } = useRaxy((store) => ({
    score: store.bricks.filter((brick) => !brick.removed).length
  }));

  return <div className="score">Blocks : {state.score}</div>;
}
Enter fullscreen mode Exit fullscreen mode

Create ball

import React, { forwardRef } from "react";
import { useRaxy } from "./store";

const Ball = forwardRef((props, ref: any) => {
  const { state } = useRaxy((store) => ({ ball: store.ball }));

  return (
    <div
      ref={ref}
      className="ball"
      style={{ bottom: `${state.ball.y}px`, left: `${state.ball.x}px` }}
    />
  );
});

export default Ball;
Enter fullscreen mode Exit fullscreen mode

And then create Brick component with colllision check in codesandbox

Finally create Game component that binds all the others in codesandbox

Pay special attention to the code block

  const { store, state } = useRaxy(
    (store) => ({
      bricks: store.bricks,
      game: store.game
    }),
    { game: { ignoreTimeStamp: true }, bricks: { ignoreTimeStamp: true } }
  );
Enter fullscreen mode Exit fullscreen mode
{ game: { ignoreTimeStamp: true }, bricks: { ignoreTimeStamp: true } }
Enter fullscreen mode Exit fullscreen mode

This part says - do not redraw the component when changing children in the store.
Thus, when the ball moves and collisions, only score, a bat, a ball and a block with which it collided will be redrawn

Top comments (0)