boxes/js/player.mjs

69 lines
1.4 KiB
JavaScript
Raw Normal View History

2023-06-23 10:05:40 +00:00
import * as world from "./world.mjs";
import { on_press } from "./input.mjs";
const player = {
x: 2,
y: 1,
};
2023-06-23 10:05:40 +00:00
world.set_tile(player.x, player.y, { type: "player" });
2023-06-23 10:05:40 +00:00
function out_of_bounds (x, y) {
return x < 0 || x >= world.BOX_SIZE ||
y < 0 || y >= world.BOX_SIZE
}
// TODO: clean up this by making tile movement be performed by the world code.
export function set_player_pos (x, y) {
2023-06-23 10:05:40 +00:00
const previous_x = player.x;
const previous_y = player.y;
if (out_of_bounds(x, y)) {
world.set_tile(previous_x, previous_y, 0);
const could_exit = world.exit_box();
if (could_exit) {
set_player_pos(0, 0);
} else {
world.set_tile(x, y, { type: "player" });
}
return;
}
if (world.get_tile(x, y)?.type === "box") {
world.set_tile(previous_x, previous_y, 0);
world.enter_box(world.get_tile(x, y).box);
set_player_pos(world.CENTER, world.CENTER);
return;
}
world.set_tile(previous_x, previous_y, 0);
world.set_tile(x, y, { type: "player" });
player.x = x;
player.y = y;
}
export function move_player (d_x, d_y) {
set_player_pos(player.x + d_x, player.y + d_y);
}
on_press("ArrowLeft", _ => {
move_player(-1, 0);
});
on_press("ArrowRight", _ => {
move_player(1, 0);
});
on_press("ArrowUp", _ => {
move_player(0, -1);
});
on_press("ArrowDown", _ => {
move_player(0, 1);
});
2023-06-23 10:05:40 +00:00
on_press(" ", _ => {
world.set_tile(player.x + 1, player.y, {
type: "box",
box: world.create_box(),
});
});