Professional Documents
Culture Documents
Pacman
Pacman
addEventListener('DOMContentLoaded', () => {
const squares = []
//create Characters
//draw pacman onto the board
let pacmanCurrentIndex = 490
squares[pacmanCurrentIndex].classList.add('pac-man')
//get the coordinates of pacman on the grid with X and Y axis
// function getCoordinates(index) {
// return [index % width, Math.floor(index / width)]
// }
// console.log(getCoordinates(pacmanCurrentIndex))
//move pacman
function movePacman(e) {
squares[pacmanCurrentIndex].classList.remove('pac-man')
switch(e.keyCode) {
case 37:
if(
pacmanCurrentIndex % width !== 0 &&
!squares[pacmanCurrentIndex -1].classList.contains('wall') &&
!squares[pacmanCurrentIndex -1].classList.contains('ghost-lair')
)
pacmanCurrentIndex -= 1
if (squares[pacmanCurrentIndex -1] === squares[363]) {
pacmanCurrentIndex = 391
}
break
case 38:
if(
pacmanCurrentIndex - width >= 0 &&
!squares[pacmanCurrentIndex -width].classList.contains('wall') &&
!squares[pacmanCurrentIndex -width].classList.contains('ghost-lair')
)
pacmanCurrentIndex -= width
break
case 39:
if(
pacmanCurrentIndex % width < width - 1 &&
!squares[pacmanCurrentIndex +1].classList.contains('wall') &&
!squares[pacmanCurrentIndex +1].classList.contains('ghost-lair')
)
pacmanCurrentIndex += 1
if (squares[pacmanCurrentIndex +1] === squares[392]) {
pacmanCurrentIndex = 364
}
break
case 40:
if (
pacmanCurrentIndex + width < width * width &&
!squares[pacmanCurrentIndex +width].classList.contains('wall') &&
!squares[pacmanCurrentIndex +width].classList.contains('ghost-lair')
)
pacmanCurrentIndex += width
break
}
squares[pacmanCurrentIndex].classList.add('pac-man')
pacDotEaten()
powerPelletEaten()
checkForGameOver()
checkForWin()
}
document.addEventListener('keyup', movePacman)
//all my ghosts
ghosts = [
new Ghost('blinky', 348, 250),
new Ghost('pinky', 376, 400),
new Ghost('inky', 351, 300),
new Ghost('clyde', 379, 500)
]
function moveGhost(ghost) {
const directions = [-1, +1, width, -width]
let direction = directions[Math.floor(Math.random() * directions.length)]
ghost.timerId = setInterval(function() {
//if the next squre your ghost is going to go to does not have a ghost and
does not have a wall
if (!squares[ghost.currentIndex + direction].classList.contains('ghost')
&&
!squares[ghost.currentIndex + direction].classList.contains('wall') ) {
//remove the ghosts classes
squares[ghost.currentIndex].classList.remove(ghost.className)
squares[ghost.currentIndex].classList.remove('ghost', 'scared-ghost')
//move into that space
ghost.currentIndex += direction
squares[ghost.currentIndex].classList.add(ghost.className, 'ghost')
//else find a new random direction ot go in
} else direction = directions[Math.floor(Math.random() *
directions.length)]