salva-la-costanera/src/utils.ts

94 lines
2.2 KiB
TypeScript
Raw Normal View History

2021-06-30 21:18:13 +00:00
import { Juego } from "./main";
2021-06-28 18:01:45 +00:00
export type Pos = {
2021-06-30 23:16:45 +00:00
x: number;
y: number;
2021-06-28 18:01:45 +00:00
};
export type Box = Pos & {
2021-06-30 23:16:45 +00:00
width: number;
height: number;
};
2021-06-30 21:18:13 +00:00
2021-06-28 18:01:45 +00:00
export function posInBox(box: Box, pos: Pos) {
2021-06-30 23:16:45 +00:00
return (
pos.x > box.x &&
pos.x < box.x + box.width &&
pos.y > box.y &&
pos.y < box.y + box.height
);
2021-06-28 18:01:45 +00:00
}
2021-06-28 19:02:12 +00:00
export function boxCollision(box1: Box, box2: Box) {
2021-06-30 23:16:45 +00:00
// http://stackoverflow.com/questions/2440377/ddg#7301852
return !(
box1.y + box1.height < box2.y ||
box1.y > box2.y + box2.height ||
box1.x + box1.width < box2.x ||
box1.x > box2.x + box2.width
);
2021-06-28 19:02:12 +00:00
}
2021-06-28 18:01:45 +00:00
2021-06-30 23:16:45 +00:00
export function drawText(
juego: Juego<any>,
text: string,
pos: Pos,
{
2021-06-30 21:18:13 +00:00
bold = false,
size = 2,
align = "left",
baseline = "top",
maxWidth,
2021-06-30 23:16:45 +00:00
}: {
align?: CanvasTextAlign;
baseline?: CanvasTextBaseline;
bold?: boolean;
2021-06-30 21:18:13 +00:00
// in rem
2021-06-30 23:16:45 +00:00
size?: number;
maxWidth?: number;
2021-06-30 23:16:45 +00:00
}
): Box {
juego.ctx.font = `${bold ? "bold " : ""}${size * 12}px sans-serif`;
2021-06-30 23:16:45 +00:00
juego.ctx.textAlign = align;
juego.ctx.textBaseline = baseline;
juego.ctx.fillText(text, pos.x, pos.y, maxWidth);
2021-06-30 21:18:13 +00:00
2021-06-30 23:16:45 +00:00
const measure = juego.ctx.measureText(text);
return {
...pos,
width: measure.width,
height: measure.actualBoundingBoxDescent,
};
2021-06-30 21:18:13 +00:00
}
export function randomFromArray<T>(array: T[]): T {
2021-06-30 23:16:45 +00:00
return array[Math.floor(Math.random() * array.length)];
}
2021-07-01 22:33:51 +00:00
export function isMobile(juego: Juego<any>): boolean {
return !!juego.touches;
2021-07-01 22:33:51 +00:00
}
export function isTouching(juego: Juego<any>, box: Box): boolean {
return !!(
juego.touches &&
Array.from(juego.touches).some((t) =>
posInBox(box, { x: t.pageX, y: t.pageY })
)
);
}
2021-07-06 17:09:21 +00:00
export async function share() {
const text =
"¿Sabías que Larreta quiere vender la Costanera para construir un mega emprendimiento inmobiliario de lujo? Estamos juntando firmas para frenarlo, ya vamos 20 mil y nos faltan 20 mil más. ¿Te animas a jugar a este videojuego para salvar la costanera?";
try {
await navigator.share({
title: "Salvá la Costanera",
url: location.href,
text,
});
} catch (error) {
location.href = `https://api.whatsapp.com/send?text=${encodeURIComponent(
text + " " + location.href
)}`;
}
}