-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathsokoban.js
72 lines (57 loc) · 1.4 KB
/
sokoban.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
kaplay({
background: [45, 33, 51],
});
loadSprite("bean", "/sprites/bean.png");
loadSprite("grass", "/sprites/grass.png");
loadSprite("steel", "/sprites/steel.png");
const level = addLevel([
".......",
".p d.",
". b b .",
". .",
".......",
], {
tileWidth: 64,
tileHeight: 64,
tiles: {
p: () => [sprite("bean"), "player"],
b: () => [sprite("grass"), "box"],
".": () => [sprite("steel"), "wall"],
},
});
const player = level.get("player")[0];
const hasTag = (objs, tag) => objs.findIndex(obj => obj.is(tag)) !== -1;
const moveObj = (obj, dir) => {
if (dir.x == 1) obj.moveRight();
if (dir.x == -1) obj.moveLeft();
if (dir.y == 1) obj.moveDown();
if (dir.y == -1) obj.moveUp();
};
const move = (dir) => {
const moveTo = player.tilePos.add(dir);
const occupant = level.getAt(moveTo);
if (hasTag(occupant, "wall")) {
return;
}
if (hasTag(occupant, "box")) {
const boxMoveTo = occupant[0].tilePos.add(dir);
const boxOccupant = level.getAt(boxMoveTo);
if (boxOccupant.length !== 0) {
return;
}
moveObj(occupant[0], dir);
}
moveObj(player, dir);
};
onKeyPress("d", () => {
move(vec2(1, 0));
});
onKeyPress("a", () => {
move(vec2(-1, 0));
});
onKeyPress("w", () => {
move(vec2(0, -1));
});
onKeyPress("s", () => {
move(vec2(0, 1));
});