ChatGPT-4 - невероятно мощный инструмент, разработанный OpenAI, предназначенный для обработки и генерации языка на высоком уровне. Благодаря своей продвинутой архитектуре и обширной базе знаний, ChatGPT-4 способен справляться с самыми разнообразными задачами. Одно из поразительных достижений этой технологии - возможность создания игры "Pong" с использованием HTML, CSS и JavaScript. Это демонстрирует глубину понимания синтаксиса и структуры кода, а также умение адаптироваться к различным сценариям и предоставлять качественные решения для вопросов пользователей.
Поиграть в нее можно тут https://pong.xorit.ru/
Так же привиду исходный код:
Файл html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pong Game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<img src="xorit-logo300-r.png" alt="Logo" class="logo">
<div class="rules">
<h2>Правила игры</h2>
<p>В игре Pong два игрока управляют платформами, перемещая их вертикально вверх и вниз. Цель игры - отбивать мяч так, чтобы он не вышел за пределы игрового поля. Каждый раз, когда мяч уходит за пределы поля, игроку начисляется очко. Игра продолжается до тех пор, пока один из игроков не наберет определенное количество очков.</p>
</div>
<div class="controls">
<h2>Управление</h2>
<p>Игрок 1 (слева): используйте клавиши со стрелками вверх и вниз для перемещения платформы вверх и вниз.</p>
</div>
<div class="canvas-container">
<canvas id="pong" width="800" height="400"></canvas>
<a href="https://xorit.ru/" class="external-link" target="_blank">Посетите Xorit.ru</a>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Файл каскадных стилей style.css:
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: black;
margin: 0;
}
.container {
display: flex;
flex-direction: column;
align-items: center;
}
.logo {
width: 300px; /* Установите ширину логотипа по желанию */
margin-bottom: 20px;
display: block;
margin-left: auto;
margin-right: auto;
}
.rules, .controls {
color: white;
text-align: center;
margin-bottom: 20px;
}
.rules h2, .controls h2 {
margin-bottom: 10px;
}
.canvas-container {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
}
canvas {
border: 1px solid black;
}
.external-link {
color: white;
text-decoration: none;
margin-top: 20px;
text-align: center;
width: 100%;
}
.external-link:hover {
text-decoration: underline;
}
Файл JavaScript - script.js:
const canvas = document.getElementById('pong');
const context = canvas.getContext('2d');
const paddleWidth = 10;
const paddleHeight = 100;
const player = {
x: 0,
y: canvas.height / 2 - paddleHeight / 2,
width: paddleWidth,
height: paddleHeight,
dy: 4
};
const computer = {
x: canvas.width - paddleWidth,
y: canvas.height / 2 - paddleHeight / 2,
width: paddleWidth,
height: paddleHeight,
dy: 4
};
const ball = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: 7,
dx: 4,
dy: 4
};
let playerScore = 0;
let computerScore = 0;
let upArrowPressed = false;
let downArrowPressed = false;
function drawPaddle(x, y, width, height) {
context.fillStyle = 'white';
context.fillRect(x, y, width, height);
}
function drawBall(x, y, radius) {
context.fillStyle = 'white';
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2, false);
context.closePath();
context.fill();
}
function drawScore() {
context.font = '24px Arial';
context.fillStyle = 'white';
context.fillText(playerScore, canvas.width / 4, 30);
context.fillText(computerScore, (3 * canvas.width) / 4, 30);
}
function update() {
if (upArrowPressed) {
player.y -= player.dy;
} else if (downArrowPressed) {
player.y += player.dy;
}
// Paddle collision with canvas
if (player.y < 0) player.y = 0;
if (player.y + player.height > canvas.height) player.y = canvas.height - player.height;
if (computer.y < 0) computer.y = 0;
if (computer.y + computer.height > canvas.height) computer.y = canvas.height - computer.height;
// Move ball
ball.x += ball.dx;
ball.y += ball.dy;
// Ball collision with canvas
if (ball.y - ball.radius < 0 || ball.y + ball.radius > canvas.height) {
ball.dy = -ball.dy;
}
// Ball collision with paddles
if (
(ball.x - ball.radius < player.x + player.width &&
ball.y > player.y &&
ball.y < player.y + player.height) ||
(ball.x + ball.radius > computer.x &&
ball.y > computer.y &&
ball.y < computer.y + computer.height)
) {
ball.dx = -ball.dx;
}
// Ball out of bounds
if (ball.x + ball.radius < 0) {
computerScore++;
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
ball.dx = -ball.dx;
} else if (ball.x - ball.radius > canvas.width) {
playerScore++;
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
ball.dx = -ball.dx;
}
if (ball.dy > 0) {
if (computer.y + computer.height / 2 < ball.y) {
computer.y += computer.dy;
}
} else {
if (computer.y + computer.height / 2 > ball.y) {
computer.y -= computer.dy;
}
}
}
function draw() {
// Clear canvas
context.fillStyle = 'black';
context.fillRect(0, 0, canvas.width, canvas.height);
// Draw paddles
drawPaddle(player.x, player.y, player.width, player.height);
drawPaddle(computer.x, computer.y, computer.width, computer.height);
// Draw ball
drawBall(ball.x, ball.y, ball.radius);
// Draw score
drawScore();
// Draw dashed line
context.beginPath();
context.setLineDash([5]);
context.moveTo(canvas.width / 2, 0);
context.lineTo(canvas.width / 2, canvas.height);
context.strokeStyle = 'white';
context.stroke();
context.closePath();
}
function gameLoop() {
update();
draw();
requestAnimationFrame(gameLoop);
}
document.addEventListener('keydown', (event) => {
if (event.code === 'ArrowUp') {
upArrowPressed = true;
} else if (event.code === 'ArrowDown') {
downArrowPressed = true;
}
});
document.addEventListener('keyup', (event) => {
if (event.code === 'ArrowUp') {
upArrowPressed = false;
} else if (event.code === 'ArrowDown') {
downArrowPressed = false;
}
});
gameLoop();
Код можно усовершенствовать из раза в раз путем дополнительных просьб, например мне уже было лень даже логипик КСОР АйТи размещать самому и я просто попросил добавить его в png, так же было и с правилами самой игры и ссылкой на наш сайт.