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 all 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
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
176 changes: 105 additions & 71 deletions packages/client/src/components/Game/Game.tsx
Original file line number Diff line number Diff line change
@@ -1,48 +1,71 @@
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import './Game.scss'
import {
initializeCampanyEnemies,
initializeRandomEnemies,
} from '@/components/Game/enemy'
import { PLAYER_DEFAULT_PARAMS } from '@/components/Game/player'
import { gameLoop } from '@/components/Game/gameLoop'
import { handleKeyDown, handleKeyUp } from '@/components/Game/controls'
import { AbstractEntity, Effect, Obstacle } from '@/components/Game/gameTypes'
import {
AbstractEntity,
Effect,
Obstacle,
BtnStates,
} from '@/components/Game/gameTypes'
import {
initializeCompanyMapObstacle,
initializeRandomObstacle,
} from '@/components/Game/obstacle'
import { Modal } from '../common/Modal/Modal'
import { handleKeyDownUp, resetButtonsStates } from '@/components/Game/controls'

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

const livesUse = 3
export const Game = (props: GamePropsType) => {
const {
lives,
isGameStarted,
isCompanyStarted,
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(initializeRandomEnemies(5))
const bulletsRef = useRef<AbstractEntity[]>([])
const obstaclesRef = useRef<Obstacle[]>(initializeRandomObstacle(20))
const effectsRef = useRef<Effect[]>([])
const livesRef = useRef(livesUse)
const [gameStarted, setGameStarted] = useState(false)
const [isPaused, setIsPaused] = useState(false)
const livesRef = useRef(lives)
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) {
gameLoop(
context,
Expand All @@ -53,76 +76,87 @@ export const Game: React.FC = () => {
obstaclesRef,
effectsRef,
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 = initializeRandomEnemies(5)
obstaclesRef.current = initializeRandomObstacle(20)
isStartedLoopRef.current = false
}, [lives])

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

isPausedRef.current = false
livesRef.current = lives
playerRef.current = PLAYER_DEFAULT_PARAMS
enemiesRef.current = initializeCampanyEnemies()
obstaclesRef.current = initializeCompanyMapObstacle()
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 = initializeRandomEnemies(5)
obstaclesRef.current = initializeRandomObstacle(20)
}
useEffect(() => {
livesRef.current = lives
isPausedRef.current = isGamePaused

const startCompany = () => {
setGameStarted(true)
setIsPaused(false)
isPausedRef.current = false
setIsGameOver(false)
livesRef.current = livesUse
playerRef.current = { ...PLAYER_DEFAULT_PARAMS }
enemiesRef.current = initializeCampanyEnemies()
obstaclesRef.current = initializeCompanyMapObstacle()
}

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={startCompany}>Начать компанию</button>
</>
) : (
<button onClick={togglePause}>
{isPaused ? 'Продолжить' : 'Пауза'}
</button>
)}

<Modal show={isGameOver} onClose={() => setIsGameOver(false)}>
<h2>Игра окончена</h2>
<button onClick={startGame}>Новая игра</button>
<button onClick={startCompany}>Компания</button>
</Modal>
</div>
)
if (!isGamePaused) {
isStartedLoopRef.current = false
}

if (isGameRunning === false) {
if (isGameStarted) {
startGame()
} else if (isCompanyStarted) {
startCompany()
}
}
}, [
lives,
isGameStarted,
isGamePaused,
isGameRunning,
startGame,
isCompanyStarted,
startCompany,
])

return <canvas ref={canvasRef} width={800} height={600}></canvas>
}
58 changes: 44 additions & 14 deletions packages/client/src/components/Game/controls.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { ControlsProps } from '@/components/Game/gameTypes'
import { BtnStates, ControlsProps } from '@/components/Game/gameTypes'
import { detectCollision } from '@/components/Game/collision'
import { createBullet } from '@/components/Game/bullet'

const btnStates: BtnStates = {
up: false,
down: false,
left: false,
right: false,
fire: false,
}
let pressedKeys: string[] = []
let shootPressed = false // Флаг для стрельбы
let lastShotTime = 0 // Время последнего выстрела
Expand Down Expand Up @@ -36,24 +43,47 @@ const VECTORS: Record<Action, Vector> = {
[Action.Shoot]: { x: 0, y: 0 },
}

export const handleKeyDown = (key: string) => {
if (!pressedKeys.includes(key)) {
pressedKeys.push(key)
}
const checkPressedKeys = (keys: string[]): BtnStates => {
keys.forEach((key: string) => {
btnStates.up = ACTION_CONTROLS[Action.MoveUp].includes(key)
btnStates.down = ACTION_CONTROLS[Action.MoveDown].includes(key)
btnStates.left = ACTION_CONTROLS[Action.MoveLeft].includes(key)
btnStates.right = ACTION_CONTROLS[Action.MoveRight].includes(key)
btnStates.fire = ACTION_CONTROLS[Action.Shoot].includes(key)
})

// Устанавливаем флаг, если нажата клавиша пробела (стрельба)
if (key === ' ') {
shootPressed = true
}
return btnStates
}

export const handleKeyUp = (key: string) => {
pressedKeys = pressedKeys.filter(currentKey => currentKey !== key)
export const handleKeyDownUp = (
type: string,
key: string,
onKeyDownUp: (state: BtnStates) => void
) => {
const isKeydown = type === 'keydown'

if (isKeydown) {
if (!pressedKeys.includes(key)) {
pressedKeys.push(key)

if (key === ' ') {
shootPressed = true
}
}
} else {
pressedKeys = pressedKeys.filter(currentKey => currentKey !== key)

// Сбрасываем флаг, если клавиша пробела отпущена
if (key === ' ') {
shootPressed = false
if (key === ' ') {
shootPressed = false
}
}

onKeyDownUp(checkPressedKeys(pressedKeys))
}

export const resetButtonsStates = () => {
pressedKeys = []
shootPressed = false
}

const getActionControlByKey = (key: string): Action | null => {
Expand Down
1 change: 1 addition & 0 deletions packages/client/src/components/Game/enemy.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import React from 'react'
import { getRandomEdgePosition } from './utils'
import { AbstractEntity, Enemy, Obstacle } from '@/components/Game/gameTypes'
import { createBullet } from '@/components/Game/bullet'
Expand Down
12 changes: 11 additions & 1 deletion packages/client/src/components/Game/gameLoop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export const gameLoop = (
obstaclesRef: React.MutableRefObject<Obstacle[]>,
effectsRef: React.MutableRefObject<Effect[]>,
livesRef: React.MutableRefObject<number>,
handleDeath: (lives: number) => void,
handleGameOver: () => void
) => {
clearCanvas(context)
Expand Down Expand Up @@ -112,6 +113,8 @@ export const gameLoop = (
// Проверка на окончание игры
if (livesRef.current <= 0) {
handleGameOver()
} else {
handleDeath(livesRef.current)
}
}
})
Expand All @@ -121,6 +124,13 @@ export const gameLoop = (
)

if (collidedEnemy) {
HandlePlayerHit(livesRef, playerRef, enemiesRef, canvasRef, handleGameOver)
HandlePlayerHit(
livesRef,
playerRef,
enemiesRef,
canvasRef,
handleGameOver,
handleDeath
)
}
}
9 changes: 9 additions & 0 deletions packages/client/src/components/Game/gameTypes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ export interface Effect {
animation: AnimationParams
}

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

export interface ControlsProps {
playerRef: React.MutableRefObject<AbstractEntity>
bulletsRef: React.MutableRefObject<AbstractEntity[]>
Expand Down
6 changes: 3 additions & 3 deletions packages/client/src/components/Game/player.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ export const HandlePlayerHit = (
playerRef: React.MutableRefObject<AbstractEntity>,
enemiesRef: React.MutableRefObject<Enemy[]>,
canvasRef: React.MutableRefObject<HTMLCanvasElement | null>,
handleGameOver: () => void
handleGameOver: () => void,
handleDeath: (lives: number) => void
) => {
livesRef.current -= 1

if (livesRef.current <= 0) {
handleGameOver()
} else {
resetPlayerPosition(playerRef)
respawnEnemies(enemiesRef, canvasRef)
handleDeath(livesRef.current)
}
}
Loading
Loading