arquivo main.js
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
canvas.width = 1024
canvas.height = 690
let y = 10
let frames = 0
let timeLimit = 90
let textTime = ''
const carros = []
const imagesCarros = [
'./assets/sprites/carro_verde.png',
'./assets/sprites/carro_vermelho.png',
'./assets/sprites/carro_roxo.png',
'./assets/sprites/carro_laranja.png',
'./assets/sprites/carro_amarelo.png',
'./assets/sprites/carro_azul.png',
'./assets/sprites/carro_oliva.png',
'./assets/sprites/carro_rosa.png',
'./assets/sprites/carro_telha.png'
]
function getImage(src) {
img = new Image()
img.src = src
return img
}
const board = {
image: getImage('./assets/sprites/pista.png'),
draw() {
//linha 1
ctx.drawImage(this.image, 0, 0)
}
}
function drawTimer() {
let textMetricos = ctx.measureText(textTime)
ctx.fillStyle = 'yellow'
ctx.font = '20px "Press Start 2P"'
ctx.fillText(textTime, `${canvas.width / 2 - textMetricos.width / 2}`, 35)
}
//Agentes do game
const galinha1 = new Galinha(
canvas.width * 0.25,
canvas.height - 35,
getImage('./assets/sprites/galinha_1.png')
)
function movimento(galinha, key) {
if (galinha === galinha1) {
if (key.up.g1.pressed) {
galinha1.dirY = -1
galinha.animation()
} else if (key.down.g1.pressed) {
galinha1.dirY = 1
galinha.animation()
} else {
galinha.dirY = 0
}
} else if (galinha === galinha2) {
if (key.up.g2.pressed) {
galinha2.dirY = -1
} else if (key.down.g2.pressed) {
galinha2.dirY = 1
} else {
galinha.dirY = 0
}
}
}
const galinha2 = new Galinha(
canvas.width * 0.75,
canvas.height - 35,
getImage('./assets/sprites/galinha_1.png')
)
const carroVerde = new Carros(canvas.width, 48, 5, getImage(imagesCarros[0]))
const carroVermelho = new Carros(
canvas.width,
105,
10,
getImage(imagesCarros[1])
)
const carroRoxo = new Carros(canvas.width, 166, 8, getImage(imagesCarros[2]))
const carroLaranja = new Carros(canvas.width, 227, 3, getImage(imagesCarros[3]))
carros.push(carroVerde)
carros.push(carroVermelho)
carros.push(carroRoxo)
carros.push(carroLaranja)
function game() {
ctx.fillStyle = '#ABABAB'
ctx.fillRect(0, 0, canvas.width, canvas.height)
board.draw()
drawTimer()
galinha1.draw()
galinha2.draw()
galinha1.drawScore(canvas.width * 0.25)
galinha2.drawScore(canvas.width * 0.75)
galinha1.update()
galinha2.update()
movimento(galinha1, keys)
movimento(galinha2, keys)
carros.forEach((carro) => {
carro.update()
carro.draw()
galinha1.colisao(carro)
galinha2.colisao(carro)
})
frames++
requestAnimationFrame(game)
}
game()
let min = Math.floor(timeLimit / 60)
let sec = timeLimit % 60
function cronometro() {
if (timeLimit > 0) {
timeLimit--
textTime = ''
min = Math.floor(timeLimit / 60)
sec = timeLimit % 60
if (min < 10) {
textTime += `0${min}`
} else {
textTime += `${min}`
}
if (sec < 10) {
textTime += `:0${sec}`
} else {
textTime += `:${sec}`
}
} else {
textTime = '00:00'
}
}
setInterval(cronometro, 1000)