Newer
Older
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
import React from 'react'
import LevelData, { Inputs } from '../game/Level'
function* __rangeInner(start, end, step) {
let c = start
while (c < end) {
yield c
c += step
}
}
function range(...args) {
if (args.length === 1) {
const [end] = args
return __rangeInner(0, end, 1)
}
if (args.length === 2) {
const [start, end] = args
return __rangeInner(start, end, 1)
}
if (args.length === 3) {
const [start, end, step] = args
return __rangeInner(start, end, step)
}
throw new TypeError('Invalid number of arguments')
}
type Props = {
scale?: number,
size?: number,
margin?: number,
level: LevelData,
}
export default class Level extends React.Component<Props> {
static defaultProps = {
scale: 1,
size: 32,
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
active: false,
}
state = {
nonce: Math.random(),
}
componentDidMount(): void {
window.addEventListener('keyup', this.handleKeyPress)
}
handleKeyPress = async e => {
e.preventDefault()
if (this.state.active > 0) {
return
}
const { key } = e
let input = null
switch (key.toLowerCase()) {
case 'arrowleft':
case 'a':
input = Inputs.Controls.Left
break
case 'arrowright':
case 'd':
input = Inputs.Controls.Right
break
case 'arrowdown':
case 's':
input = Inputs.Controls.Down
break
case 'arrowup':
case 'w':
input = Inputs.Controls.Up
break
case ' ':
input = Inputs.Actions.Wait
break
}
if (input) {
this.setState(s => ({ active: s.active + 1 }))
await this.props.level.processInput(input)
this.setState(s => ({ nonce: Math.random(), active: s.active - 1 }))
}
}
render() {
const {scale, size, margin, level} = this.props
const {width, height} = level
return (
<div className="level-container">
{[...range(width)].map(x =>
[...range(height)].map(y => (
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
left: (margin * x) + (x * 32 * scale),
top: (margin * y) + (y * 32 * scale),
width: size * scale,
height: size * scale
}}/>
))
).reduce((a, c) => (a || []).concat(c))}
{level.entities.map(entity => {
const {x, y, image} = entity.renderProps
const left = (margin * x) + (x * 32 * scale)
const top = (margin * y) + (y * 32 * scale)
return (
<img className="level-entity" src={image} style={{
left,
top,
width: size * scale,
height: size * scale
}}/>
)
})}
{level.connectors.map(connector => {
const {x, y, type: cType} = connector
const left = (margin * x) + (x * 32 * scale)
const top = (margin * y) + (y * 32 * scale)
return (
<img className="level-entity" src={`/${ cType }-text.png`} style={{
left,
top,
width: size * scale,
height: size * scale
}}/>
)
})}
</div>
)
}
}