boxes/js/player.mjs

62 lines
1.2 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";
import * as entity from "./entity.mjs";
const player = entity.create(2, 1, "#0f0");
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
}
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)) {
const could_exit = world.exit_box();
if (could_exit) {
set_player_pos(0, 0);
} else {
set_player_pos(previous_x, previous_y);
2023-06-23 10:05:40 +00:00
}
return;
}
if (world.get_tile(x, y)?.type === "box") {
world.enter_box(world.get_tile(x, y).box);
set_player_pos(world.CENTER, world.CENTER);
return;
}
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(),
});
});