react.js

리액트로 테트리스 만들어보자[5]

윤만석 2022. 10. 31. 15:00

https://orgin00.tistory.com/51

 

리액트로 테트리스 만들어보자[4]

https://orgin00.tistory.com/50 리액트로 테트리스 만들어보자[3] https://orgin00.tistory.com/49 리액트로 테트리스 만들어보자[2] https://orgin00.tistory.com/48 리액트로 테트리스 만들어보자[1] App.js 전..

orgin00.tistory.com

이번에는 블록이 한 라인에 꽉차면 사라지게 만들고, 게임오버를 만드는 등 게임 진행에 필요한 나머지 로직을 작성하겠습니다.

 useEffect(() => {
    const repeatMotion = (timeStamp) => {
      /*
      이전에 작성한 블록이 내려가는 로직입니다.
      if (timeStamp - cur > speed[data.stage]) {
        if (!validateMove(CurrentBlock, map, 0, 1)) {
          stack(CurrentBlock, map);
          ChangeBlocks();
        }

        setCur(timeStamp);

        reDraw();
      }*/
      
      //가득 찬 line이 있는지 확인합니다.
      setFilledlines(isLineFilled(map));
      //만약 존재하는경우,
      if (FilledLines.length > 0) {
      //시간을 체크합니다. timeForRemoved는 0으로 초기화 되어있습니다. 
        if (timeForRemoved === 0) {
          setTimeForRemoved(timeStamp);
        }

        if (timeStamp - timeForRemoved > 400) { //line이 가득찬 시점으로부터 0.4초 후
        //점수 +
          setData({
            ...data,
            score: data.score + CalScore(FilledLines.length),
            stage: CalStage(data.score + CalScore(FilledLines.length)),
          });
         //라인을 지웁니다
          lineRemove(FilledLines, map);
          //filledlines을 빈 array로 초기화합니다.
          setFilledlines([]);
          //마찬가지로 timeforremove 0으로 초기화
          setTimeForRemoved(0);
          reDraw();
        }
      }
		//현재 블록과 다음 블록이 같은경우, 다른 블록으로 바꿔주는 로직입니다. 물론 다시 같을 수 있습니다.
      if (
        JSON.stringify(CurrentBlock.type) === JSON.stringify(NextBlock.type)
      ) {
        setNextBlock(createRandomBlock());
        reDraw();
      }
      
      //게임 종료 로직입니다. 만약 map의 위에서 2번째 칸까지 블록이 차는경우 게임을 종료합니다.
      if (map[1].some((c) => c > 0)) {
        setOnGame(false);
        alert("game Over");
      }
      repeatRef.current = requestAnimationFrame(repeatMotion);
    };
    if (onGame) repeatRef.current = requestAnimationFrame(repeatMotion);

    return () => cancelAnimationFrame(repeatRef.current);
  });

기본적인 테트리스를 모두 완성했습니다.

 

이후에도 콤보기능, 블록이 아래로 내려온 위치를 보여주는 기능 등 넣어야 하는 기능이 많습니다.

그리고 node.js 웹소켓을 이용해 멀티플레이 기능도 만들어 보겠습니다.

 

https://github.com/Mansook/TetrisBot

 

GitHub - Mansook/TetrisBot: tetris

tetris. Contribute to Mansook/TetrisBot development by creating an account on GitHub.

github.com