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

[SOK-29] Start End State #22

Merged
merged 19 commits into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
b706fe6
Правки:
Timur233 Oct 11, 2024
336d951
Баг
Timur233 Oct 11, 2024
266d3a9
Состояние управлением игрой
Timur233 Oct 11, 2024
ef9ab0e
Добавил защиту от повторного запуска цикла игры
Timur233 Oct 11, 2024
be9d52e
Добавил защиту от залипания клавиш, при потери фокуса со страницы
Timur233 Oct 11, 2024
aabd4b7
Добавил обработку паузы на нажатие клавиши Escape
Timur233 Oct 11, 2024
7ffcacf
Добавил прелоадер в privateLayout
Timur233 Oct 11, 2024
10e3557
Добавил вин скрин
Timur233 Oct 11, 2024
cedc17a
Орефакторил код, по исправлял ошибки
Timur233 Oct 11, 2024
21450d0
Merge branch 'develop' of https://github.com/Timur233/falcon-tanks in…
Timur233 Oct 11, 2024
2624ff9
Merge branch 'develop' of https://github.com/Timur233/falcon-tanks in…
Timur233 Oct 11, 2024
db6b3aa
Правки по ревью
Timur233 Oct 12, 2024
7e4a653
Правки по ревью
Timur233 Oct 12, 2024
c6fe79b
Merge branch 'SOK-29_game-start-end-state' of https://github.com/Timu…
Timur233 Oct 12, 2024
43031a6
Merge
Timur233 Oct 15, 2024
27430da
Merge branch 'develop' of https://github.com/Timur233/falcon-tanks in…
Timur233 Oct 15, 2024
4cf4bd1
go
Timur233 Oct 15, 2024
6d5ae88
Merge branch 'develop' of https://github.com/Timur233/falcon-tanks in…
Timur233 Oct 15, 2024
695ab18
linter & format
Timur233 Oct 15, 2024
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
2 changes: 1 addition & 1 deletion packages/client/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/favicon.png" />
<link rel="manifest" href="/manifest.json">
<link rel="manifest" href="/manifest.json" />

<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
Expand Down
17 changes: 8 additions & 9 deletions packages/client/public/serviceWorker.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
const CACHE_NAME = 'cache-data-v1'
const urlsToCache = [
'/'
]
const urlsToCache = ['/']

const networkFirst = async (request) => {
const networkFirst = async request => {
const cache = await caches.open(CACHE_NAME)
try {
const response = await fetch(request)
const cachePutCondition = response && response.status === 200 && response.type === 'basic'
const cachePutCondition =
response && response.status === 200 && response.type === 'basic'
if (cachePutCondition) {
await cache.put(request, response.clone())
}
Expand All @@ -25,21 +24,21 @@ const networkFirst = async (request) => {
}
}

self.addEventListener('install', (event) => {
self.addEventListener('install', event => {
event.waitUntil(
caches
.open(CACHE_NAME)
.then((cache) => {
.then(cache => {
return cache.addAll(urlsToCache)
})
.then(() => self.skipWaiting())
.catch((err) => {
.catch(err => {
console.error('Cache installation failed:', err)
})
)
})

self.addEventListener('fetch', (event) => {
self.addEventListener('fetch', event => {
const { request } = event
const { url, method } = request

Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added packages/client/src/assets/images/win-screen.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 0 additions & 2 deletions packages/client/src/components/Game/Game.scss
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ $img_default-canvas-background: '@/assets/images/ground.png';
}

canvas {
border-radius: $border-radius--default;
box-shadow: 0 4px 8px rgba($c_black, 0.5);
background-image: url($img_default-canvas-background);
background-repeat: repeat;
}
Expand Down
132 changes: 74 additions & 58 deletions packages/client/src/components/Game/Game.tsx
Original file line number Diff line number Diff line change
@@ -1,113 +1,129 @@
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import './Game.scss'
import { initializeEnemies } from '@/components/Game/enemy'
import { PLAYER_DEFAULT_PARAMS } from '@/components/Game/player'
import { gameLoop } from '@/components/Game/gameLoop'
import {
handleKeyDown,
handleKeyUp,
handleKeyDownUp,
resetButtonsStates,
updatePlayerMovement,
} from '@/components/Game/controls'
import { ControlsProps, Obstacle } from '@/components/Game/gameTypes'
import { BtnStates, ControlsProps, Obstacle } from '@/components/Game/gameTypes'
import { initializeObstacle } from '@/components/Game/obstacle'
import { Modal } from '../common/Modal/Modal'

const livesUse = 3
type GamePropsType = {
lives: number
isGameStarted: boolean
isGamePaused: boolean
onDeath: (lives: number) => void
onGameOver: (isVictory: boolean) => void
onKeyDownUp: (btnStates: BtnStates) => void
}

export const Game = (props: GamePropsType) => {
const {
lives,
isGameStarted,
isGamePaused,
onDeath,
onGameOver,
onKeyDownUp,
} = props

// TODO: Нужно обработать победу в игре

export const Game: React.FC = () => {
const canvasRef = useRef<HTMLCanvasElement | null>(null)
const playerRef = useRef(PLAYER_DEFAULT_PARAMS)
const enemiesRef = useRef(initializeEnemies(5))
const obstaclesRef = useRef<Obstacle[]>(initializeObstacle())
const livesRef = useRef(livesUse)
const [gameStarted, setGameStarted] = useState(false)
const [isPaused, setIsPaused] = useState(false)
const livesRef = useRef(0)
const isPausedRef = useRef(false)
const [isGameOver, setIsGameOver] = useState(false)
const isStartedLoopRef = useRef(false)

const togglePause = useCallback(() => {
setIsPaused(prev => !prev)
isPausedRef.current = !isPausedRef.current // Обновляем ref для паузы
}, [])
const [isGameRunning, setIsGameRunning] = useState(false)
const [isGameOver, setIsGameOver] = useState(false)

const handleGameOver = useCallback(() => {
onGameOver(false)
setIsGameOver(true)
setIsPaused(true)
setIsGameRunning(false)

isPausedRef.current = true
}, [])
}, [onGameOver])

const loop = useCallback(() => {
if (!isPausedRef.current && !isGameOver && canvasRef.current) {
const context = canvasRef.current.getContext('2d')

if (context) {
const moveProps: ControlsProps = {
playerRef,
obstacles: obstaclesRef.current,
canvasWidth: canvasRef.current.width,
canvasHeight: canvasRef.current.height,
}
updatePlayerMovement(moveProps)

updatePlayerMovement(moveProps)
gameLoop(
context,
playerRef,
enemiesRef,
obstaclesRef.current,
livesRef,
onDeath,
handleGameOver
)
}

requestAnimationFrame(loop)
}
}, [isGameOver, handleGameOver, livesRef])
}, [isGameOver, onDeath, handleGameOver])

const startGame = useCallback(() => {
setIsGameRunning(true)
setIsGameOver(false)

isPausedRef.current = false
livesRef.current = lives
playerRef.current = PLAYER_DEFAULT_PARAMS
enemiesRef.current = initializeEnemies(5)
isStartedLoopRef.current = false
}, [lives])

useEffect(() => {
const handleKeyDownWrapper = (event: KeyboardEvent) =>
handleKeyDown(event.key)
const handleKeyUpWrapper = (event: KeyboardEvent) => handleKeyUp(event.key)
const handleKeyDownUpWrapper = (event: KeyboardEvent) => {
handleKeyDownUp(event.type, event.key, onKeyDownUp)
}

window.addEventListener('keydown', handleKeyDownWrapper)
window.addEventListener('keyup', handleKeyUpWrapper)
window.addEventListener('keydown', handleKeyDownUpWrapper)
window.addEventListener('keyup', handleKeyDownUpWrapper)
window.addEventListener('blur', resetButtonsStates)

return () => {
window.removeEventListener('keydown', handleKeyDownWrapper)
window.removeEventListener('keyup', handleKeyUpWrapper)
window.removeEventListener('keydown', handleKeyDownUpWrapper)
window.removeEventListener('keyup', handleKeyDownUpWrapper)
window.removeEventListener('blur', resetButtonsStates)
}
}, [])
}, [onKeyDownUp])

useEffect(() => {
if (gameStarted && !isPaused) {
if (isGameRunning && !isGamePaused && !isStartedLoopRef.current) {
isStartedLoopRef.current = true

requestAnimationFrame(loop)
}
}, [gameStarted, isPaused, loop])
}, [isGameRunning, isGamePaused, loop])

const startGame = () => {
setGameStarted(true)
setIsPaused(false)
isPausedRef.current = false
setIsGameOver(false)
livesRef.current = livesUse
playerRef.current = PLAYER_DEFAULT_PARAMS
enemiesRef.current = initializeEnemies(5)
}

return (
<div className="game-container">
<div className="lives">{`Жизни: ${livesRef.current.toString()}`}</div>
<canvas ref={canvasRef} width={800} height={600}></canvas>

{!gameStarted ? (
<button onClick={startGame}>Начать игру</button>
) : (
<button onClick={togglePause}>
{isPaused ? 'Продолжить' : 'Пауза'}
</button>
)}

<Modal show={isGameOver} onClose={() => setIsGameOver(false)}>
<h2>Игра окончена</h2>
<button onClick={startGame}>Заново</button>
</Modal>
</div>
)
useEffect(() => {
livesRef.current = lives
isPausedRef.current = isGamePaused

if (!isGamePaused) {
isStartedLoopRef.current = false
}

if (isGameStarted && isGameRunning === false) startGame()
}, [lives, isGameStarted, isGamePaused, isGameRunning, startGame])

return <canvas ref={canvasRef} width={800} height={600}></canvas>
}
55 changes: 42 additions & 13 deletions packages/client/src/components/Game/controls.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,46 @@
import { ControlsProps, KeyMap } from '@/components/Game/gameTypes'

import { ControlsProps, BtnStates } from '@/components/Game/gameTypes'
import { detectCollision } from '@/components/Game/collision'

const keyMap: KeyMap = {}
const btnStates: BtnStates = {
up: false,
down: false,
left: false,
right: false,
fire: false,
}

export const handleKeyDownUp = (
type: string,
key: string,
onKeyDownUp: (state: BtnStates) => void
) => {
const checkBtnState = (
aliases: string[],
type: string,
prevState: boolean
) => {
if (aliases.includes(key)) {
return type === 'keydown'
}

return prevState
}

btnStates.up = checkBtnState(['ArrowUp', 'w', 'ц'], type, btnStates.up)
btnStates.down = checkBtnState(['ArrowDown', 's', 'ы'], type, btnStates.down)
btnStates.left = checkBtnState(['ArrowLeft', 'a', 'ф'], type, btnStates.left)
btnStates.right = checkBtnState(
['ArrowRight', 'd', 'в'],
type,
btnStates.right
)
btnStates.fire = checkBtnState([' '], type, btnStates.fire)

// Обработчик нажатия клавиш
export const handleKeyDown = (key: string) => {
keyMap[key] = true
onKeyDownUp(btnStates)
}

// Обработчик отпускания клавиш
export const handleKeyUp = (key: string) => {
delete keyMap[key]
export const resetButtonsStates = () => {
Object.keys(btnStates).forEach((key: string) => (btnStates[key] = false))
}

// Функция для обновления позиции игрока на основе нажатых клавиш
Expand All @@ -21,19 +50,19 @@ export const updatePlayerMovement = (props: ControlsProps) => {
let newY = props.playerRef.current.y

// Определение направления движения
if (keyMap['ArrowUp'] || keyMap['w'] || keyMap['ц']) {
if (btnStates.up) {
props.playerRef.current.direction = { x: 0, y: 1 }
newY -= speed
}
if (keyMap['ArrowDown'] || keyMap['s'] || keyMap['ы']) {
if (btnStates.down) {
props.playerRef.current.direction = { x: 0, y: -1 }
newY += speed
}
if (keyMap['ArrowLeft'] || keyMap['a'] || keyMap['ф']) {
if (btnStates.left) {
props.playerRef.current.direction = { x: -1, y: 0 }
newX -= speed
}
if (keyMap['ArrowRight'] || keyMap['d'] || keyMap['в']) {
if (btnStates.right) {
props.playerRef.current.direction = { x: 1, y: 0 }
newX += speed
}
Expand Down
3 changes: 3 additions & 0 deletions packages/client/src/components/Game/gameLoop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const gameLoop = (
enemiesRef: React.MutableRefObject<Enemy[]>,
obstacles: Obstacle[],
livesRef: React.MutableRefObject<number>,
handleDeath: (lives: number) => void,
handleGameOver: () => void
) => {
clearCanvas(context)
Expand All @@ -41,6 +42,8 @@ export const gameLoop = (
() => resetPlayerPosition(playerRef),
() => respawnEnemies(enemiesRef)
)

handleDeath(livesRef.current)
}
})
}
7 changes: 6 additions & 1 deletion packages/client/src/components/Game/gameTypes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,13 @@ export interface Obstacle {
height: number
}

export interface KeyMap {
export interface BtnStates {
[key: string]: boolean
up: boolean
down: boolean
left: boolean
right: boolean
fire: boolean
}

export interface ControlsProps {
Expand Down
8 changes: 4 additions & 4 deletions packages/client/src/components/Game/player.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ export const HandlePlayerHit = (
) => {
const newLives = livesRef.current - 1

livesRef.current = newLives
resetPlayerPosition() // Сбрасываем позицию игрока
respawnEnemies() // Респавн врагов

if (newLives <= 0) {
handleGameOver()
} else {
livesRef.current = newLives
resetPlayerPosition() // Сбрасываем позицию игрока
respawnEnemies() // Респавн врагов
}
}
6 changes: 3 additions & 3 deletions packages/client/src/components/common/Modal/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ export const Modal = (props: ModalPropsType) => {

useEffect(() => {
const handleEscape = (event: KeyboardEvent) => {
event.preventDefault()
if (event.key === 'Escape' && show) {
event.preventDefault()

if (event.key === 'Escape') {
onClose()
}
}
Expand All @@ -29,7 +29,7 @@ export const Modal = (props: ModalPropsType) => {
return () => {
document.removeEventListener('keydown', handleEscape)
}
}, [onClose])
}, [onClose, show])

return ReactDOM.createPortal(
<div className={`modal ${show ? 'modal_show' : ''}`} onClick={onClose}>
Expand Down
Loading