|
15 | 15 | drawWorld,
|
16 | 16 | updateWorld,
|
17 | 17 | clamp,
|
| 18 | + canWalk, |
18 | 19 | } = fur
|
19 | 20 |
|
20 | 21 | function init () {
|
|
62 | 63 | const context = canvas.getContext('2d')
|
63 | 64 |
|
64 | 65 | window.addEventListener('keydown', ({ key }) => {
|
65 |
| - const prevPosition = { ...state.player.position } |
| 66 | + const { position } = state.player |
| 67 | + const prevPosition = { ...position } |
66 | 68 |
|
67 |
| - let moveKey = false |
68 | 69 | if (key === 'ArrowUp') {
|
69 |
| - state.player.position.direction = 0 |
70 |
| - state.player.position.y -= 1 |
71 |
| - moveKey = true |
| 70 | + position.direction = 0 |
| 71 | + if (canWalk(objects, state, { x: position.x, y: position.y - 1 })) { |
| 72 | + position.y -= 1 |
| 73 | + } |
72 | 74 | } else if (key === 'ArrowLeft') {
|
73 |
| - state.player.position.direction = 1 |
74 |
| - state.player.position.x -= 1 |
75 |
| - moveKey = true |
| 75 | + position.direction = 1 |
| 76 | + if (canWalk(objects, state, { x: position.x - 1, y: position.y })) { |
| 77 | + position.x -= 1 |
| 78 | + } |
76 | 79 | } else if (key === 'ArrowDown') {
|
77 |
| - state.player.position.direction = 2 |
78 |
| - state.player.position.y += 1 |
79 |
| - moveKey = true |
| 80 | + position.direction = 2 |
| 81 | + if (canWalk(objects, state, { x: position.x, y: position.y + 1 })) { |
| 82 | + position.y += 1 |
| 83 | + } |
80 | 84 | } else if (key === 'ArrowRight') {
|
81 |
| - state.player.position.direction = 3 |
82 |
| - state.player.position.x += 1 |
83 |
| - moveKey = true |
| 85 | + position.direction = 3 |
| 86 | + if (canWalk(objects, state, { x: position.x + 1, y: position.y })) { |
| 87 | + position.x += 1 |
| 88 | + } |
84 | 89 | } else if (key === 'a') {
|
85 |
| - applyUseRules(state.player.position) |
| 90 | + applyUseRules(position) |
86 | 91 | }
|
87 | 92 |
|
88 |
| - if (moveKey) { |
| 93 | + if ( |
| 94 | + prevPosition.x !== position.x || |
| 95 | + prevPosition.y !== position.y |
| 96 | + ) { |
89 | 97 | clamp(
|
90 |
| - state.player.position, |
| 98 | + position, |
91 | 99 | { x: 0, y: 0 },
|
92 |
| - levelSize[state.player.position.level], |
| 100 | + levelSize[position.level], |
93 | 101 | )
|
94 | 102 |
|
95 | 103 | if (
|
96 |
| - prevPosition.x !== state.player.position.x || |
97 |
| - prevPosition.y !== state.player.position.y |
| 104 | + prevPosition.x !== position.x || |
| 105 | + prevPosition.y !== position.y |
98 | 106 | ) {
|
99 | 107 | applyLeaveRules(prevPosition)
|
100 | 108 |
|
101 |
| - applyEnterRules(state.player.position) |
| 109 | + applyEnterRules(position) |
102 | 110 |
|
103 |
| - applyNearRules(state.player.position) |
| 111 | + applyNearRules(position) |
104 | 112 | }
|
105 | 113 | }
|
106 | 114 |
|
|
0 commit comments