
Golf
Juegas un recorrido de golf golpe a golpe: eliges el palo, apuntas teniendo en cuenta el viento y el terreno y marcas la fuerza del golpe, a menudo con una barra que detienes en el momento justo. Ganas metiendo la bola en cada hoyo en el menor número de golpes.
También se llama: videojuego de golf, minigolf
Esta es una ficha básica: tiene la definición y la clasificación. Las fichas completas suman historia, juegos y una demo.
Demo propia
Controles. Flechas izquierda y derecha (o A/D) o el ratón para apuntar, C o flecha arriba para cambiar de palo, y espacio, Enter o clic dos veces, una para arrancar la barra de potencia y otra para detenerla. En pantallas táctiles, toca hacia dónde quieres tirar y vuelve a tocar para detener la barra, o usa los botones.
Abrir en pantalla completaUn recorrido corto de tres hoyos visto desde arriba, con calle, rough, búnkeres de arena y agua. En cada golpe eliges palo, apuntas teniendo en cuenta el viento y fijas la fuerza con la barra que sube y baja. Al final, una tarjeta compara tus golpes con el par.
Hecha con Kaplay, en unas 225 líneas de JavaScript.
Cómo está hecha
Configuración
Se crea el juego con cuatro botones virtuales (girar a cada lado, cambiar de palo y golpear) y sus botones táctiles. Las constantes fijan el máximo de golpes por hoyo, el tamaño del hoyo y la velocidad por encima de la cual la bola pasa por encima sin entrar.
const k = kaplay({ width: 640, height: 360, letterbox: true, pixelDensity, background: [70, 120, 60], buttons: { left: { keyboard: ["left", "a"] }, right: { keyboard: ["right", "d"] }, club: { keyboard: ["c", "up", "w"] }, swing: { keyboard: ["space", "enter"] }, }, }); touchControls(k, [ { button: "left", label: "↺" }, { button: "right", label: "↻" }, { button: "club", label: "♣", side: "right" }, { button: "swing", label: "●", side: "right" }, ]); const MAX_STROKES = 10; // after this the ball is picked up, so a hole never lasts forever const CUP_R = 7; const CUP_SPEED = 230; // faster than this, the ball rolls over the cupLos palos
Cada palo tiene un alcance máximo. La madera llega más lejos y el hierro menos, pero ambos levantan la bola. El putter nunca vuela, solo la hace rodar. Elegir palo es la primera decisión de cada golpe.
// Each club has a maximum carry. The putter never flies: it only rolls. const CLUBS = [ { name: { es: "Madera", en: "Wood" }, carry: 260 }, { name: { es: "Hierro", en: "Iron" }, carry: 160 }, { name: { es: "Putter", en: "Putter" }, roll: 150 }, ];El recorrido
Cada hoyo es una lista de formas (rectángulos y círculos) con su tipo de terreno, y la última forma bajo un punto decide qué terreno hay ahí. Lo que no está en ninguna forma es rough. Cada terreno tiene su fricción, que es lo que hace que la bola ruede lejos en el green y casi nada en la arena. Para diseñar un hoyo nuevo basta con añadir otra entrada a HOLES.
// Every hole is a list of shapes drawn in order; the last shape under a point // decides its terrain, and anything outside every shape is rough. const HOLES = [ { par: 3, tee: [70, 200], cup: [545, 180], shapes: [ ["fairway", "rect", 50, 160, 440, 80], ["sand", "circle", 445, 128, 28], ["water", "rect", 290, 250, 110, 110], ["green", "circle", 545, 180, 55], ], }, { par: 4, tee: [70, 300], cup: [560, 85], shapes: [ ["fairway", "rect", 40, 265, 360, 65], ["fairway", "rect", 330, 70, 90, 260], ["water", "rect", 440, 175, 200, 110], ["sand", "circle", 480, 140, 24], ["green", "circle", 560, 85, 50], ], }, { par: 3, tee: [110, 185], cup: [470, 190], shapes: [ ["fairway", "rect", 40, 145, 150, 80], ["water", "rect", 200, 60, 120, 260], ["sand", "circle", 410, 115, 22], ["sand", "circle", 420, 270, 22], ["green", "circle", 470, 190, 62], ], }, ]; // Rolling friction in px/s² and the colour of each terrain. const TERRAIN = { green: { friction: 110, color: [120, 200, 100] }, fairway: { friction: 220, color: [95, 165, 75] }, rough: { friction: 480, color: [70, 120, 60] }, sand: { friction: 1300, color: [225, 205, 140] }, water: { friction: 0, color: [60, 120, 200] }, }; function terrainAt(hole, p) { if (p.x < 0 || p.y < 30 || p.x > 640 || p.y > 360) return "water"; // out of bounds counts as a hazard let found = "rough"; for (const [type, shape, x, y, a, b] of hole.shapes) { const inside = shape === "rect" ? p.x >= x && p.x <= x + a && p.y >= y && p.y <= y + b : p.dist(vec2(x, y)) <= a; if (inside) found = type; } return found; }La bola
La bola guarda en qué fase del golpe estás (apuntar, barra, vuelo, rodar), su altura, su velocidad, el palo y los golpes. Al empezar y después de cada golpe se elige un palo según la distancia al hoyo y el terreno.
// state: aim → meter → flight → roll → aim. The meter oscillates until you stop it. const ball = add([pos(...hole.tee), "ball", { state: "aim", z: 0, vel: vec2(0), aim: cup.sub(...hole.tee).angle(), club: 0, power: 0, meterT: 0, strokes: 0, last: vec2(...hole.tee), flight: null, cup, wind, }]); const pickClub = () => { const d = ball.pos.dist(cup); ball.club = terrainAt(hole, ball.pos) === "green" ? 2 : d > 200 ? 0 : 1; }; pickClub();Apuntar y la barra de potencia
Apuntas girando con las flechas o señalando con el ratón. La barra de potencia es el control clásico del género. El primer toque la pone en marcha, sube hasta el cien por cien y vuelve a bajar, y el segundo toque la detiene. Acertar el momento es una habilidad de reflejos dentro de un juego que, por lo demás, no tiene prisa.
onButtonDown("left", () => ball.state === "aim" && (ball.aim -= 90 * dt())); onButtonDown("right", () => ball.state === "aim" && (ball.aim += 90 * dt())); onButtonPress("club", () => ball.state === "aim" && (ball.club = (ball.club + 1) % CLUBS.length)); onMouseMove((p) => ball.state === "aim" && (ball.aim = p.sub(ball.pos).angle())); onButtonPress("swing", swing); onClick(() => { if (ball.state === "aim") ball.aim = mousePos().sub(ball.pos).angle(); swing(); }); function swing() { if (ball.state === "aim") { ball.state = "meter"; ball.meterT = 0; } else if (ball.state === "meter") hit(ball.power); } // The classic meter: power climbs to 100 % and falls back, 1.6 s per cycle. onFixedUpdate(() => { if (ball.state !== "meter") return; ball.meterT += fixedDt(); const ph = (ball.meterT / 1.6) % 1; ball.power = ph < 0.5 ? ph * 2 : 2 - ph * 2; });El golpe
Con el putter se calcula la velocidad justa para que la bola se detenga a la distancia elegida sobre el green. Con los otros palos se calcula el punto de caída, que es la dirección por la distancia, más lo que el viento empuja durante el vuelo. Por eso conviene apuntar un poco contra el viento.
function hit(power) { power = Math.max(power, 0.03); ball.strokes++; ball.last = ball.pos.clone(); const dir = Vec2.fromAngle(ball.aim); const club = CLUBS[ball.club]; if (club.roll) { // Speed that, with the green's friction, stops after exactly roll × power px. ball.vel = dir.scale(Math.sqrt(2 * TERRAIN.green.friction * club.roll * power)); ball.state = "roll"; return; } const carry = club.carry * power; const time = 0.6 + carry / 300; // The landing spot: straight ahead, plus how far the wind pushes during the flight. const to = ball.pos.add(dir.scale(carry)).add(wind.scale(time)); ball.flight = { from: ball.pos.clone(), to, time, t: 0, height: 20 + carry / 5, speed: carry * 0.5 }; ball.state = "flight"; }Vuelo y rodada
En el aire, la bola va del punto de salida al de caída y su altura sigue una parábola. Al caer, rueda y frena según la fricción del terreno que pisa. Si toca el agua hay penalización, y si pasa por el hoyo lo bastante lenta, entra. Todo corre en pasos fijos de 50 por segundo, para que un fotograma lento no haga que la bola salte por encima del hoyo.
// Fixed 50 Hz steps, so a slow frame never lets the ball skip over the cup. onFixedUpdate(() => { const h = fixedDt(); if (ball.state === "flight") { const f = ball.flight; f.t = Math.min(1, f.t + h / f.time); ball.pos = f.from.lerp(f.to, f.t); ball.z = 4 * f.height * f.t * (1 - f.t); // a parabola: 0 at both ends if (f.t === 1) { ball.z = 0; ball.vel = f.to.sub(f.from).unit().scale(f.speed); ball.state = "roll"; } } else if (ball.state === "roll") { ball.pos = ball.pos.add(ball.vel.scale(h)); const ground = terrainAt(hole, ball.pos); if (ground === "water") return penalty(); if (ball.pos.dist(cup) < CUP_R && ball.vel.len() < CUP_SPEED) return holed(); const speed = Math.max(0, ball.vel.len() - TERRAIN[ground].friction * h); ball.vel = ball.vel.unit().scale(speed); if (speed < 4) rest(); } }); function rest() { ball.state = "aim"; ball.aim = cup.sub(ball.pos).angle(); pickClub(); if (ball.strokes >= MAX_STROKES) holed(); } // Water: one penalty stroke and back to where you hit from. function penalty() { ball.strokes++; ball.pos = ball.last.clone(); flash(t({ es: "¡Al agua! +1 golpe", en: "In the water! +1 stroke" })); rest(); } function holed() { ball.state = "done"; const diff = ball.strokes - hole.par; const names = { "-2": ["Eagle", "Eagle"], "-1": ["Birdie", "Birdie"], 0: ["Par", "Par"], 1: ["Bogey", "Bogey"] }; const [es, en] = names[diff] ?? (diff < 0 ? ["¡Increíble!", "Amazing!"] : [`+${diff}`, `+${diff}`]); flash(t({ es, en })); const next = [...card, ball.strokes]; wait(1.6, () => (holeIndex + 1 < HOLES.length ? go("game", holeIndex + 1, next) : go("end", next))); } function flash(msg) { const m = add([text(msg, { size: 28, font: FONT }), pos(320, 180), anchor("center"), color(255, 255, 255), opacity(1)]); m.onUpdate(() => (m.opacity -= dt() * 0.7)); wait(1.5, () => m.destroy()); }Dibujo y marcador
Se dibujan el terreno, la bandera, la línea de mira (tan larga como el golpe más fuerte del palo) y la bola con su sombra. La sombra se queda en el suelo y la bola sube y crece, así se ve la altura en una vista desde arriba. Arriba van el hoyo, el par, los golpes, el palo y una flecha con la fuerza del viento.
onDraw(() => { for (const [type, shape, x, y, a, b] of hole.shapes) { const c = rgb(...TERRAIN[type].color); if (shape === "rect") drawRect({ pos: vec2(x, y), width: a, height: b, color: c, radius: 14 }); else drawCircle({ pos: vec2(x, y), radius: a, color: c }); } drawCircle({ pos: cup, radius: CUP_R - 2, color: rgb(20, 30, 20) }); drawLine({ p1: cup, p2: cup.sub(0, 30), width: 2, color: rgb(240, 240, 240) }); drawTriangle({ p1: cup.sub(0, 30), p2: cup.sub(-16, 24), p3: cup.sub(0, 18), color: rgb(230, 60, 60) }); if (ball.state === "aim" || ball.state === "meter") { // Aim line as long as the club's full shot (without wind). const club = CLUBS[ball.club]; const end = ball.pos.add(Vec2.fromAngle(ball.aim).scale(club.carry ?? club.roll)); drawLine({ p1: ball.pos, p2: end, width: 2, color: rgb(255, 255, 255), opacity: 0.45 }); drawCircle({ pos: end, radius: 4, outline: { width: 2, color: rgb(255, 255, 255) }, fill: false }); } // The shadow stays on the ground; the ball rises above it and looks bigger the higher it is. drawCircle({ pos: ball.pos, radius: 4, color: rgb(0, 0, 0), opacity: 0.3 }); drawCircle({ pos: ball.pos.sub(0, ball.z), radius: 4 + ball.z / 25, color: rgb(255, 255, 255) }); // HUD: hole, par, strokes, club, wind arrow and power meter. drawRect({ pos: vec2(0, 0), width: 640, height: 30, color: rgb(20, 40, 25) }); const info = t({ es: `Hoyo ${holeIndex + 1}/3 · Par ${hole.par} · Golpes ${ball.strokes} · Palo: `, en: `Hole ${holeIndex + 1}/3 · Par ${hole.par} · Strokes ${ball.strokes} · Club: ` }); drawText({ text: info + t(CLUBS[ball.club].name), pos: vec2(10, 8), size: 15, font: FONT }); const wc = vec2(540, 15); const tip = wc.add(wind.unit().scale(4 + wind.len() / 3)); drawLine({ p1: wc, p2: tip, width: 3, color: rgb(200, 230, 255) }); drawCircle({ pos: tip, radius: 3, color: rgb(200, 230, 255) }); drawText({ text: `${t({ es: "viento", en: "wind" })} ${Math.round(wind.len())}`, pos: vec2(562, 8), size: 13, font: FONT, color: rgb(200, 230, 255) }); if (ball.state === "meter") { drawRect({ pos: vec2(600, 60), width: 20, height: 200, color: rgb(30, 30, 30), outline: { width: 2, color: rgb(255, 255, 255) } }); drawRect({ pos: vec2(602, 258 - 196 * ball.power), width: 16, height: 196 * ball.power, color: rgb(255, 200 - 150 * ball.power, 60) }); } });Escenas y tarjeta
Título, juego y tarjeta final. Al terminar cada hoyo aparece el nombre del resultado (birdie, par, bogey…), y la tarjeta suma los golpes y los compara con el par total. Contar golpes contra el par es lo que convierte una serie de tiros en una partida de golf.
function screen(lines, next) { add([text(lines, { size: 16, font: FONT, align: "center", width: 560, lineSpacing: 6 }), pos(center()), anchor("center")]); wait(0.5, () => { onButtonPress("swing", next); onClick(next); }); } scene("title", () => screen( t({ es: "Golf\n\nTres hoyos. Apunta con ←/→ o el ratón, cambia de palo con C\ny pulsa espacio dos veces: una para empezar la barra de potencia\ny otra para detenerla. El viento desvía la bola en el aire.\n\nEspacio o clic para empezar.", en: "Golf\n\nThree holes. Aim with ←/→ or the mouse, change club with C\nand press space twice: once to start the power meter\nand again to stop it. The wind pushes the ball while it flies.\n\nSpace or click to start.", }), () => go("game", 0, []), ), ); // The scorecard: strokes against par for each hole. scene("end", (card) => { const total = card.reduce((a, b) => a + b, 0); const par = HOLES.reduce((a, h) => a + h.par, 0); const diff = total - par; const rows = card.map((s, i) => `${t({ es: "Hoyo", en: "Hole" })} ${i + 1} Par ${HOLES[i].par} ${s}`).join("\n"); screen( `${t({ es: "Tarjeta", en: "Scorecard" })}\n\n${rows}\n\nTotal ${total} (${diff > 0 ? "+" : ""}${diff === 0 ? "par" : diff})\n\n${t({ es: "Espacio o clic para volver a jugar.", en: "Space or click to play again." })}`, () => go("title"), ); }); go("title");
Qué simplificamos
- La bola vuela en línea recta hacia el punto de caída y solo el viento la desvía. No hay efecto (slice o hook), ni golpes altos o bajos, ni pendientes en el green.
- Hay tres palos en vez de catorce, y el palo se elige solo según la distancia y el terreno. Tú puedes cambiarlo.
- Si la bola cae al agua o sale del mapa, sumas un golpe y vuelves a tirar desde donde estabas. Con diez golpes en un hoyo, la bola se levanta y pasas al siguiente.
Para modificarla
- Diseña un cuarto hoyo en HOLES, de par 4 o 5, con un dogleg y un búnker que castigue al que quiera atajar.
- Añade pendiente al green, una fuerza constante que empuje la bola hacia un lado mientras rueda, y dibuja una flecha que la muestre.
- Cambia la barra de potencia por una de tres toques, como en muchos juegos de golf, en la que el tercer toque decide la precisión y desvía la bola si llega tarde o temprano.
Código completo
// Golf demo
// Engine: Kaplay 3001 (https://kaplayjs.com). MIT licence.
import kaplay from "../../vendor/kaplay.mjs";
import { t, FONT, touchControls, pixelDensity } from "../common.js";
// #region setup
const k = kaplay({
width: 640,
height: 360,
letterbox: true, pixelDensity,
background: [70, 120, 60],
buttons: {
left: { keyboard: ["left", "a"] },
right: { keyboard: ["right", "d"] },
club: { keyboard: ["c", "up", "w"] },
swing: { keyboard: ["space", "enter"] },
},
});
touchControls(k, [
{ button: "left", label: "↺" },
{ button: "right", label: "↻" },
{ button: "club", label: "♣", side: "right" },
{ button: "swing", label: "●", side: "right" },
]);
const MAX_STROKES = 10; // after this the ball is picked up, so a hole never lasts forever
const CUP_R = 7;
const CUP_SPEED = 230; // faster than this, the ball rolls over the cup
// #endregion
// #region clubs
// Each club has a maximum carry. The putter never flies: it only rolls.
const CLUBS = [
{ name: { es: "Madera", en: "Wood" }, carry: 260 },
{ name: { es: "Hierro", en: "Iron" }, carry: 160 },
{ name: { es: "Putter", en: "Putter" }, roll: 150 },
];
// #endregion
// #region course
// Every hole is a list of shapes drawn in order; the last shape under a point
// decides its terrain, and anything outside every shape is rough.
const HOLES = [
{
par: 3, tee: [70, 200], cup: [545, 180],
shapes: [
["fairway", "rect", 50, 160, 440, 80], ["sand", "circle", 445, 128, 28],
["water", "rect", 290, 250, 110, 110], ["green", "circle", 545, 180, 55],
],
},
{
par: 4, tee: [70, 300], cup: [560, 85],
shapes: [
["fairway", "rect", 40, 265, 360, 65], ["fairway", "rect", 330, 70, 90, 260],
["water", "rect", 440, 175, 200, 110], ["sand", "circle", 480, 140, 24],
["green", "circle", 560, 85, 50],
],
},
{
par: 3, tee: [110, 185], cup: [470, 190],
shapes: [
["fairway", "rect", 40, 145, 150, 80], ["water", "rect", 200, 60, 120, 260],
["sand", "circle", 410, 115, 22], ["sand", "circle", 420, 270, 22], ["green", "circle", 470, 190, 62],
],
},
];
// Rolling friction in px/s² and the colour of each terrain.
const TERRAIN = {
green: { friction: 110, color: [120, 200, 100] },
fairway: { friction: 220, color: [95, 165, 75] },
rough: { friction: 480, color: [70, 120, 60] },
sand: { friction: 1300, color: [225, 205, 140] },
water: { friction: 0, color: [60, 120, 200] },
};
function terrainAt(hole, p) {
if (p.x < 0 || p.y < 30 || p.x > 640 || p.y > 360) return "water"; // out of bounds counts as a hazard
let found = "rough";
for (const [type, shape, x, y, a, b] of hole.shapes) {
const inside = shape === "rect" ? p.x >= x && p.x <= x + a && p.y >= y && p.y <= y + b : p.dist(vec2(x, y)) <= a;
if (inside) found = type;
}
return found;
}
// #endregion
scene("game", (holeIndex, card) => {
const hole = HOLES[holeIndex];
const cup = vec2(...hole.cup);
const wind = Vec2.fromAngle(rand(0, 360)).scale(rand(5, 30)); // px/s of drift while the ball is in the air
// #region ball
// state: aim → meter → flight → roll → aim. The meter oscillates until you stop it.
const ball = add([pos(...hole.tee), "ball", {
state: "aim", z: 0, vel: vec2(0), aim: cup.sub(...hole.tee).angle(), club: 0, power: 0, meterT: 0,
strokes: 0, last: vec2(...hole.tee), flight: null, cup, wind,
}]);
const pickClub = () => {
const d = ball.pos.dist(cup);
ball.club = terrainAt(hole, ball.pos) === "green" ? 2 : d > 200 ? 0 : 1;
};
pickClub();
// #endregion
// #region aim-and-meter
onButtonDown("left", () => ball.state === "aim" && (ball.aim -= 90 * dt()));
onButtonDown("right", () => ball.state === "aim" && (ball.aim += 90 * dt()));
onButtonPress("club", () => ball.state === "aim" && (ball.club = (ball.club + 1) % CLUBS.length));
onMouseMove((p) => ball.state === "aim" && (ball.aim = p.sub(ball.pos).angle()));
onButtonPress("swing", swing);
onClick(() => {
if (ball.state === "aim") ball.aim = mousePos().sub(ball.pos).angle();
swing();
});
function swing() {
if (ball.state === "aim") {
ball.state = "meter";
ball.meterT = 0;
} else if (ball.state === "meter") hit(ball.power);
}
// The classic meter: power climbs to 100 % and falls back, 1.6 s per cycle.
onFixedUpdate(() => {
if (ball.state !== "meter") return;
ball.meterT += fixedDt();
const ph = (ball.meterT / 1.6) % 1;
ball.power = ph < 0.5 ? ph * 2 : 2 - ph * 2;
});
// #endregion
// #region shot
function hit(power) {
power = Math.max(power, 0.03);
ball.strokes++;
ball.last = ball.pos.clone();
const dir = Vec2.fromAngle(ball.aim);
const club = CLUBS[ball.club];
if (club.roll) {
// Speed that, with the green's friction, stops after exactly roll × power px.
ball.vel = dir.scale(Math.sqrt(2 * TERRAIN.green.friction * club.roll * power));
ball.state = "roll";
return;
}
const carry = club.carry * power;
const time = 0.6 + carry / 300;
// The landing spot: straight ahead, plus how far the wind pushes during the flight.
const to = ball.pos.add(dir.scale(carry)).add(wind.scale(time));
ball.flight = { from: ball.pos.clone(), to, time, t: 0, height: 20 + carry / 5, speed: carry * 0.5 };
ball.state = "flight";
}
// #endregion
// #region physics
// Fixed 50 Hz steps, so a slow frame never lets the ball skip over the cup.
onFixedUpdate(() => {
const h = fixedDt();
if (ball.state === "flight") {
const f = ball.flight;
f.t = Math.min(1, f.t + h / f.time);
ball.pos = f.from.lerp(f.to, f.t);
ball.z = 4 * f.height * f.t * (1 - f.t); // a parabola: 0 at both ends
if (f.t === 1) {
ball.z = 0;
ball.vel = f.to.sub(f.from).unit().scale(f.speed);
ball.state = "roll";
}
} else if (ball.state === "roll") {
ball.pos = ball.pos.add(ball.vel.scale(h));
const ground = terrainAt(hole, ball.pos);
if (ground === "water") return penalty();
if (ball.pos.dist(cup) < CUP_R && ball.vel.len() < CUP_SPEED) return holed();
const speed = Math.max(0, ball.vel.len() - TERRAIN[ground].friction * h);
ball.vel = ball.vel.unit().scale(speed);
if (speed < 4) rest();
}
});
function rest() {
ball.state = "aim";
ball.aim = cup.sub(ball.pos).angle();
pickClub();
if (ball.strokes >= MAX_STROKES) holed();
}
// Water: one penalty stroke and back to where you hit from.
function penalty() {
ball.strokes++;
ball.pos = ball.last.clone();
flash(t({ es: "¡Al agua! +1 golpe", en: "In the water! +1 stroke" }));
rest();
}
function holed() {
ball.state = "done";
const diff = ball.strokes - hole.par;
const names = { "-2": ["Eagle", "Eagle"], "-1": ["Birdie", "Birdie"], 0: ["Par", "Par"], 1: ["Bogey", "Bogey"] };
const [es, en] = names[diff] ?? (diff < 0 ? ["¡Increíble!", "Amazing!"] : [`+${diff}`, `+${diff}`]);
flash(t({ es, en }));
const next = [...card, ball.strokes];
wait(1.6, () => (holeIndex + 1 < HOLES.length ? go("game", holeIndex + 1, next) : go("end", next)));
}
function flash(msg) {
const m = add([text(msg, { size: 28, font: FONT }), pos(320, 180), anchor("center"), color(255, 255, 255), opacity(1)]);
m.onUpdate(() => (m.opacity -= dt() * 0.7));
wait(1.5, () => m.destroy());
}
// #endregion
// #region drawing
onDraw(() => {
for (const [type, shape, x, y, a, b] of hole.shapes) {
const c = rgb(...TERRAIN[type].color);
if (shape === "rect") drawRect({ pos: vec2(x, y), width: a, height: b, color: c, radius: 14 });
else drawCircle({ pos: vec2(x, y), radius: a, color: c });
}
drawCircle({ pos: cup, radius: CUP_R - 2, color: rgb(20, 30, 20) });
drawLine({ p1: cup, p2: cup.sub(0, 30), width: 2, color: rgb(240, 240, 240) });
drawTriangle({ p1: cup.sub(0, 30), p2: cup.sub(-16, 24), p3: cup.sub(0, 18), color: rgb(230, 60, 60) });
if (ball.state === "aim" || ball.state === "meter") {
// Aim line as long as the club's full shot (without wind).
const club = CLUBS[ball.club];
const end = ball.pos.add(Vec2.fromAngle(ball.aim).scale(club.carry ?? club.roll));
drawLine({ p1: ball.pos, p2: end, width: 2, color: rgb(255, 255, 255), opacity: 0.45 });
drawCircle({ pos: end, radius: 4, outline: { width: 2, color: rgb(255, 255, 255) }, fill: false });
}
// The shadow stays on the ground; the ball rises above it and looks bigger the higher it is.
drawCircle({ pos: ball.pos, radius: 4, color: rgb(0, 0, 0), opacity: 0.3 });
drawCircle({ pos: ball.pos.sub(0, ball.z), radius: 4 + ball.z / 25, color: rgb(255, 255, 255) });
// HUD: hole, par, strokes, club, wind arrow and power meter.
drawRect({ pos: vec2(0, 0), width: 640, height: 30, color: rgb(20, 40, 25) });
const info = t({ es: `Hoyo ${holeIndex + 1}/3 · Par ${hole.par} · Golpes ${ball.strokes} · Palo: `, en: `Hole ${holeIndex + 1}/3 · Par ${hole.par} · Strokes ${ball.strokes} · Club: ` });
drawText({ text: info + t(CLUBS[ball.club].name), pos: vec2(10, 8), size: 15, font: FONT });
const wc = vec2(540, 15);
const tip = wc.add(wind.unit().scale(4 + wind.len() / 3));
drawLine({ p1: wc, p2: tip, width: 3, color: rgb(200, 230, 255) });
drawCircle({ pos: tip, radius: 3, color: rgb(200, 230, 255) });
drawText({ text: `${t({ es: "viento", en: "wind" })} ${Math.round(wind.len())}`, pos: vec2(562, 8), size: 13, font: FONT, color: rgb(200, 230, 255) });
if (ball.state === "meter") {
drawRect({ pos: vec2(600, 60), width: 20, height: 200, color: rgb(30, 30, 30), outline: { width: 2, color: rgb(255, 255, 255) } });
drawRect({ pos: vec2(602, 258 - 196 * ball.power), width: 16, height: 196 * ball.power, color: rgb(255, 200 - 150 * ball.power, 60) });
}
});
// #endregion
});
// #region scenes
function screen(lines, next) {
add([text(lines, { size: 16, font: FONT, align: "center", width: 560, lineSpacing: 6 }), pos(center()), anchor("center")]);
wait(0.5, () => {
onButtonPress("swing", next);
onClick(next);
});
}
scene("title", () =>
screen(
t({
es: "Golf\n\nTres hoyos. Apunta con ←/→ o el ratón, cambia de palo con C\ny pulsa espacio dos veces: una para empezar la barra de potencia\ny otra para detenerla. El viento desvía la bola en el aire.\n\nEspacio o clic para empezar.",
en: "Golf\n\nThree holes. Aim with ←/→ or the mouse, change club with C\nand press space twice: once to start the power meter\nand again to stop it. The wind pushes the ball while it flies.\n\nSpace or click to start.",
}),
() => go("game", 0, []),
),
);
// The scorecard: strokes against par for each hole.
scene("end", (card) => {
const total = card.reduce((a, b) => a + b, 0);
const par = HOLES.reduce((a, h) => a + h.par, 0);
const diff = total - par;
const rows = card.map((s, i) => `${t({ es: "Hoyo", en: "Hole" })} ${i + 1} Par ${HOLES[i].par} ${s}`).join("\n");
screen(
`${t({ es: "Tarjeta", en: "Scorecard" })}\n\n${rows}\n\nTotal ${total} (${diff > 0 ? "+" : ""}${diff === 0 ? "par" : diff})\n\n${t({ es: "Espacio o clic para volver a jugar.", en: "Space or click to play again." })}`,
() => go("title"),
);
});
go("title");
// #endregionHistoria
- 1978Origen
La lista de videojuegos de golf de Wikipedia empieza con Computer Golf! (1978), de Magnavox, para Odyssey².
List of golf video games (Wikipedia) - 1984Golf
Golf, de Nintendo y HAL Laboratory, sale para Famicom y se convierte en el juego de deportes más vendido de esa consola.
Golf (1984 video game) (Wikipedia) - 1997Everybody's Golf
Everybody's Golf (Hot Shots Golf), de Camelot, inicia una serie de golf desenfadado para PlayStation; Camelot hará después Mario Golf para Nintendo.
Everybody's Golf (1997 video game) (Wikipedia)
Juegos de referencia
1984
Golf
Golf de Nintendo para Famicom (NES en 1985 en Norteamérica). Fue el juego de deportes más vendido de la consola y lo programó Satoru Iwata, luego presidente de Nintendo.
1997
Everybody's Golf
Golf de tono desenfadado, llamado Hot Shots Golf en Norteamérica y Minna no Golf en Japón. Es el primero de su serie y el único hecho por Camelot, que después desarrolló Mario Golf.