-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpythonpath.js
More file actions
241 lines (207 loc) · 8.57 KB
/
pythonpath.js
File metadata and controls
241 lines (207 loc) · 8.57 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
document.addEventListener('DOMContentLoaded', () => {
const gameBoard = document.getElementById('gameBoard');
const scoreDisplay = document.getElementById('score');
const startButton = document.getElementById('startButton');
const resetButton = document.getElementById('resetButton');
const codeConsole = document.getElementById('codeConsole');
const gridSize = 20; // 20x20 grid
const cellSize = 25; // in pixels, for visual scaling (board width / gridSize)
let snake = [{x: 10, y: 10}]; // Snake starts in the middle
let direction = 'right'; // Initial direction
let currentSnippet = {};
let score = 0;
let gameInterval = null;
let gameSpeed = 400; // milliseconds per move
let isGameRunning = false;
let collectedSnippets = [];
let allCells = []; // Store references to all cells once for efficiency
const pythonKeywords = [
"print", "if", "else", "for", "while", "def", "return", "import", "as",
"True", "False", "None", "+", "-", "*", "/", "==", "!="
];
function initializeGame() {
console.log('Initializing game...');
gameBoard.style.gridTemplateColumns = `repeat(${gridSize}, ${cellSize}px)`;
gameBoard.style.gridTemplateRows = `repeat(${gridSize}, ${cellSize}px)`;
gameBoard.style.width = `${gridSize * cellSize}px`;
gameBoard.style.height = `${gridSize * cellSize}px`;
// Ensure all previous game state is fully reset
clearInterval(gameInterval);
gameInterval = null;
isGameRunning = false;
snake = [{x: 10, y: 10}];
direction = 'right';
score = 0;
collectedSnippets = [];
drawBoard(); // This also populates allCells
placeSnippet(true); // Pass true for initial placement
drawSnake(); // Draw initial snake and snippet
scoreDisplay.textContent = score;
updateCodeConsole();
startButton.disabled = false;
resetButton.disabled = true;
}
function drawBoard() {
gameBoard.innerHTML = ''; // Clear existing cells
allCells = []; // Clear array of cell references
for (let i = 0; i < gridSize * gridSize; i++) {
const cell = document.createElement('div');
cell.classList.add('game-cell');
gameBoard.appendChild(cell);
allCells.push(cell); // Store reference to cell
}
}
function getCell(x, y) {
if (x < 0 || x >= gridSize || y < 0 || y >= gridSize) {
return null;
}
return allCells[y * gridSize + x]; // Use stored references for efficiency
}
function drawSnake() {
allCells.forEach(cell => {
cell.classList.remove('snake', 'snake-head', 'snippet');
cell.textContent = '';
});
snake.forEach((segment, index) => {
const cell = getCell(segment.x, segment.y);
if (cell) {
cell.classList.add('snake');
if (index === 0) {
cell.classList.add('snake-head');
}
}
});
if (currentSnippet && currentSnippet.x !== undefined && currentSnippet.y !== undefined) {
const snippetCell = getCell(currentSnippet.x, currentSnippet.y);
if (snippetCell) {
snippetCell.classList.add('snippet');
snippetCell.textContent = currentSnippet.keyword;
}
}
}
function placeSnippet(isInitialPlacement = false) { // Added parameter
let x, y;
if (isInitialPlacement) {
x = Math.floor(gridSize / 2); // 10
y = Math.floor(gridSize / 2) - 3; // 7 (3 rows above snake's start)
} else {
// For subsequent snippets, find a random empty spot
let attempts = 0;
const maxAttempts = gridSize * gridSize * 2;
do {
x = Math.floor(Math.random() * gridSize);
y = Math.floor(Math.random() * gridSize);
attempts++;
if (attempts > maxAttempts) {
console.warn("Could not place snippet after many attempts (board might be full).");
gameOver();
return;
}
} while (isSnakeOccupying(x, y) || (currentSnippet.x === x && currentSnippet.y === y));
}
currentSnippet = {x, y, keyword: pythonKeywords[Math.floor(Math.random() * pythonKeywords.length)]};
const snippetCell = getCell(currentSnippet.x, currentSnippet.y);
if (snippetCell) {
snippetCell.classList.add('snippet');
snippetCell.textContent = currentSnippet.keyword;
}
}
function isSnakeOccupying(x, y) {
return snake.some(segment => segment.x === x && segment.y === y);
}
function moveSnake() {
if (!isGameRunning) {
console.log('MoveSnake called, but game is not running. Stopping.');
clearInterval(gameInterval);
return;
}
const head = {...snake[0]};
switch (direction) {
case 'up': head.y--; break;
case 'down': head.y++; break;
case 'left': head.x--; break;
case 'right': head.x++; break;
}
if (head.x < 0 || head.x >= gridSize || head.y < 0 || head.y >= gridSize || isSnakeOccupying(head.x, head.y)) {
gameOver();
return;
}
snake.unshift(head);
if (head.x === currentSnippet.x && head.y === currentSnippet.y) {
score++;
scoreDisplay.textContent = score;
collectedSnippets.push(currentSnippet.keyword);
updateCodeConsole();
placeSnippet(); // Call without 'true' for subsequent random placement
} else {
snake.pop();
}
drawSnake();
}
function removeSnippetFromBoard() {
// This function is now less critical as drawSnake clears all cells before drawing.
}
function updateCodeConsole() {
codeConsole.innerHTML = '<span class="snippet-prefix"># Your Python Code Path:</span>';
collectedSnippets.forEach(snippet => {
const line = document.createElement('span');
line.classList.add('console-line');
line.textContent = snippet;
codeConsole.appendChild(line);
});
codeConsole.scrollTop = codeConsole.scrollHeight;
}
function startGame() {
console.log('Starting game...');
if (isGameRunning) {
console.log('Game already running, ignoring start call.');
return;
}
isGameRunning = true;
startButton.disabled = true;
resetButton.disabled = false;
if (gameInterval !== null) {
clearInterval(gameInterval);
}
gameInterval = setInterval(moveSnake, gameSpeed);
console.log(`Game started with speed: ${gameSpeed}ms`);
}
function resetGame() {
console.log('Resetting game...');
clearInterval(gameInterval);
gameInterval = null;
isGameRunning = false;
initializeGame();
console.log('Game reset.');
}
function gameOver() {
console.log('Game Over!');
isGameRunning = false;
clearInterval(gameInterval);
gameInterval = null;
alert(`Game Over! You collected ${score} snippets. Your code path:\n\n# Your Python Code Path:\n${collectedSnippets.join('\n')}\n\nPress Reset to play again.`);
startButton.disabled = false;
resetButton.disabled = false;
}
// Event Listeners
startButton.addEventListener('click', startGame);
resetButton.addEventListener('click', resetGame);
document.addEventListener('keydown', e => {
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
e.preventDefault();
}
const newDirectionKey = e.key.replace('Arrow', '').toLowerCase();
const oppositeDirections = {
'up': 'down', 'down': 'up',
'left': 'right', 'right': 'left'
};
if (['up', 'down', 'left', 'right'].includes(newDirectionKey) && oppositeDirections[direction] !== newDirectionKey) {
if (!isGameRunning) {
startGame();
}
direction = newDirectionKey;
}
});
// Initialize the game on page load (once DOM is ready)
initializeGame();
});