From b0b7631dcbe7f53140d3fd6d6aafa11e35e17602 Mon Sep 17 00:00:00 2001
From: aamira0 <150680980+aamira0@users.noreply.github.com>
Date: Sat, 15 Jun 2024 14:37:30 +0200
Subject: [PATCH 01/22] First basics of pac man
- pac man collects points and the dots disappear
- ghosts exist and wander around
---
PacMan/index.html | 22 ++++++
PacMan/jscrpt.js | 168 ++++++++++++++++++++++++++++++++++++++++++++++
PacMan/style.css | 91 +++++++++++++++++++++++++
3 files changed, 281 insertions(+)
create mode 100644 PacMan/index.html
create mode 100644 PacMan/jscrpt.js
create mode 100644 PacMan/style.css
diff --git a/PacMan/index.html b/PacMan/index.html
new file mode 100644
index 0000000000..1ef0d9ca8c
--- /dev/null
+++ b/PacMan/index.html
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+ Pac-Man Game
+
+
+
+
+
+
+
+
+
+
Score: 0
+
+
+
+
+
diff --git a/PacMan/jscrpt.js b/PacMan/jscrpt.js
new file mode 100644
index 0000000000..8f55546a3c
--- /dev/null
+++ b/PacMan/jscrpt.js
@@ -0,0 +1,168 @@
+document.addEventListener('DOMContentLoaded', () => {
+ // Get the game board element
+ const gameBoard = document.getElementById('gameBoard');
+
+ // Initialize variables
+ const grid = []; // Array to hold the grid cells
+ const rows = 20; // Number of rows in the grid
+ const cols = 20; // Number of columns in the grid
+ let score = 0; // Player's score
+ const totalPacDots = document.querySelectorAll('.pac-dot').length; // Total number of pac-dots in the game
+
+ // Level layout (0 = empty, 1 = wall, 2 = pac-dot)
+ const layout = [
+ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+ 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,
+ 1,2,1,1,1,1,1,2,1,1,2,1,1,2,1,1,1,1,2,1,
+ 1,2,2,2,2,2,2,2,1,2,2,2,1,2,1,2,2,2,2,1,
+ 1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,1,
+ 1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,1,
+ 1,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,
+ 1,1,1,2,1,1,1,1,1,2,1,1,1,1,1,2,1,1,1,1,
+ 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,
+ 1,2,1,1,1,2,1,1,1,1,1,1,1,1,2,1,1,1,2,1,
+ 1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,
+ 1,2,1,2,1,1,1,1,1,1,1,1,1,2,1,1,1,1,2,1,
+ 1,2,1,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,1,
+ 1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,1,2,1,
+ 1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,2,2,2,1,
+ 1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,1,1,1,
+ 1,2,2,2,2,2,2,2,1,2,2,2,1,2,2,2,2,2,2,1,
+ 1,2,1,1,1,1,1,2,1,2,1,2,1,2,1,1,1,1,2,1,
+ 1,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,1,
+ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
+ ];
+
+// Create the gameboard
+layout.forEach((cell, index) => {
+ const div = document.createElement('div'); // Create a new div element for each cell
+ div.classList.add('cell'); // Add the 'cell' class to the div
+
+ // Add wall class if the cell is a wall, pac-dot class if the cell contains a pac-dot
+ if (cell === 1) {
+ div.classList.add('wall'); // Add the 'wall' class to the div if the cell represents a wall
+ } else if (cell === 2) {
+ div.classList.add('pac-dot'); // Add the 'pac-dot' class to the div if the cell contains a pac-dot
+ }
+
+ gameBoard.appendChild(div); // Add the div to the game board element in the HTML
+ grid.push(div); // Add the div element to the grid array for tracking
+});
+
+ // Place Pac-Man
+ let pacmanCurrentIndex = 21; // Set Pac-Man's initial position to index 21
+ grid[pacmanCurrentIndex].classList.add('pacman'); // Add 'pacman' class to the cell at Pac-Man's initial position
+
+ // Remove pac-dot at initial position if present
+ if (grid[pacmanCurrentIndex].classList.contains('pac-dot')) {
+ grid[pacmanCurrentIndex].classList.remove('pac-dot'); // Remove 'pac-dot' class if present at Pac-Man's initial position
+ score += 10; // Increase the score by 10 points
+ console.log('Score:', score); // Output the current score to the console
+}
+
+// Function to move Pac-Man
+const movePacman = () => {
+ if (direction !== null) {
+ let newIndex = pacmanCurrentIndex; // Initialize newIndex with the current Pac-Man index
+
+ // Move Pac-Man based on the current direction
+ switch (direction) {
+ case 'ArrowUp': // Move Pac-Man up if the direction is 'ArrowUp'
+ // Check if moving up is possible and there is no wall in the way
+ if (pacmanCurrentIndex - cols >= 0 && !grid[pacmanCurrentIndex - cols].classList.contains('wall')) {
+ newIndex -= cols; // Move Pac-Man up by one row
+ }
+ break;
+ case 'ArrowDown': // Move Pac-Man down if the direction is 'ArrowDown'
+ // Check if moving down is possible and there is no wall in the way
+ if (pacmanCurrentIndex + cols < cols * rows && !grid[pacmanCurrentIndex + cols].classList.contains('wall')) {
+ newIndex += cols; // Move Pac-Man down by one row
+ }
+ break;
+ case 'ArrowLeft': // Move Pac-Man left if the direction is 'ArrowLeft'
+ // Check if moving left is possible and there is no wall in the way
+ if (pacmanCurrentIndex % cols !== 0 && !grid[pacmanCurrentIndex - 1].classList.contains('wall')) {
+ newIndex -= 1; // Move Pac-Man left by one column
+ }
+ break;
+ case 'ArrowRight': // Move Pac-Man right if the direction is 'ArrowRight'
+ // Check if moving right is possible and there is no wall in the way
+ if (pacmanCurrentIndex % cols < cols - 1 && !grid[pacmanCurrentIndex + 1].classList.contains('wall')) {
+ newIndex += 1; // Move Pac-Man right by one column
+ }
+ break;
+ }
+
+ // Check if Pac-Man's position has changed
+ if (newIndex !== pacmanCurrentIndex) {
+ // Remove Pac-Man from the current position
+ grid[pacmanCurrentIndex].classList.remove('pacman');
+ pacmanCurrentIndex = newIndex; // Update Pac-Man's current index
+ grid[pacmanCurrentIndex].classList.add('pacman'); // Add Pac-Man to the new position
+
+ // Check if Pac-Man has eaten a pac-dot
+ if (grid[pacmanCurrentIndex].classList.contains('pac-dot')) {
+ grid[pacmanCurrentIndex].classList.remove('pac-dot'); // Remove the pac-dot
+ score += 10; // Increase the score
+ document.getElementById('scoreValue').textContent = score; // Update the score display
+ console.log('Score:', score);
+
+ // Check if all pac-dots are collected
+ if (score === totalPacDots * 10) {
+ console.log('Congratulations! You won!');
+ }
+ }
+ }
+ }
+ };
+
+ // Check for keydown events to set Pac-Man's direction
+ document.addEventListener('keydown', (event) => {
+ const key = event.key;
+ if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(key)) {
+ direction = key; // Set Pac-Man's direction based on the pressed key
+ }
+ });
+
+ // Game loop
+ setInterval(movePacman, 200); // Move Pac-Man every 200ms
+
+ //Ghost
+ class Ghost {
+ constructor(startIndex, color) {
+ // Initialize Ghost
+ this.currentIndex = startIndex; // Set the current index of the ghost
+ this.color = color; // Set the color of the ghost
+ }
+
+ moveGhost() {
+ const directions = [-1, +1, -cols, +cols]; // Possible directions for the ghost
+ let direction = directions[Math.floor(Math.random() * directions.length)]; // Initial direction
+
+ // Move the ghost at regular intervals
+ this.timerId = setInterval(() => {
+ // Logic for ghost movement
+ const nextMove = this.currentIndex + direction; // Calculate the next potential position for the ghost
+ if (!grid[nextMove].classList.contains('wall') && !grid[nextMove].classList.contains('ghost')) { // Check if next move isn't a wall
+ // Remove ghost from the current position
+ grid[this.currentIndex].classList.remove('ghost', this.color);
+ // Move the ghost to the next position
+ this.currentIndex = nextMove;
+ // Place the ghost on the new position
+ grid[this.currentIndex].classList.add('ghost', this.color);
+ } else {
+ // Choose a new random direction if the ghost can't move
+ direction = directions[Math.floor(Math.random() * directions.length)];
+ }
+ }, 200); // Move Ghost every 200ms
+ }
+ }
+
+ // Create ghosts
+ const ghost1 = new Ghost(209, 'red'); // Place the first ghost
+ const ghost2 = new Ghost(229, 'blue'); // Place the second ghost
+
+ // Start ghost movement
+ ghost1.moveGhost();
+ ghost2.moveGhost();
+});
\ No newline at end of file
diff --git a/PacMan/style.css b/PacMan/style.css
new file mode 100644
index 0000000000..8d8db15d71
--- /dev/null
+++ b/PacMan/style.css
@@ -0,0 +1,91 @@
+body {
+ /* Center align the content vertically and horizontally */
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ /* Set the height of the body to 100% of the viewport height */
+ height: 100vh;
+ /* Remove margin to prevent unwanted spacing */
+ margin: 0;
+ /* Set background color to black */
+ background-color: #000;
+}
+
+#gameBoard {
+ /* Create a grid layout for the game board */
+ display: grid;
+ /* Define 20 columns each with a width of 30px */
+ grid-template-columns: repeat(20, 30px);
+ /* Define 20 rows each with a height of 30px */
+ grid-template-rows: repeat(20, 30px);
+ /* Set the gap between grid items */
+ gap: 2px;
+}
+
+.cell {
+ width: 30px;
+ height: 30px;
+}
+
+.wall {
+ background-color: blue;
+}
+
+/*Space for the pac dots*/
+.pac-dot {
+ background-color: black;
+ /* Center align content vertically and horizontally */
+ display: flex;
+ justify-content: center;
+ align-items: center;
+}
+
+/*Pac dots themselves*/
+.pac-dot::after {
+ /*Create circle*/
+ content: '';
+ width: 10px;
+ height: 10px;
+
+ background-color: white;
+ /*Create a rounded shape*/
+ border-radius: 50%;
+}
+
+/*Pac-Man*/
+.pacman {
+ background-color: yellow;
+ /*Create a round shape*/
+ border-radius: 50%;
+}
+
+/*Score display*/
+#score {
+ font-size: 24px;
+ font-weight: bold;
+ color: white;
+ background-color: black;
+ padding: 10px;
+}
+
+/*Score value*/
+#scoreValue {
+ color: yellow;
+}
+
+
+/*Ghosts*/
+.ghost {
+ /*Set background color dynamically*/
+ background-color: var(--ghost-color);
+}
+
+/*Red ghost*/
+.red {
+ --ghost-color: red;
+}
+
+/*Blue ghost*/
+.blue {
+ --ghost-color: green;
+}
From 22bc978e849ba3229d2a02b3e8e855d7cf5896ff Mon Sep 17 00:00:00 2001
From: aamira0 <150680980+aamira0@users.noreply.github.com>
Date: Sat, 15 Jun 2024 15:33:59 +0200
Subject: [PATCH 02/22] Ghost movements
-improved ghost movements
-ghosts follow pacman
---
PacMan/jscrpt.js | 63 +++++++++++++++++++++++++++++++++++++++---------
1 file changed, 51 insertions(+), 12 deletions(-)
diff --git a/PacMan/jscrpt.js b/PacMan/jscrpt.js
index 8f55546a3c..edb0b9c392 100644
--- a/PacMan/jscrpt.js
+++ b/PacMan/jscrpt.js
@@ -137,22 +137,61 @@ const movePacman = () => {
moveGhost() {
const directions = [-1, +1, -cols, +cols]; // Possible directions for the ghost
- let direction = directions[Math.floor(Math.random() * directions.length)]; // Initial direction
-
+
+ // Function to calculate distance between two indices on the grid
+ const distanceToPacman = (ghostIndex, pacmanIndex) => {
+ const ghostRow = Math.floor(ghostIndex / cols);
+ const ghostCol = ghostIndex % cols;
+ const pacmanRow = Math.floor(pacmanIndex / cols);
+ const pacmanCol = pacmanIndex % cols;
+ return Math.abs(ghostRow - pacmanRow) + Math.abs(ghostCol - pacmanCol);
+ };
+
+ // Function to choose the best direction towards Pac-Man
+ const chooseDirection = () => {
+ // Get Pac-Man's current index
+ const pacmanIndex = grid.findIndex(cell => cell.classList.contains('pacman'));
+
+ // Calculate distances for each direction and filter out invalid moves
+ const validDirections = directions.filter(direction => {
+ const nextMove = this.currentIndex + direction;
+ return !grid[nextMove].classList.contains('wall') && !grid[nextMove].classList.contains('ghost');
+ });
+
+ // Sort directions by distance to Pac-Man
+ validDirections.sort((dir1, dir2) => {
+ const nextMove1 = this.currentIndex + dir1;
+ const nextMove2 = this.currentIndex + dir2;
+ return distanceToPacman(nextMove1, pacmanIndex) - distanceToPacman(nextMove2, pacmanIndex);
+ });
+
+ // Return the closest direction if available
+ return validDirections.length > 0 ? validDirections[0] : null;
+ };
+
+ let direction = chooseDirection(); // Initial direction
+
// Move the ghost at regular intervals
this.timerId = setInterval(() => {
// Logic for ghost movement
- const nextMove = this.currentIndex + direction; // Calculate the next potential position for the ghost
- if (!grid[nextMove].classList.contains('wall') && !grid[nextMove].classList.contains('ghost')) { // Check if next move isn't a wall
- // Remove ghost from the current position
- grid[this.currentIndex].classList.remove('ghost', this.color);
- // Move the ghost to the next position
- this.currentIndex = nextMove;
- // Place the ghost on the new position
- grid[this.currentIndex].classList.add('ghost', this.color);
+ if (direction !== null) {
+ const nextMove = this.currentIndex + direction; // Calculate the next potential position for the ghost
+
+ // Check if next move isn't a wall or another ghost
+ if (!grid[nextMove].classList.contains('wall') && !grid[nextMove].classList.contains('ghost')) {
+ // Remove ghost from the current position
+ grid[this.currentIndex].classList.remove('ghost', this.color);
+ // Move the ghost to the next position
+ this.currentIndex = nextMove;
+ // Place the ghost on the new position
+ grid[this.currentIndex].classList.add('ghost', this.color);
+ } else {
+ // Choose a new direction if the ghost can't move
+ direction = chooseDirection();
+ }
} else {
- // Choose a new random direction if the ghost can't move
- direction = directions[Math.floor(Math.random() * directions.length)];
+ // Choose a new direction if no valid direction is found
+ direction = chooseDirection();
}
}, 200); // Move Ghost every 200ms
}
From e0d9d10e93af373573050b05639cfd6d8bf9b140 Mon Sep 17 00:00:00 2001
From: aamira0 <150680980+aamira0@users.noreply.github.com>
Date: Sat, 15 Jun 2024 16:50:04 +0200
Subject: [PATCH 03/22] Stopping game
-Game stops when player wins (using 200 score for test)
-Game stops when player is touched by ghost
---
PacMan/jscrpt.js | 223 +++++++++++++++++++++++++++++------------------
1 file changed, 137 insertions(+), 86 deletions(-)
diff --git a/PacMan/jscrpt.js b/PacMan/jscrpt.js
index edb0b9c392..b03afda5ca 100644
--- a/PacMan/jscrpt.js
+++ b/PacMan/jscrpt.js
@@ -7,7 +7,8 @@ document.addEventListener('DOMContentLoaded', () => {
const rows = 20; // Number of rows in the grid
const cols = 20; // Number of columns in the grid
let score = 0; // Player's score
- const totalPacDots = document.querySelectorAll('.pac-dot').length; // Total number of pac-dots in the game
+ let totalPacDots = 0; // Total number of pac-dots in the game
+ let gameOver = false; // Flag to track game over state
// Level layout (0 = empty, 1 = wall, 2 = pac-dot)
const layout = [
@@ -33,21 +34,22 @@ document.addEventListener('DOMContentLoaded', () => {
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
];
-// Create the gameboard
-layout.forEach((cell, index) => {
- const div = document.createElement('div'); // Create a new div element for each cell
- div.classList.add('cell'); // Add the 'cell' class to the div
+ // Create the gameboard
+ layout.forEach((cell, index) => {
+ const div = document.createElement('div'); // Create a new div element for each cell
+ div.classList.add('cell'); // Add the 'cell' class to the div
- // Add wall class if the cell is a wall, pac-dot class if the cell contains a pac-dot
- if (cell === 1) {
- div.classList.add('wall'); // Add the 'wall' class to the div if the cell represents a wall
- } else if (cell === 2) {
- div.classList.add('pac-dot'); // Add the 'pac-dot' class to the div if the cell contains a pac-dot
- }
+ // Add wall class if the cell is a wall, pac-dot class if the cell contains a pac-dot
+ if (cell === 1) {
+ div.classList.add('wall'); // Add the 'wall' class to the div if the cell represents a wall
+ } else if (cell === 2) {
+ div.classList.add('pac-dot'); // Add the 'pac-dot' class to the div if the cell contains a pac-dot
+ totalPacDots++; // Increment totalPacDots for each pac-dot found
+ }
- gameBoard.appendChild(div); // Add the div to the game board element in the HTML
- grid.push(div); // Add the div element to the grid array for tracking
-});
+ gameBoard.appendChild(div); // Add the div to the game board element in the HTML
+ grid.push(div); // Add the div element to the grid array for tracking
+ });
// Place Pac-Man
let pacmanCurrentIndex = 21; // Set Pac-Man's initial position to index 21
@@ -55,68 +57,91 @@ layout.forEach((cell, index) => {
// Remove pac-dot at initial position if present
if (grid[pacmanCurrentIndex].classList.contains('pac-dot')) {
- grid[pacmanCurrentIndex].classList.remove('pac-dot'); // Remove 'pac-dot' class if present at Pac-Man's initial position
- score += 10; // Increase the score by 10 points
- console.log('Score:', score); // Output the current score to the console
-}
-
-// Function to move Pac-Man
-const movePacman = () => {
- if (direction !== null) {
- let newIndex = pacmanCurrentIndex; // Initialize newIndex with the current Pac-Man index
-
- // Move Pac-Man based on the current direction
- switch (direction) {
- case 'ArrowUp': // Move Pac-Man up if the direction is 'ArrowUp'
- // Check if moving up is possible and there is no wall in the way
- if (pacmanCurrentIndex - cols >= 0 && !grid[pacmanCurrentIndex - cols].classList.contains('wall')) {
- newIndex -= cols; // Move Pac-Man up by one row
- }
- break;
- case 'ArrowDown': // Move Pac-Man down if the direction is 'ArrowDown'
- // Check if moving down is possible and there is no wall in the way
- if (pacmanCurrentIndex + cols < cols * rows && !grid[pacmanCurrentIndex + cols].classList.contains('wall')) {
- newIndex += cols; // Move Pac-Man down by one row
- }
- break;
- case 'ArrowLeft': // Move Pac-Man left if the direction is 'ArrowLeft'
- // Check if moving left is possible and there is no wall in the way
- if (pacmanCurrentIndex % cols !== 0 && !grid[pacmanCurrentIndex - 1].classList.contains('wall')) {
- newIndex -= 1; // Move Pac-Man left by one column
- }
- break;
- case 'ArrowRight': // Move Pac-Man right if the direction is 'ArrowRight'
- // Check if moving right is possible and there is no wall in the way
- if (pacmanCurrentIndex % cols < cols - 1 && !grid[pacmanCurrentIndex + 1].classList.contains('wall')) {
- newIndex += 1; // Move Pac-Man right by one column
- }
- break;
- }
+ grid[pacmanCurrentIndex].classList.remove('pac-dot'); // Remove 'pac-dot' class if present at Pac-Man's initial position
+ score += 10; // Increase the score by 10 points
+ document.getElementById('scoreValue').textContent = score; // Update the score display
+ console.log('Score:', score); // Output the current score to the console
+ }
- // Check if Pac-Man's position has changed
- if (newIndex !== pacmanCurrentIndex) {
- // Remove Pac-Man from the current position
- grid[pacmanCurrentIndex].classList.remove('pacman');
- pacmanCurrentIndex = newIndex; // Update Pac-Man's current index
- grid[pacmanCurrentIndex].classList.add('pacman'); // Add Pac-Man to the new position
-
- // Check if Pac-Man has eaten a pac-dot
- if (grid[pacmanCurrentIndex].classList.contains('pac-dot')) {
- grid[pacmanCurrentIndex].classList.remove('pac-dot'); // Remove the pac-dot
- score += 10; // Increase the score
- document.getElementById('scoreValue').textContent = score; // Update the score display
- console.log('Score:', score);
-
- // Check if all pac-dots are collected
- if (score === totalPacDots * 10) {
- console.log('Congratulations! You won!');
- }
+ // Function to move Pac-Man
+ const movePacman = () => {
+ if (!gameOver && direction !== null) {
+ let newIndex = pacmanCurrentIndex; // Initialize newIndex with the current Pac-Man index
+
+ // Move Pac-Man based on the current direction
+ switch (direction) {
+ case 'ArrowUp': // Move Pac-Man up if the direction is 'ArrowUp'
+ // Check if moving up is possible and there is no wall in the way
+ if (pacmanCurrentIndex - cols >= 0 && !grid[pacmanCurrentIndex - cols].classList.contains('wall')) {
+ newIndex -= cols; // Move Pac-Man up by one row
+ }
+ break;
+ case 'ArrowDown': // Move Pac-Man down if the direction is 'ArrowDown'
+ // Check if moving down is possible and there is no wall in the way
+ if (pacmanCurrentIndex + cols < cols * rows && !grid[pacmanCurrentIndex + cols].classList.contains('wall')) {
+ newIndex += cols; // Move Pac-Man down by one row
+ }
+ break;
+ case 'ArrowLeft': // Move Pac-Man left if the direction is 'ArrowLeft'
+ // Check if moving left is possible and there is no wall in the way
+ if (pacmanCurrentIndex % cols !== 0 && !grid[pacmanCurrentIndex - 1].classList.contains('wall')) {
+ newIndex -= 1; // Move Pac-Man left by one column
+ }
+ break;
+ case 'ArrowRight': // Move Pac-Man right if the direction is 'ArrowRight'
+ // Check if moving right is possible and there is no wall in the way
+ if (pacmanCurrentIndex % cols < cols - 1 && !grid[pacmanCurrentIndex + 1].classList.contains('wall')) {
+ newIndex += 1; // Move Pac-Man right by one column
+ }
+ break;
+ }
+
+ // Check if Pac-Man's position has changed
+ if (newIndex !== pacmanCurrentIndex) {
+ // Remove Pac-Man from the current position
+ grid[pacmanCurrentIndex].classList.remove('pacman');
+ pacmanCurrentIndex = newIndex; // Update Pac-Man's current index
+ grid[pacmanCurrentIndex].classList.add('pacman'); // Add Pac-Man to the new position
+
+ // Check if Pac-Man has eaten a pac-dot
+ if (grid[pacmanCurrentIndex].classList.contains('pac-dot')) {
+ grid[pacmanCurrentIndex].classList.remove('pac-dot'); // Remove the pac-dot
+ score += 10; // Increase the score
+ document.getElementById('scoreValue').textContent = score; // Update the score display
+ console.log('Score:', score);
+
+ // Call checkForWin function after updating score
+ checkForWin();
}
}
}
};
+ // Function to check for win condition
+ const checkForWin = () => {
+ if (score === 200) { // Aanpassen naar de gewenste winvoorwaarde
+ clearInterval(gameLoop); // Stop the game loop
+
+ // Stop ghost movements
+ ghost1.stop();
+ ghost2.stop();
+
+ // Display win message after a short delay
+ setTimeout(() => {
+ alert("Congratulations! You won!");
+ }, 500);
+
+ gameOver = true; // Set game over flag
+ clearInterval(gameLoop); // Stop the game loop
+
+ // Optionally, reset the game here if needed
+ resetGame();
+ }
+};
+
+
// Check for keydown events to set Pac-Man's direction
+ let direction = null; // Initialize direction as null
document.addEventListener('keydown', (event) => {
const key = event.key;
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(key)) {
@@ -124,20 +149,38 @@ const movePacman = () => {
}
});
+ // Function to end the game
+ const endGame = (isWin) => {
+ gameOver = true; // Set game over flag
+ clearInterval(gameLoop); // Stop the game loop
+
+ // Stop ghost movements
+ ghost1.stop();
+ ghost2.stop();
+
+ // Display game over message
+ const message = isWin ? 'Congratulations! You won!' : 'Game over! You lost!';
+ alert(message); // Display a simple alert message
+
+ // Optionally, you could reset the game here if needed
+ resetGame();
+ };
+
// Game loop
- setInterval(movePacman, 200); // Move Pac-Man every 200ms
+ const gameLoop = setInterval(movePacman, 200); // Move Pac-Man every 200ms
- //Ghost
+ // Ghost
class Ghost {
constructor(startIndex, color) {
// Initialize Ghost
this.currentIndex = startIndex; // Set the current index of the ghost
this.color = color; // Set the color of the ghost
- }
+ this.timerId = null; // Timer ID for ghost movement interval
+ }
moveGhost() {
const directions = [-1, +1, -cols, +cols]; // Possible directions for the ghost
-
+
// Function to calculate distance between two indices on the grid
const distanceToPacman = (ghostIndex, pacmanIndex) => {
const ghostRow = Math.floor(ghostIndex / cols);
@@ -146,37 +189,37 @@ const movePacman = () => {
const pacmanCol = pacmanIndex % cols;
return Math.abs(ghostRow - pacmanRow) + Math.abs(ghostCol - pacmanCol);
};
-
+
// Function to choose the best direction towards Pac-Man
const chooseDirection = () => {
// Get Pac-Man's current index
const pacmanIndex = grid.findIndex(cell => cell.classList.contains('pacman'));
-
+
// Calculate distances for each direction and filter out invalid moves
const validDirections = directions.filter(direction => {
const nextMove = this.currentIndex + direction;
return !grid[nextMove].classList.contains('wall') && !grid[nextMove].classList.contains('ghost');
});
-
+
// Sort directions by distance to Pac-Man
validDirections.sort((dir1, dir2) => {
const nextMove1 = this.currentIndex + dir1;
const nextMove2 = this.currentIndex + dir2;
return distanceToPacman(nextMove1, pacmanIndex) - distanceToPacman(nextMove2, pacmanIndex);
});
-
+
// Return the closest direction if available
return validDirections.length > 0 ? validDirections[0] : null;
};
-
+
let direction = chooseDirection(); // Initial direction
-
+
// Move the ghost at regular intervals
this.timerId = setInterval(() => {
// Logic for ghost movement
- if (direction !== null) {
+ if (!gameOver && direction !== null) {
const nextMove = this.currentIndex + direction; // Calculate the next potential position for the ghost
-
+
// Check if next move isn't a wall or another ghost
if (!grid[nextMove].classList.contains('wall') && !grid[nextMove].classList.contains('ghost')) {
// Remove ghost from the current position
@@ -189,14 +232,21 @@ const movePacman = () => {
// Choose a new direction if the ghost can't move
direction = chooseDirection();
}
- } else {
- // Choose a new direction if no valid direction is found
- direction = chooseDirection();
+
+ // Check if the ghost touched Pac-Man
+ if (this.currentIndex === pacmanCurrentIndex) {
+ gameOver = true;
+ endGame(false); // Pac-Man loses
+ }
}
}, 200); // Move Ghost every 200ms
}
+
+ stop() {
+ clearInterval(this.timerId); // Stop the ghost movement
+ }
}
-
+
// Create ghosts
const ghost1 = new Ghost(209, 'red'); // Place the first ghost
const ghost2 = new Ghost(229, 'blue'); // Place the second ghost
@@ -204,4 +254,5 @@ const movePacman = () => {
// Start ghost movement
ghost1.moveGhost();
ghost2.moveGhost();
-});
\ No newline at end of file
+});
+
From 655f6600058844119de0ca040c4b259594e23763 Mon Sep 17 00:00:00 2001
From: aamira0 <150680980+aamira0@users.noreply.github.com>
Date: Sat, 15 Jun 2024 17:11:36 +0200
Subject: [PATCH 04/22] Update
Update gamewin
---
PacMan/jscrpt.js | 5 +----
1 file changed, 1 insertion(+), 4 deletions(-)
diff --git a/PacMan/jscrpt.js b/PacMan/jscrpt.js
index b03afda5ca..e0254a712d 100644
--- a/PacMan/jscrpt.js
+++ b/PacMan/jscrpt.js
@@ -120,6 +120,7 @@ document.addEventListener('DOMContentLoaded', () => {
// Function to check for win condition
const checkForWin = () => {
if (score === 200) { // Aanpassen naar de gewenste winvoorwaarde
+ gameOver = true; // Set game over flag
clearInterval(gameLoop); // Stop the game loop
// Stop ghost movements
@@ -131,15 +132,11 @@ document.addEventListener('DOMContentLoaded', () => {
alert("Congratulations! You won!");
}, 500);
- gameOver = true; // Set game over flag
- clearInterval(gameLoop); // Stop the game loop
-
// Optionally, reset the game here if needed
resetGame();
}
};
-
// Check for keydown events to set Pac-Man's direction
let direction = null; // Initialize direction as null
document.addEventListener('keydown', (event) => {
From 89eacc9b5765891b6b81dc2c3420cf9e4866b866 Mon Sep 17 00:00:00 2001
From: aamira0 <150680980+aamira0@users.noreply.github.com>
Date: Sat, 15 Jun 2024 18:05:22 +0200
Subject: [PATCH 05/22] Small code updates
---
PacMan/jscrpt.js | 15 ++++++++-------
1 file changed, 8 insertions(+), 7 deletions(-)
diff --git a/PacMan/jscrpt.js b/PacMan/jscrpt.js
index e0254a712d..2b19aea9b3 100644
--- a/PacMan/jscrpt.js
+++ b/PacMan/jscrpt.js
@@ -119,7 +119,7 @@ document.addEventListener('DOMContentLoaded', () => {
// Function to check for win condition
const checkForWin = () => {
- if (score === 200) { // Aanpassen naar de gewenste winvoorwaarde
+ if (score === 300) { // Total score won
gameOver = true; // Set game over flag
clearInterval(gameLoop); // Stop the game loop
@@ -132,7 +132,7 @@ document.addEventListener('DOMContentLoaded', () => {
alert("Congratulations! You won!");
}, 500);
- // Optionally, reset the game here if needed
+ // Reset the game
resetGame();
}
};
@@ -156,10 +156,12 @@ document.addEventListener('DOMContentLoaded', () => {
ghost2.stop();
// Display game over message
- const message = isWin ? 'Congratulations! You won!' : 'Game over! You lost!';
- alert(message); // Display a simple alert message
+ // Display win message after a short delay
+ setTimeout(() => {
+ alert("Game over! You lost!");
+ }, 500);
- // Optionally, you could reset the game here if needed
+ // Reset the game
resetGame();
};
@@ -251,5 +253,4 @@ document.addEventListener('DOMContentLoaded', () => {
// Start ghost movement
ghost1.moveGhost();
ghost2.moveGhost();
-});
-
+});
\ No newline at end of file
From 3a69bbfa508e106605895cc138b7896d0914b381 Mon Sep 17 00:00:00 2001
From: aamira0 <150680980+aamira0@users.noreply.github.com>
Date: Sat, 15 Jun 2024 18:30:41 +0200
Subject: [PATCH 06/22] Update comment
---
PacMan/jscrpt.js | 7 +++----
1 file changed, 3 insertions(+), 4 deletions(-)
diff --git a/PacMan/jscrpt.js b/PacMan/jscrpt.js
index 2b19aea9b3..78d14b4ac7 100644
--- a/PacMan/jscrpt.js
+++ b/PacMan/jscrpt.js
@@ -154,10 +154,9 @@ document.addEventListener('DOMContentLoaded', () => {
// Stop ghost movements
ghost1.stop();
ghost2.stop();
-
- // Display game over message
- // Display win message after a short delay
- setTimeout(() => {
+
+ // Display win message after a short delay
+ setTimeout(() => {
alert("Game over! You lost!");
}, 500);
From dea6e13aef33716e2c96932d62146a0346831e92 Mon Sep 17 00:00:00 2001
From: aamira0 <150680980+aamira0@users.noreply.github.com>
Date: Sat, 15 Jun 2024 23:13:54 +0200
Subject: [PATCH 07/22] Game ends
-game ends when player wins
-game ends when lives are up and ghost gets the player
-display lives
---
PacMan/index.html | 6 +
PacMan/jscrpt.js | 315 +++++++++++++++++++++++++++-------------------
PacMan/style.css | 18 +++
3 files changed, 212 insertions(+), 127 deletions(-)
diff --git a/PacMan/index.html b/PacMan/index.html
index 1ef0d9ca8c..2a7dd4a7fc 100644
--- a/PacMan/index.html
+++ b/PacMan/index.html
@@ -15,6 +15,12 @@