Ping-Pong z komputerem

Kod gry w ping-pong z komputerem

#HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ping Pong</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="score">Gracz: 0 | Komputer: 0</div>
    <button id="pauseButton">Zatrzymaj</button>
    <canvas id="pongCanvas"></canvas>
    <script src="script.js"></script>
</body>
</html>

#CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #000;
    flex-direction: column;
}

#score {
    color: #fff;
    font-size: 24px;
    margin-bottom: 10px;
}

canvas {
    background-color: #111;
    display: block;
    border: 2px solid #fff;
}

#JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// Inicjalizacja canvas i kontekstu
const canvas = document.getElementById('pongCanvas');
const context = canvas.getContext('2d');

// Ustawienia wymiarów canvas
canvas.width = 800;
canvas.height = 600;

const pauseButton = document.getElementById('pauseButton');
let isGamePaused = false; // Flaga do sprawdzania, czy gra jest zatrzymana

// Definicje obiektów
const paddleWidth = 10;
const paddleHeight = 100;
const ballRadius = 10;

const player = {
    x: 0,
    y: canvas.height / 2 - paddleHeight / 2,
    width: paddleWidth,
    height: paddleHeight,
    color: "#fff",
    dy: 0,
    speed: 6,
    score: 0
};

const computer = {
    x: canvas.width - paddleWidth,
    y: canvas.height / 2 - paddleHeight / 2,
    width: paddleWidth,
    height: paddleHeight,
    color: "#fff",
    speed: 4,
    score: 0
};

const ball = {
    x: canvas.width / 2,
    y: canvas.height / 2,
    radius: ballRadius,
    speed: 4,
    dx: 4,
    dy: 4,
    color: "#fff"
};

// Funkcja rysowania obiektów
function drawRect(x, y, width, height, color) {
    context.fillStyle = color;
    context.fillRect(x, y, width, height);
}

function drawCircle(x, y, radius, color) {
    context.fillStyle = color;
    context.beginPath();
    context.arc(x, y, radius, 0, Math.PI * 2);
    context.closePath();
    context.fill();
}

function drawNet() {
    for (let i = 0; i < canvas.height; i += 20) {
        drawRect(canvas.width / 2 - 1, i, 2, 10, '#fff');
    }
}

// Rysowanie wyniku
function drawScore() {
    document.getElementById('score').innerText = `Gracz: ${player.score} | Komputer: ${computer.score}`;
}

// Funkcja do poruszania komputerem (AI)
function moveComputer() {
    const difficulty = Math.random() * (ball.speed - 2) + 1; // Dynamiczne dopasowanie trudności
    if (ball.y < computer.y + computer.height / 2) {
        computer.y -= computer.speed * difficulty;
    } else if (ball.y > computer.y + computer.height / 2) {
        computer.y += computer.speed * difficulty;
    }
}

// Obsługa klawiatury
document.addEventListener('keydown', event => {
    if (event.key === 'ArrowUp') {
        player.dy = -player.speed;
    } else if (event.key === 'ArrowDown') {
        player.dy = player.speed;
    }
});

document.addEventListener('keyup', event => {
    if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
        player.dy = 0;
    }
});

// Kolizje z paletkami
function checkCollision(paddle, ball) {
    return ball.x - ball.radius < paddle.x + paddle.width &&
           ball.x + ball.radius > paddle.x &&
           ball.y + ball.radius > paddle.y &&
           ball.y - ball.radius < paddle.y + paddle.height;
}

// Resetowanie piłki po zdobyciu punktu
function resetBall() {
    ball.x = canvas.width / 2;
    ball.y = canvas.height / 2;
    ball.speed = 4;
    ball.dx = (Math.random() > 0.5 ? 1 : -1) * 4;
    ball.dy = (Math.random() > 0.5 ? 1 : -1) * 4;
}

// Aktualizacja punktów
function updateScore() {
    if (ball.x - ball.radius < 0) {
        computer.score += 1;
        resetBall();
    } else if (ball.x + ball.radius > canvas.width) {
        player.score += 1;
        resetBall();
    }
    drawScore();
}

// Funkcja do aktualizacji stanu gry
function update() {
    // Jeśli gra jest zatrzymana, nie aktualizujemy stanu
    if (isGamePaused) return;

    // Ruch piłki
    ball.x += ball.dx;
    ball.y += ball.dy;

    // Ruch gracza
    player.y += player.dy;

    // Kolizje ze ścianami
    if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
        ball.dy *= -1;
    }

    // Kolizje z paletkami
    if (checkCollision(player, ball)) {
        let collidePoint = ball.y - (player.y + player.height / 2);
        collidePoint = collidePoint / (player.height / 2);

        let angleRad = (Math.PI / 4) * collidePoint;
        ball.dx = ball.speed * Math.cos(angleRad);
        ball.dy = ball.speed * Math.sin(angleRad);

        ball.speed += 0.5;
        ball.dx = Math.abs(ball.dx); // Upewnij się, że piłka odbija się w prawo
    }

    if (checkCollision(computer, ball)) {
        let collidePoint = ball.y - (computer.y + computer.height / 2);
        collidePoint = collidePoint / (computer.height / 2);

        let angleRad = (Math.PI / 4) * collidePoint;
        ball.dx = ball.speed * Math.cos(angleRad);
        ball.dy = ball.speed * Math.sin(angleRad);

        ball.speed += 0.5;
        ball.dx = -Math.abs(ball.dx); // Upewnij się, że piłka odbija się w lewo
    }

    // Ruch komputera (AI)
    moveComputer();

    // Aktualizacja punktów
    updateScore();
}

// Funkcja do renderowania gry
function render() {
    // Czyszczenie canvas
    context.clearRect(0, 0, canvas.width, canvas.height);

    // Rysowanie elementów
    drawNet();
    drawRect(player.x, player.y, player.width, player.height, player.color);
    drawRect(computer.x, computer.y, computer.width, computer.height, computer.color);
    drawCircle(ball.x, ball.y, ball.radius, ball.color);
}

// Główna pętla gry
function gameLoop() {
    update();
    render();
    if (!isGamePaused) {
        requestAnimationFrame(gameLoop);
    }
}

// Obsługa zatrzymywania i wznawiania gry
pauseButton.addEventListener('click', () => {
    isGamePaused = !isGamePaused;
    if (isGamePaused) {
        pauseButton.innerText = "Wznów";
    } else {
        pauseButton.innerText = "Zatrzymaj";
        gameLoop(); // Uruchom ponownie główną pętlę gry, jeśli gra była zatrzymana
    }
});

// Rozpoczęcie gry
drawScore(); // Początkowy stan wyniku
gameLoop();
error: Treść jest chroniona !!

Arnold Basiński

Komputerowka.pl

Versja: 1.0.1

komputerówka.pl | Radość programowania

Napisz wiadomość

Smok Heighwaya | Klasówki i Kartkóki online
Krzywa Hilberta | Kartkówki i Klasówki online
Dywan Sierpińskiego | Kartkówki i Klasówki online
Drzewo Pitagorada | Kartkówki i Klasówki online
FRaktale Juli | Klasówki i Kartkówki online
Zbiór Mandelbrota | Klasówki i kartkówki online
Trojkat Sierpińskiego | Kartkówki i klasówki online
Płatek Kocha | Kartkówki i klasówki online