-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.js
49 lines (46 loc) · 1.36 KB
/
list.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
import getControls from "./controls.js";
import { clamp } from "./utils.js";
export default class List {
constructor(ctx, { items, onSelect, x = 0, y = 0 }) {
this.ctx = ctx;
this.items = items;
this.x = x;
this.y = y;
this.selectedIndex = 0;
this.controlIndex = 0;
this.onSelect = onSelect;
this.prevControl = this.getControl();
}
getControl() {
return getControls()[this.controlIndex];
}
update() {
const prevControl = this.prevControl;
const control = this.getControl();
if (prevControl.down && !control.down) {
this.selectedIndex++;
this.selectedIndex = clamp(this.selectedIndex, 0, this.items.length - 1);
} else if (prevControl.up && !control.up) {
this.selectedIndex--;
this.selectedIndex = clamp(this.selectedIndex, 0, this.items.length - 1);
} else if (prevControl.start && !control.start) {
this.onSelect(this.items[this.selectedIndex]);
}
this.prevControl = control;
}
render() {
const height = 30;
const xOffset = -26;
let itemY = height + this.y;
this.ctx.font = `20px Gameplay`;
this.items.forEach((item, i) => {
const selected = this.selectedIndex === i;
this.ctx.fillText(
selected ? `► ${item.text}` : `${item.text}`,
this.x + (selected ? xOffset : 0),
itemY
);
itemY += height;
});
}
}