-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.html
95 lines (83 loc) · 2.47 KB
/
index.html
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<!doctype html>
<html>
<head>
<title>Manuel!</title>
<style>canvas { border: 1px solid #999; }</style>
</head>
<body>
<canvas></canvas>
<script src="./support.js"></script>
<script src="./immutable.min.js"></script>
<script>
var canvasEl = document.querySelector('canvas');
var ctx = canvasEl.getContext('2d');
var BOULDER_HEIGHT = 20;
var BOULDER_WIDTH = 20;
function clearCanvas() {
canvasEl.width = 500;
canvasEl.height = 300;
}
function drawBackground(state) {
var boulderPos = state.get('boulderPos');
ctx.fillStyle = '#008A00';
ctx.fillRect(0, 250, 500, 50);
ctx.fillStyle = '#ccc';
ctx.fillRect(boulderPos.get('x'), boulderPos.get('y'),
BOULDER_WIDTH, BOULDER_HEIGHT);
return [];
}
function processInput(state) {
var currX = state.getIn(['pos', 'x']);
if (dpad.right) {
return [{op: 'setIn', path: ['pos', 'x'], value: currX + 3}];
} else if (dpad.left) {
return [{op: 'setIn', path: ['pos', 'x'], value: currX - 3}];
}
return [];
}
function drawManuel(state) {
var pos = state.get('pos');
ctx.fillStyle = '#AF8452';
ctx.fillRect(pos.get('x') + 5, pos.get('y') - 10, 10, 10);
ctx.fillStyle = '#C91B13';
ctx.fillRect(pos.get('x'), pos.get('y'), 20, 20);
ctx.fillRect(pos.get('x'), pos.get('y') + 20, 8, 10);
ctx.fillRect(pos.get('x') + 12, pos.get('y') + 20, 8, 10);
return [];
}
function handleCollisions(state) {
var pos = state.get('pos');
var boulderPos = state.get('boulderPos');
// If Manuel is overlapping the boulder, move him.
if (pos.get('x') + 20 > boulderPos.get('x')) {
return [{op: 'setIn', path: ['pos', 'x'], value: boulderPos.get('x') - 20}];
}
return []; // No update.
}
function applyUpdates(state, updates) {
return updates.reduce(function(prevState, update) {
switch (update.op) {
case 'setIn':
return prevState.setIn(update.path, update.value);
default:
throw new Error("Unknown op '" + update.op + "'");
}
}, state);
}
var initialState = Immutable.Map({
pos: Immutable.Map({x: 200, y: 220}), // Manuel's position.
boulderPos: Immutable.Map({x: 300, y: 230})
});
window.requestAnimationFrame(function render(state) {
clearCanvas();
var updates = []
.concat(processInput(state))
.concat(handleCollisions(state))
.concat(drawBackground(state))
.concat(drawManuel(state));
var newState = applyUpdates(state, updates);
window.requestAnimationFrame(render.bind(null, newState));
}.bind(null, initialState));
</script>
</body>
</html>