implement basic box functionality.

This commit is contained in:
HyperOnion 2023-06-23 12:05:40 +02:00 committed by transoptimal
parent b4976a0d94
commit f7caf8a3a8
3 changed files with 77 additions and 10 deletions

View File

@ -32,9 +32,18 @@ export function draw_world (box_size, get_tile) {
iter_2d(range(0, box_size - 1), (x, y) => {
const tile = get_tile(x, y);
if (tile === "player") {
graphics.set_color("#0f0");
draw_tile(x, y);
switch (tile.type) {
case "player": {
graphics.set_color("#0f0");
draw_tile(x, y);
break;
}
case "box": {
graphics.set_color("#ff0");
draw_tile(x, y);
break;
}
}
});
}

View File

@ -1,4 +1,4 @@
import { BOX_SIZE, get_tile, set_tile } from "./world.mjs";
import * as world from "./world.mjs";
import { on_press } from "./input.mjs";
@ -7,11 +7,38 @@ const player = {
x: 2,
y: 1,
};
set_tile(player.x, player.y, "player");
world.set_tile(player.x, player.y, { type: "player" });
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) {
set_tile(player.x, player.y, 0);
set_tile(x, y, "player");
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;
}
@ -32,3 +59,10 @@ on_press("ArrowUp", _ => {
on_press("ArrowDown", _ => {
move_player(0, 1);
});
on_press(" ", _ => {
world.set_tile(player.x + 1, player.y, {
type: "box",
box: world.create_box(),
});
});

View File

@ -1,12 +1,36 @@
export const BOX_SIZE = 9;
export const CENTER = Math.floor(BOX_SIZE / 2);
const world = Array(BOX_SIZE).fill(0).map(_ => Array(BOX_SIZE).fill(0));
function create_world (size) {
return Array(BOX_SIZE).fill(0).map(_ => Array(BOX_SIZE).fill(0));
}
const world = create_world(BOX_SIZE);
const parent_stack = [];
let current_world = world;
export function set_tile (x, y, tile) {
world[x][y] = tile;
current_world[x][y] = tile;
}
export function get_tile (x, y) {
return world[x][y];
return current_world[x][y];
}
export function create_box () {
return create_world(BOX_SIZE);
}
export function enter_box (box) {
parent_stack.push(current_world);
current_world = box;
}
export function exit_box () {
if (parent_stack.length > 0) {
current_world = parent_stack.pop();
return true;
}
return false;
}