-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
322 lines (288 loc) · 10.4 KB
/
game.js
File metadata and controls
322 lines (288 loc) · 10.4 KB
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
(() => {
// --- State ---
let gridSize = 4;
let players = [
{ name: 'Player 1', color: '#e74c3c', score: 0 },
{ name: 'Player 2', color: '#3498db', score: 0 },
];
let currentPlayer = 0;
// Lines: horizontal[row][col] and vertical[row][col]
// horizontal: (gridSize) rows x (gridSize-1) cols
// vertical: (gridSize-1) rows x (gridSize) cols
let hLines = [];
let vLines = [];
// Boxes: (gridSize-1) x (gridSize-1), null or player index
let boxes = [];
let gameOver = false;
// --- DOM refs ---
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
const setupScreen = document.getElementById('setup-screen');
const gameScreen = document.getElementById('game-screen');
const gameOverScreen = document.getElementById('game-over');
// --- Constants ---
const DOT_RADIUS = 6;
const LINE_THICKNESS = 5;
const CELL_SIZE = 80;
const PADDING = 30;
// --- Theme ---
const themeToggle = document.getElementById('theme-toggle');
function applyTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
themeToggle.textContent = theme === 'dark' ? '☀️' : '🌙';
localStorage.setItem('dab-theme', theme);
if (!setupScreen.classList.contains('hidden')) return;
draw();
}
themeToggle.addEventListener('click', () => {
const current = document.documentElement.getAttribute('data-theme');
applyTheme(current === 'dark' ? 'light' : 'dark');
});
// Load saved theme
const savedTheme = localStorage.getItem('dab-theme') || 'light';
applyTheme(savedTheme);
// --- Grid size buttons ---
document.querySelectorAll('.grid-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.grid-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
gridSize = parseInt(btn.dataset.size);
});
});
// --- Start game ---
document.getElementById('start-btn').addEventListener('click', startGame);
document.getElementById('restart-btn').addEventListener('click', () => {
gameScreen.classList.add('hidden');
gameOverScreen.classList.add('hidden');
setupScreen.classList.remove('hidden');
});
document.getElementById('play-again-btn').addEventListener('click', () => {
gameOverScreen.classList.add('hidden');
gameScreen.classList.add('hidden');
setupScreen.classList.remove('hidden');
});
function startGame() {
players[0].name = document.getElementById('p1-name').value || 'Player 1';
players[0].color = document.getElementById('p1-color').value;
players[1].name = document.getElementById('p2-name').value || 'Player 2';
players[1].color = document.getElementById('p2-color').value;
players[0].score = 0;
players[1].score = 0;
currentPlayer = 0;
gameOver = false;
// Init line arrays: false = not drawn
const rows = gridSize;
const cols = gridSize;
hLines = Array.from({ length: rows }, () => Array(cols - 1).fill(false));
vLines = Array.from({ length: rows - 1 }, () => Array(cols).fill(false));
boxes = Array.from({ length: rows - 1 }, () => Array(cols - 1).fill(null));
// Size canvas
const w = (gridSize - 1) * CELL_SIZE + PADDING * 2;
const h = (gridSize - 1) * CELL_SIZE + PADDING * 2;
const dpr = window.devicePixelRatio || 1;
canvas.width = w * dpr;
canvas.height = h * dpr;
canvas.style.width = w + 'px';
canvas.style.height = h + 'px';
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
setupScreen.classList.add('hidden');
gameScreen.classList.remove('hidden');
updateScoreboard();
draw();
}
// --- Drawing ---
function getCSS(varName) {
return getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
}
function draw() {
const w = parseFloat(canvas.style.width);
const h = parseFloat(canvas.style.height);
ctx.clearRect(0, 0, w, h);
// Draw filled boxes
for (let r = 0; r < gridSize - 1; r++) {
for (let c = 0; c < gridSize - 1; c++) {
if (boxes[r][c] !== null) {
const x = PADDING + c * CELL_SIZE;
const y = PADDING + r * CELL_SIZE;
ctx.fillStyle = players[boxes[r][c]].color + '44';
ctx.fillRect(x, y, CELL_SIZE, CELL_SIZE);
}
}
}
// Draw horizontal lines
for (let r = 0; r < gridSize; r++) {
for (let c = 0; c < gridSize - 1; c++) {
const x1 = PADDING + c * CELL_SIZE;
const y1 = PADDING + r * CELL_SIZE;
ctx.strokeStyle = hLines[r][c] ? hLines[r][c] : getCSS('--line-empty');
ctx.lineWidth = hLines[r][c] ? LINE_THICKNESS + 1 : LINE_THICKNESS;
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x1 + CELL_SIZE, y1);
ctx.stroke();
}
}
// Draw vertical lines
for (let r = 0; r < gridSize - 1; r++) {
for (let c = 0; c < gridSize; c++) {
const x1 = PADDING + c * CELL_SIZE;
const y1 = PADDING + r * CELL_SIZE;
ctx.strokeStyle = vLines[r][c] ? vLines[r][c] : getCSS('--line-empty');
ctx.lineWidth = vLines[r][c] ? LINE_THICKNESS + 1 : LINE_THICKNESS;
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x1, y1 + CELL_SIZE);
ctx.stroke();
}
}
// Draw dots
for (let r = 0; r < gridSize; r++) {
for (let c = 0; c < gridSize; c++) {
const x = PADDING + c * CELL_SIZE;
const y = PADDING + r * CELL_SIZE;
ctx.fillStyle = getCSS('--dot-color');
ctx.beginPath();
ctx.arc(x, y, DOT_RADIUS, 0, Math.PI * 2);
ctx.fill();
}
}
}
// --- Click handling ---
canvas.addEventListener('click', (e) => {
if (gameOver) return;
const rect = canvas.getBoundingClientRect();
const mx = e.clientX - rect.left;
const my = e.clientY - rect.top;
const hit = findClosestLine(mx, my);
if (!hit) return;
const { type, row, col } = hit;
// Check if already drawn
if (type === 'h' && hLines[row][col]) return;
if (type === 'v' && vLines[row][col]) return;
// Draw line with player color
const color = players[currentPlayer].color;
if (type === 'h') hLines[row][col] = color;
else vLines[row][col] = color;
// Check for completed boxes
const scored = checkBoxes();
if (scored === 0) {
currentPlayer = 1 - currentPlayer;
}
updateScoreboard();
draw();
// Check game over
const totalBoxes = (gridSize - 1) * (gridSize - 1);
if (players[0].score + players[1].score === totalBoxes) {
gameOver = true;
showGameOver();
}
});
// Hover effect
canvas.addEventListener('mousemove', (e) => {
if (gameOver) return;
const rect = canvas.getBoundingClientRect();
const mx = e.clientX - rect.left;
const my = e.clientY - rect.top;
const hit = findClosestLine(mx, my);
canvas.style.cursor = hit ? 'pointer' : 'default';
});
function findClosestLine(mx, my) {
const threshold = 15;
let best = null;
let bestDist = threshold;
// Check horizontal lines
for (let r = 0; r < gridSize; r++) {
for (let c = 0; c < gridSize - 1; c++) {
if (hLines[r][c]) continue;
const x1 = PADDING + c * CELL_SIZE;
const y1 = PADDING + r * CELL_SIZE;
const x2 = x1 + CELL_SIZE;
const dist = distToSegment(mx, my, x1, y1, x2, y1);
if (dist < bestDist) {
bestDist = dist;
best = { type: 'h', row: r, col: c };
}
}
}
// Check vertical lines
for (let r = 0; r < gridSize - 1; r++) {
for (let c = 0; c < gridSize; c++) {
if (vLines[r][c]) continue;
const x1 = PADDING + c * CELL_SIZE;
const y1 = PADDING + r * CELL_SIZE;
const y2 = y1 + CELL_SIZE;
const dist = distToSegment(mx, my, x1, y1, x1, y2);
if (dist < bestDist) {
bestDist = dist;
best = { type: 'v', row: r, col: c };
}
}
}
return best;
}
function distToSegment(px, py, x1, y1, x2, y2) {
const dx = x2 - x1;
const dy = y2 - y1;
const lenSq = dx * dx + dy * dy;
let t = ((px - x1) * dx + (py - y1) * dy) / lenSq;
t = Math.max(0, Math.min(1, t));
const cx = x1 + t * dx;
const cy = y1 + t * dy;
const ex = px - cx;
const ey = py - cy;
return Math.sqrt(ex * ex + ey * ey);
}
function checkBoxes() {
let scored = 0;
for (let r = 0; r < gridSize - 1; r++) {
for (let c = 0; c < gridSize - 1; c++) {
if (boxes[r][c] !== null) continue;
const top = hLines[r][c];
const bottom = hLines[r + 1][c];
const left = vLines[r][c];
const right = vLines[r][c + 1];
if (top && bottom && left && right) {
boxes[r][c] = currentPlayer;
players[currentPlayer].score++;
scored++;
}
}
}
return scored;
}
// --- Scoreboard ---
function updateScoreboard() {
const p1Card = document.getElementById('p1-score-card');
const p2Card = document.getElementById('p2-score-card');
document.getElementById('p1-label').textContent = players[0].name;
document.getElementById('p2-label').textContent = players[1].name;
document.getElementById('p1-score').textContent = players[0].score;
document.getElementById('p2-score').textContent = players[1].score;
p1Card.style.color = players[0].color;
p2Card.style.color = players[1].color;
p1Card.classList.toggle('active', currentPlayer === 0);
p2Card.classList.toggle('active', currentPlayer === 1);
const indicator = document.getElementById('turn-indicator');
indicator.textContent = `${players[currentPlayer].name}'s turn`;
indicator.style.color = players[currentPlayer].color;
}
// --- Game Over ---
function showGameOver() {
const winnerText = document.getElementById('winner-text');
const finalScore = document.getElementById('final-score');
if (players[0].score > players[1].score) {
winnerText.textContent = `${players[0].name} Wins!`;
winnerText.style.color = players[0].color;
} else if (players[1].score > players[0].score) {
winnerText.textContent = `${players[1].name} Wins!`;
winnerText.style.color = players[1].color;
} else {
winnerText.textContent = "It's a Tie!";
winnerText.style.color = '';
}
finalScore.textContent = `${players[0].score} - ${players[1].score}`;
gameOverScreen.classList.remove('hidden');
}
})();