Skip to content

Commit

Permalink
PacTroll wrapped up
Browse files Browse the repository at this point in the history
  • Loading branch information
thomax committed Apr 30, 2024
1 parent 2de829c commit 361cc10
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions Eksamen/v23/10-b/game.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,22 @@ function gameLoop() {
// remove food
food.element.remove()
foods.splice(index, 1)
// spawn obstacle
spawnObstacle(food.x, food.y)
// spawn obstacle, but wait to avoid instakill
setTimeout(() => {
spawnObstacle(food.x, food.y)
}, 500)
spawnFood()
}
})

// check obstacle collision
obstacles.forEach(obstacle => {
if (isColliding(obstacle.rect(), troll.rect())) {
gameOver = true
gameOverReason = 'You hit an obstacle'
}
})

window.requestAnimationFrame(gameLoop)
}
}
Expand All @@ -119,10 +130,25 @@ function spawnFood() {
gameAreaElement.appendChild(element)
const x = randomBetween(0, gameWidth - spriteSize)
const y = randomBetween(0, gameHeight - spriteSize)
food = new Food(x, y, element)
const food = new Food(x, y, element)

const allTheThings = foods.concat(obstacles).concat([troll])
ensureItemNotOverlappingWithThings(food, allTheThings)

foods.push(food)
}

function ensureItemNotOverlappingWithThings(item, things) {
things.forEach(thing => {
while (isColliding(thing.rect(), item.rect())) {
console.log('overlapping, reposition')
const x = randomBetween(0, gameWidth - spriteSize)
const y = randomBetween(0, gameHeight - spriteSize)
item.positionAt(x, y)
}
})
}

function spawnObstacle(x, y) {
const element = document.createElement('div')
element.classList.add('obstacle')
Expand Down

0 comments on commit 361cc10

Please sign in to comment.