Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor 6 #24

Open
wants to merge 1 commit into
base: refactor-5
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions src/components/App/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from "react";
import { MutableRefObject, useState } from "react";
import { GlobalContext } from "../../contexts";
import World from "../World";
import Player from "../Player";
Expand All @@ -12,6 +12,7 @@ import House from "../House";
import Fire from "../Fire";
import GameOver from "../GameOver";
import { GAME_STATES, MAX_HEALTH } from "../../constants";
import { Collider } from "../../utils";
import "./style.css";

/*
Expand All @@ -21,24 +22,27 @@ import "./style.css";
*/
export default function App() {
const [gameState, setGameState] = useState<GAME_STATES>(GAME_STATES.Game);
const [colliders, setColliders] = useState<MutableRefObject<Collider>[]>([]);
const [isCellarDoorOpen, setIsCellarDoorOpen] = useState(false);
const [isLeverUsed, setIsLeverUsed] = useState(false);
const [playerHealth, setPlayerHealth] = useState(MAX_HEALTH);

return (
<div className="App">
<GlobalContext.Provider
value={{ gameState: gameState, setGameState, playerHealth }}
value={{
gameState,
setGameState,
playerHealth,
setPlayerHealth,
colliders,
setColliders,
}}
>
{gameState === GAME_STATES.GameOver && <GameOver />}
<World />
<PlayerHealth />
<Player
top={328}
left={420}
onInteract={setIsLeverUsed}
onCollision={setPlayerHealth}
/>
<Player top={328} left={420} onInteract={setIsLeverUsed} />
<Npc left={1608} top={224} />
<CellarDoor isOpen={isCellarDoorOpen} left={528} top={272} />
<Lever
Expand Down
14 changes: 11 additions & 3 deletions src/components/Coin/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
import { useRef, FC } from "react";
import { TILE_SIZE, TILE_SETS } from "../../constants";
import { useAnimatedSprite } from "../../hooks";
import { useAnimatedSprite, useColliders } from "../../hooks";
import { Collider, ColliderType, Rect } from "../../utils";
import "./style.css";

const WIDTH = TILE_SIZE;
const HEIGHT = TILE_SIZE;
const TILE_X = 0;
const TILE_Y = 128;

type CoinProps = { left: number; top: number };

const Coin: FC<CoinProps> = ({ left, top }) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const collider = useRef<Collider>(
new Collider(new Rect(left, top, WIDTH, HEIGHT), ColliderType.Bonus)
);

useColliders(collider);

useAnimatedSprite({
canvasRef,
Expand All @@ -18,8 +26,8 @@ const Coin: FC<CoinProps> = ({ left, top }) => {
tileSet: TILE_SETS.Objects,
width: WIDTH,
height: HEIGHT,
tileX: 0,
tileY: 128,
tileX: TILE_X,
tileY: TILE_Y,
animationLength: 3,
animationSpeed: 100,
});
Expand Down
14 changes: 11 additions & 3 deletions src/components/Fire/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
import { useRef, FC } from "react";
import { TILE_SIZE, TILE_SETS } from "../../constants";
import { useAnimatedSprite } from "../../hooks";
import { useAnimatedSprite, useColliders } from "../../hooks";
import { Collider, ColliderType, Rect } from "../../utils";
import "./style.css";

const WIDTH = TILE_SIZE;
const HEIGHT = TILE_SIZE;
const TILE_X = 130;
const TILE_Y = 98;

type FireProps = { left: number; top: number };

const Fire: FC<FireProps> = ({ left, top }) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const collider = useRef<Collider>(
new Collider(new Rect(left, top, WIDTH, HEIGHT), ColliderType.Damage)
);

useColliders(collider);

useAnimatedSprite({
canvasRef,
Expand All @@ -18,8 +26,8 @@ const Fire: FC<FireProps> = ({ left, top }) => {
tileSet: TILE_SETS.Objects,
width: WIDTH,
height: HEIGHT,
tileX: 130,
tileY: 98,
tileX: TILE_X,
tileY: TILE_Y,
animationLength: 6,
animationSpeed: 125,
});
Expand Down
35 changes: 29 additions & 6 deletions src/components/Heart/index.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,48 @@
import { useRef, FC } from "react";
import { useRef, FC, useState } from "react";
import { TILE_SIZE, TILE_SETS } from "../../constants";
import { useAnimatedSprite } from "../../hooks";
import { useAnimatedSprite, useColliders } from "../../hooks";
import {
Collider,
ColliderType,
getRandomPosition,
Rect,
Vector,
} from "../../utils";
import "./style.css";

const WIDTH = TILE_SIZE;
const HEIGHT = TILE_SIZE;
const TILE_X = 0;
const TILE_Y = 96;

type HeartProps = { left: number; top: number };

const Heart: FC<HeartProps> = ({ left, top }) => {
const [position, setPosition] = useState<Vector>(new Vector(left, top));
const canvasRef = useRef<HTMLCanvasElement>(null);
const updatePosition = (c: Collider) => {
const newPosition = getRandomPosition(WIDTH, HEIGHT);
setPosition(newPosition);
c.rect.moveTo(newPosition.x, newPosition.y);
};
const collider = new Collider(
new Rect(position.x, position.y, WIDTH, HEIGHT),
ColliderType.Health,
updatePosition
);
const colliderRef = useRef<Collider>(collider);

useColliders(colliderRef);

useAnimatedSprite({
canvasRef,
left,
top,
left: position.x,
top: position.y,
tileSet: TILE_SETS.Objects,
width: WIDTH,
height: HEIGHT,
tileX: 0,
tileY: 96,
tileX: TILE_X,
tileY: TILE_Y,
animationLength: 3,
animationSpeed: 75,
});
Expand Down
1 change: 1 addition & 0 deletions src/components/Player/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export const TILE_X = 0;
export const TILE_Y = 8;
export const ANIMATION_LENGTH = 3;
export const SPEED = 4;
export const KNOCKBACK = SPEED * 12;

export const Input = {
Interact: [" ", "Enter"],
Expand Down
161 changes: 62 additions & 99 deletions src/components/Player/index.tsx
Original file line number Diff line number Diff line change
@@ -1,41 +1,35 @@
import { useEffect, useRef, FC, useContext } from "react";
import { GAME_STATES, TILE_SETS } from "../../constants";
import {
GAME_STATES,
MAX_HEALTH,
MIN_HEALTH,
TILE_SETS,
} from "../../constants";
import { GlobalContext } from "../../contexts";
import { Vector } from "../../utils";
import { ColliderType, Rect, Vector } from "../../utils";
import { ANIMATION_LENGTH, HEIGHT, Input, WIDTH } from "./constants";
import { drawFrame, getInputVector, move } from "./utils";
import { drawFrame, getInputVector, walk, knockback } from "./utils";
import "./style.css";

type PlayerProps = {
top: number;
left: number;
onInteract: (isOpen: boolean | ((wasOpen: boolean) => boolean)) => void;
onCollision: (health: number | ((prev: number) => number)) => void;
};

/*
* TODO:
* - move object specific interactions outside of Player
* - move player controls to global context
* - use input loop to remove keydown delay
* - create util function for collisions
*/
let invulnerable = false;
const Player: FC<PlayerProps> = ({ onInteract, onCollision, top, left }) => {
const Player: FC<PlayerProps> = ({ onInteract, top, left }) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const { setGameState, playerHealth } = useContext(GlobalContext);
const playerRect = useRef<Rect>(new Rect(left, top, WIDTH, HEIGHT));
const { setGameState, playerHealth, setPlayerHealth, colliders } =
useContext(GlobalContext);

useEffect(() => {
const fireCanvas = document.getElementById(
"fire-canvas"
) as HTMLCanvasElement | null;
const heartCanvas = document.getElementById(
"heart-canvas"
) as HTMLCanvasElement | null;
const coinCanvas = document.getElementById(
"coin-canvas"
) as HTMLCanvasElement | null;

const ctx = canvasRef.current?.getContext("2d");
if (!canvasRef.current || !ctx) {
return;
Expand Down Expand Up @@ -64,82 +58,32 @@ const Player: FC<PlayerProps> = ({ onInteract, onCollision, top, left }) => {
return;
}

if (playerHealth > 0) {
if (playerHealth < 4) {
if (
heartCanvas &&
parseInt(canvasRef.current.style.left || "0") + 6 <=
parseInt(heartCanvas.style.left || "0") + 16 &&
parseInt(canvasRef.current.style.left || "0") + 36 >=
parseInt(heartCanvas.style.left || "0") &&
parseInt(canvasRef.current.style.top || "0") + 36 <=
parseInt(heartCanvas.style.top || "0") + 32 &&
parseInt(canvasRef.current.style.top || "0") + 36 >=
parseInt(heartCanvas.style.top || "0") + 16
) {
onCollision((playerHealth) => Math.min(4, playerHealth + 1));
heartCanvas.remove();
}
colliders.forEach((collider) => {
if (!collider.current.rect.overlaps(playerRect.current)) {
return;
}

if (
coinCanvas &&
parseInt(canvasRef.current.style.left || "0") + 6 <=
parseInt(coinCanvas.style.left || "0") + 16 &&
parseInt(canvasRef.current.style.left || "0") + 36 >=
parseInt(coinCanvas.style.left || "0") &&
parseInt(canvasRef.current.style.top || "0") + 36 <=
parseInt(coinCanvas.style.top || "0") + 32 &&
parseInt(canvasRef.current.style.top || "0") + 36 >=
parseInt(coinCanvas.style.top || "0") + 16
collider.current.type === ColliderType.Health &&
playerHealth < MAX_HEALTH
) {
coinCanvas.remove();
}

if (Input.Interact.includes(event.key)) {
onInteract((wasOpen) => !wasOpen);
}
collider.current.onCollision();
setPlayerHealth(Math.min(MAX_HEALTH, playerHealth + 1));
} else if (collider.current.type === ColliderType.Bonus) {
collider.current.onCollision();
// TODO
} else if (
collider.current.type === ColliderType.Damage &&
!invulnerable
) {
collider.current.onCollision();

direction = getInputVector(event.key);
move(direction, canvasRef.current);
const velocity = knockback(direction, canvasRef.current!);
playerRect.current.moveBy(velocity.x, velocity.y);

if (
fireCanvas &&
!invulnerable &&
parseInt(canvasRef.current.style.left || "0") + 6 <=
parseInt(fireCanvas.style.left || "0") + 16 &&
parseInt(canvasRef.current.style.left || "0") + 36 >=
parseInt(fireCanvas.style.left || "0") &&
parseInt(canvasRef.current.style.top || "0") + 36 <=
parseInt(fireCanvas.style.top || "0") + 32 &&
parseInt(canvasRef.current.style.top || "0") + 36 >=
parseInt(fireCanvas.style.top || "0") + 16
) {
if (event.key === "w" || event.key === "ArrowUp") {
canvasRef.current.style.top = `${Math.min(
window.innerHeight,
parseInt(canvasRef.current.style.top || "0") + 48
)}px`;
} else if (event.key === "s" || event.key === "ArrowDown") {
canvasRef.current.style.top = `${Math.max(
0,
parseInt(canvasRef.current.style.top || "0") - 48
)}px`;
} else if (event.key === "a" || event.key === "ArrowLeft") {
canvasRef.current.style.left = `${Math.min(
window.innerWidth,
parseInt(canvasRef.current.style.left || "0") + 48
)}px`;
} else if (event.key === "d" || event.key === "ArrowRight") {
canvasRef.current.style.left = `${Math.max(
0,
parseInt(canvasRef.current.style.left || "0") - 48
)}px`;
}

onCollision((playerHealth) => Math.max(0, playerHealth - 1));
setPlayerHealth(Math.max(MIN_HEALTH, playerHealth - 1));
invulnerable = true;
canvasRef.current.style.filter = "brightness(6)";
canvasRef.current!.style.filter = "brightness(6)";

const interval = setInterval(() => {
if (!canvasRef.current) {
Expand All @@ -161,23 +105,42 @@ const Player: FC<PlayerProps> = ({ onInteract, onCollision, top, left }) => {
invulnerable = false;
}, 1500);
}
});

if (!keyPressed) {
keyPressed = true;
drawFrame(ctx, tileSet, direction, currentFrame);

setTimeout(() => {
keyPressed = false;
currentFrame =
currentFrame === ANIMATION_LENGTH ? 0 : currentFrame + 1;
}, 125);
}
} else {
if (playerHealth <= MIN_HEALTH) {
setGameState(GAME_STATES.GameOver);
return;
}

if (Input.Interact.includes(event.key)) {
onInteract((wasOpen) => !wasOpen);
}

direction = getInputVector(event.key);
const velocity = walk(direction, canvasRef.current);
playerRect.current.moveBy(velocity.x, velocity.y);

if (!keyPressed) {
keyPressed = true;
drawFrame(ctx, tileSet, direction, currentFrame);

setTimeout(() => {
keyPressed = false;
currentFrame =
currentFrame === ANIMATION_LENGTH ? 0 : currentFrame + 1;
}, 125);
}
};
};
}, [onInteract, onCollision, playerHealth, setGameState, top, left]);
}, [
onInteract,
setPlayerHealth,
playerHealth,
setGameState,
top,
left,
colliders,
]);

return (
<>
Expand Down
Loading