Derur's picture
Upload 14 files
3bb8cb9 verified
<!DOCTYPE html>
<html>
<head>
<title>Pong Game</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
background: #1a1a1a;
margin: 0;
min-height: 100vh;
font-family: Arial, sans-serif;
}
canvas {
border: 2px solid #fff;
margin: 20px 0;
}
.menu {
margin: 20px;
text-align: center;
}
button {
padding: 10px 20px;
margin: 5px;
cursor: pointer;
background: #4CAF50;
border: none;
color: white;
border-radius: 4px;
font-size: 16px;
}
.game-over {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 48px;
font-weight: bold;
color: white;
text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
animation: zoom 1s infinite;
z-index: 1000;
text-align: center;
}
@keyframes zoom {
0% { transform: translate(-50%, -50%) scale(1); }
50% { transform: translate(-50%, -50%) scale(1.2); }
100% { transform: translate(-50%, -50%) scale(1); }
}
#fullscreenBtn {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
z-index: 1000;
}
.score {
position: fixed;
top: 20px;
font-size: 40px;
color: white;
transition: all 0.3s ease;
}
.score.changed {
transform: scale(1.5);
color: #4CAF50;
}
#leftPlayerName {
left: 20px;
}
#rightPlayerName {
right: 20px;
}
#playerNames {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0,0,0,0.8);
padding: 20px;
border-radius: 10px;
text-align: center;
color: white;
z-index: 1001;
}
#playerNames input {
margin: 10px;
padding: 8px;
font-size: 16px;
width: 200px;
}
.player-name {
position: fixed;
top: 80px;
font-size: 24px;
color: white;
text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
}
.goal-effect {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(255,255,255,0.3);
animation: blink 0.5s linear 2;
pointer-events: none;
display: none;
}
@keyframes blink {
0%, 100% { opacity: 0; }
50% { opacity: 1; }
}
</style>
</head>
<body>
<div id="playerNames">
<h2>Введите имена игроков</h2>
<input type="text" id="leftPlayer" placeholder="Левый игрок">
<input type="text" id="rightPlayer" placeholder="Правый игрок"><br>
<button onclick="startGame()">Начать игру</button>
</div>
<div class="goal-effect" id="goalEffect"></div>
<div class="player-name" id="leftPlayerName"></div>
<div class="player-name" id="rightPlayerName"></div>
<div class="score" id="leftScore" style="left: 20px;">0</div>
<div class="score" id="rightScore" style="right: 20px;">0</div>
<button id="fullscreenBtn" onclick="toggleFullscreen()"></button>
<canvas id="gameCanvas" width="800" height="500"></canvas>
<div id="gameOver" class="game-over"></div>
<!-- Звуковые файлы -->
<audio id="paddleSound" src="paddle_hit.wav"></audio>
<audio id="obstacleSound" src="obstacle_hit.wav"></audio>
<audio id="winSound" src="win_sound.wav"></audio>
<audio id="goalSound" src="goal.wav"></audio>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const gameOverElement = document.getElementById('gameOver');
const playerNamesDiv = document.getElementById('playerNames');
const leftPlayerNameElement = document.getElementById('leftPlayerName');
const rightPlayerNameElement = document.getElementById('rightPlayerName');
const leftScoreElement = document.getElementById('leftScore');
const rightScoreElement = document.getElementById('rightScore');
// Аудио элементы
const paddleSound = document.getElementById('paddleSound');
const obstacleSound = document.getElementById('obstacleSound');
const winSound = document.getElementById('winSound');
const goalSound = document.getElementById('goalSound');
// Игровые переменные
let gameMode = '';
let isPlaying = false;
let obstacles = [];
const obstacleTypes = ['paddle', 'ball', 'random'];
let leftPlayerName = 'Левый игрок';
let rightPlayerName = 'Правый игрок';
// Таймеры для препятствий
let lastObstacleTime = 0;
const OBSTACLE_INTERVAL = 5000;
const OBSTACLE_LIFETIME = 30000;
// Размеры объектов
let paddleHeight = 80;
const paddleWidth = 10;
const ballSize = 8;
// Позиции и скорости
let leftPaddleY = canvas.height/2 - paddleHeight/2;
let rightPaddleY = canvas.height/2 - paddleHeight/2;
let ballX = canvas.width/2;
let ballY = canvas.height/2;
let ballSpeedX = 5;
let ballSpeedY = 3;
let scoreLeft = 0;
let scoreRight = 0;
// Состояния клавиш
const keys = {
w: false,
s: false,
ArrowUp: false,
ArrowDown: false
};
function showGoalEffect() {
const effect = document.getElementById('goalEffect');
effect.style.display = 'block';
setTimeout(() => {
effect.style.display = 'none';
}, 1000);
}
function startGame() {
leftPlayerName = document.getElementById('leftPlayer').value || 'Левый игрок';
rightPlayerName = document.getElementById('rightPlayer').value || 'Правый игрок';
gameMode = 'hard';
playerNamesDiv.style.display = 'none';
initGame();
}
function initGame() {
isPlaying = true;
obstacles = [];
scoreLeft = 0;
scoreRight = 0;
lastObstacleTime = 0;
paddleHeight = 80;
leftPlayerNameElement.textContent = leftPlayerName;
rightPlayerNameElement.textContent = rightPlayerName;
leftScoreElement.textContent = '0';
rightScoreElement.textContent = '0';
resetBall();
gameLoop();
}
function resetBall() {
ballX = canvas.width/2;
ballY = canvas.height/2;
ballSpeedX = Math.random() > 0.5 ? 5 : -5;
ballSpeedY = 3;
}
function createObstacle() {
if (gameMode === 'hard' && Date.now() - lastObstacleTime > OBSTACLE_INTERVAL) {
const type = obstacleTypes[Math.floor(Math.random() * obstacleTypes.length)];
obstacles.push({
type: type,
x: Math.random() * (canvas.width - 40),
y: Math.random() * (canvas.height - 40),
width: 40,
height: 40,
createdAt: Date.now(),
color: type === 'paddle' ? (Math.random() > 0.5 ? 'red' : 'green') :
type === 'ball' ? ['red', 'blue', 'green'][Math.floor(Math.random()*3)] : 'yellow',
rotation: 0
});
lastObstacleTime = Date.now();
}
}
function handleObstacles() {
const now = Date.now();
obstacles = obstacles.filter(obs => now - obs.createdAt < OBSTACLE_LIFETIME);
obstacles.forEach((obs, index) => {
if (obs.type === 'random') obs.rotation += 0.1;
if (ballX + ballSize > obs.x &&
ballX < obs.x + obs.width &&
ballY + ballSize > obs.y &&
ballY < obs.y + obs.height) {
obstacleSound.currentTime = 0;
obstacleSound.play();
switch(obs.type) {
case 'paddle':
paddleHeight = obs.color === 'red' ? 60 : 100;
break;
case 'ball':
if(obs.color === 'red') {
ballSpeedX *= 1.5;
ballSpeedY *= 1.5;
} else if(obs.color === 'blue') {
ballSpeedX *= 0.7;
ballSpeedY *= 0.7;
} else {
ballSpeedX *= -1;
}
break;
case 'random':
ballSpeedX = (Math.random() - 0.5) * 10;
ballSpeedY = (Math.random() - 0.5) * 10;
break;
}
obstacles.splice(index, 1);
}
});
}
function drawObstacle(obs) {
ctx.save();
ctx.translate(obs.x + obs.width/2, obs.y + obs.height/2);
ctx.rotate(obs.rotation);
switch(obs.type) {
case 'paddle':
ctx.fillStyle = obs.color;
ctx.fillRect(-obs.width/2, -obs.height/2, obs.width, obs.height);
break;
case 'ball':
ctx.beginPath();
ctx.arc(0, 0, obs.width/2, 0, Math.PI*2);
ctx.fillStyle = obs.color;
ctx.fill();
break;
case 'random':
ctx.beginPath();
for(let i = 0; i < 5; i++) {
const angle = i * Math.PI*2/5;
const x = Math.cos(angle) * obs.width/2;
const y = Math.sin(angle) * obs.height/2;
if(i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.closePath();
ctx.fillStyle = obs.color;
ctx.fill();
break;
}
ctx.restore();
}
function animateScore(isLeft) {
const element = isLeft ? leftScoreElement : rightScoreElement;
element.classList.add('changed');
setTimeout(() => element.classList.remove('changed'), 300);
}
function gameLoop() {
if (!isPlaying) return;
// Движение ракеток
if (keys.w && leftPaddleY > 0) leftPaddleY -= 5;
if (keys.s && leftPaddleY < canvas.height - paddleHeight) leftPaddleY += 5;
if (keys.ArrowUp && rightPaddleY > 0) rightPaddleY -= 5;
if (keys.ArrowDown && rightPaddleY < canvas.height - paddleHeight) rightPaddleY += 5;
// Движение мяча
ballX += ballSpeedX;
ballY += ballSpeedY;
// Отскок от стен
if (ballY < 0 || ballY > canvas.height - ballSize) ballSpeedY *= -1;
// Столкновение с ракетками
if ((ballX < paddleWidth && ballY > leftPaddleY && ballY < leftPaddleY + paddleHeight) ||
(ballX > canvas.width - paddleWidth - ballSize && ballY > rightPaddleY && ballY < rightPaddleY + paddleHeight)) {
paddleSound.currentTime = 0;
paddleSound.play();
ballSpeedX *= -1;
ballSpeedY += (Math.random() - 0.5) * 2;
}
// Гол
if (ballX < 0 || ballX > canvas.width) {
goalSound.currentTime = 0;
goalSound.play();
showGoalEffect(); // Добавляем эффект
if(ballX < 0) {
scoreRight++;
rightScoreElement.textContent = scoreRight;
animateScore(false);
} else {
scoreLeft++;
leftScoreElement.textContent = scoreLeft;
animateScore(true);
}
resetBall();
}
// Обработка препятствий
createObstacle();
handleObstacles();
// Проверка победы
if (scoreLeft >= 10 || scoreRight >= 10) {
isPlaying = false;
gameOverElement.style.display = 'block';
const winner = scoreLeft >= 10 ? leftPlayerName : rightPlayerName;
gameOverElement.innerHTML = `Победитель:<br>${winner}!`;
winSound.currentTime = 0;
winSound.play();
return;
}
// Отрисовка
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Ракетки
ctx.fillStyle = 'white';
ctx.fillRect(0, leftPaddleY, paddleWidth, paddleHeight);
ctx.fillRect(canvas.width - paddleWidth, rightPaddleY, paddleWidth, paddleHeight);
// Мяч
ctx.beginPath();
ctx.arc(ballX + ballSize/2, ballY + ballSize/2, ballSize, 0, Math.PI*2);
ctx.fill();
// Препятствия
obstacles.forEach(obs => {
const timeLeft = OBSTACLE_LIFETIME - (Date.now() - obs.createdAt);
const alpha = Math.min(1, timeLeft / 2000);
ctx.globalAlpha = alpha;
drawObstacle(obs);
ctx.globalAlpha = 1;
});
requestAnimationFrame(gameLoop);
}
function toggleFullscreen() {
if (!document.fullscreenElement) {
canvas.requestFullscreen().catch(err => {
alert(`Ошибка при переходе в полноэкранный режим: ${err.message}`);
});
} else {
document.exitFullscreen();
}
}
// Обработчики событий
document.addEventListener('keydown', (e) => {
if (keys.hasOwnProperty(e.key)) keys[e.key] = true;
});
document.addEventListener('keyup', (e) => {
if (keys.hasOwnProperty(e.key)) keys[e.key] = false;
});
</script>
</body>
</html>