salva-la-costanera/src/jugando.ts

94 lines
2.8 KiB
TypeScript
Raw Normal View History

2021-06-28 18:01:45 +00:00
import { loadSprite } from './sprite'
import { Juego } from './main'
const larretaImg = document.getElementById("img-larreta") as HTMLImageElement
const inmobiliariaImg = document.getElementById("img-inmobiliaria") as HTMLImageElement
const veredaImg = document.getElementById("img-vereda") as HTMLImageElement
const fondoImg = document.getElementById("img-fondo") as HTMLImageElement
const jugadorxImg = document.getElementById("img-jugadorx") as HTMLImageElement
const jugadorxSprite = loadSprite(jugadorxImg, 133, 266, juego => juego.canvas.height / 4)
const larretaSprite = loadSprite(larretaImg, 800, 1069, juego => juego.canvas.height / 4)
export type State = {
current: "jugando"
pos: { x: number }
view: { x: number }
velocity: { x: number }
enemies: { x: number }[]
}
export function createJugandoState(): State {
return {
current: "jugando",
pos: { x: 3000 },
view: { x: 0 },
velocity: { x: 0 },
enemies: [{ x: 2700 }],
}
}
export function update(juego: Juego<State>, dt: number) {
juego.state.velocity.x = 0
if (juego.keyboard.keys.d) {
juego.state.velocity.x += 200
}
if (juego.keyboard.keys.a) {
juego.state.velocity.x -= 200
}
juego.state.pos.x += (dt / 1000) * juego.state.velocity.x
if (juego.state.pos.x < 2000) juego.state.pos.x = 2000
if (juego.state.pos.x > 4000) juego.state.pos.x = 4000
juego.state.view.x = -juego.state.pos.x + juego.canvas.width / 2 - jugadorxSprite.getWidth(juego) / 2
}
function drawBackground(
juego: Juego<State>,
y: number | ((height: number) => number),
height: number,
img: HTMLImageElement,
) {
const aspect = img.width / img.height
const width = height * aspect
const realY = typeof y === 'function' ? y(height) : y
for (let i = 0; i < 10; i++) {
juego.ctx.drawImage(img, i * (width - 1) + juego.state.view.x, realY, width, height)
}
return realY
}
function drawJugadorx(juego: Juego<State>, floorY: number) {
const height = jugadorxSprite.getHeight(juego)
jugadorxSprite.draw(
juego,
juego.state.pos.x + juego.state.view.x,
floorY - height,
0
)
}
function drawEnemies(juego: Juego<State>, floorY: number) {
const height = larretaSprite.getHeight(juego)
for (const enemy of juego.state.enemies) {
larretaSprite.draw(
juego,
enemy.x + juego.state.view.x,
floorY - height,
0
)
}
}
export function draw(juego: Juego<State>, timestamp: number) {
const { height } = juego.canvas
drawBackground(juego, 0, (height / 3) * 2, fondoImg)
const floorY = drawBackground(juego, h => height - h, height / 3, veredaImg)
drawEnemies(juego, floorY)
drawJugadorx(juego, floorY)
}