This repository has been archived by the owner on Sep 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GameCreation.tsx
343 lines (310 loc) · 13.9 KB
/
GameCreation.tsx
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
96
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import { remote } from 'electron'
import * as React from 'react'
import { Button, Input, SelectBox } from './photon-fix/Components'
import { GameCreationOptions, GameType, HumanPlayer, Player, PlayerType, StartType } from '../api/rules/GameCreationOptions'
import { Api } from '../api/Api'
import * as fs from 'fs'
import * as v from 'validate-typescript'
import { loadFromStorage } from '../helpers/Cache'
import { useValue } from '../helpers/Controls'
import { GameInfo } from '../api/synchronous/GameInfo'
import { Logger } from '../api/Logger'
import { stringify } from '../helpers/Utils'
const dialog = remote.dialog
const localStorageCreationOptions = 'creationOptions'
const localStorageProgramPath = 'defaultProgramPath'
type Errors = Array<string>
// Interface to hold the value for an input along with its validation status
interface FieldState<V> {
value: V
errors: Errors
}
// The game creation form holds settings for two players, which structure are the same for each player.
interface FormState {
generalErrors: Errors
gameName: FieldState<string>
players: PlayerFormState[]
}
// These are the settings for each player.
interface PlayerFormState {
type: FieldState<PlayerType>
name: FieldState<string>
path: FieldState<string>
timeoutEnabled: FieldState<boolean>
}
class ErrorList extends React.PureComponent<{ errors: Array<string> }> {
render() {
const listItems = this.props.errors.map((error) =>
<li>{error}</li>,
)
return <ul>{listItems}</ul>
}
}
export class GameCreation extends React.Component<{ serverPort: number, createGame: (GameCreationOptions) => Promise<GameInfo> }, FormState> {
constructor(props) {
super(props)
let kioskMode = require('electron').remote.getGlobal('kioskMode')
let defaults = {
generalErrors: [],
gameName: GameCreation.unvalidatedField('Neue Begegnung'),
players: [GameCreation.newPlayerForm((kioskMode ? PlayerType.Human : PlayerType.Computer)), GameCreation.newPlayerForm(PlayerType.Human)],
}
const schema = {
generalErrors: [v.Type(String)],
gameName: GameCreation.fieldStateSchema(String),
players: [
{
type: { value: v.Options(Object.keys(PlayerType)), errors: [v.Type(String)] },
name: GameCreation.fieldStateSchema(String),
path: GameCreation.fieldStateSchema(String),
timeoutEnabled: GameCreation.fieldStateSchema(Boolean),
},
],
}
this.state = loadFromStorage(localStorageCreationOptions, schema, defaults)
if (kioskMode) {
this.state.players[0].name.value = 'Spieler 1'
this.state.players[1].name.value = 'Spieler 2'
}
}
private static fieldStateSchema(type) {
return { value: v.Type(type), errors: [v.Type(String)] }
}
private static newPlayerForm(type: PlayerType) {
return {
type: this.unvalidatedField(type),
name: this.unvalidatedField(type),
path: this.unvalidatedField(null),
timeoutEnabled: this.unvalidatedField(true),
}
}
private static unvalidatedField(value) { return { value: value, errors: [] } }
// To be called as onChange handler on form controls. Takes a setter function which changes the form state according to the new value. Special handling for checkboxes, because they provide their value different from all other input elements.
private handleControlChange(setter: (s: FormState, val: string) => void): (event: any) => void {
return useValue(value => {
this.setState((prev, _props) => {
setter(prev, value)
return prev
})
})
}
// shows a file select dialog and calls the given setter with the selected file
private clientFileSelectDialog(setter: (s: FormState, firstSelectedFilename: string) => void): void {
dialog.showOpenDialog(null,
{
title: 'Wähle einen Computerspieler',
properties: ['openFile'],
}).then(result => {
if (!result.canceled && result.filePaths.length > 0 && result.filePaths[0]) {
window.localStorage[localStorageProgramPath] = result.filePaths[0]
this.setState((prev, _props) => {
setter(prev, result.filePaths[0])
return prev
})
}
})
}
private static createPlayer(playerSettings: PlayerFormState): Player {
switch (playerSettings.type.value) {
case PlayerType.Human:
return {
kind: PlayerType.Human,
name: playerSettings.name.value,
timeoutPossible: false,
} as HumanPlayer
case PlayerType.Computer:
return {
kind: PlayerType.Computer,
name: playerSettings.name.value,
timeoutPossible: playerSettings.timeoutEnabled.value,
path: playerSettings.path.value,
startType: playerSettings.path.value.endsWith('.jar') ? StartType.Java : StartType.Direct,
}
case PlayerType.Manual:
return {
kind: PlayerType.Manual,
name: playerSettings.name.value,
timeoutPossible: playerSettings.timeoutEnabled.value,
}
}
}
// is called when the user wants to start a game with a valid configuration
private handleStartGame(parsed: GameCreationOptions) {
window.localStorage[localStorageCreationOptions] = JSON.stringify(this.state)
if (this.state.players.some(p => p.type.value == PlayerType.Manual)) {
document.getElementById('waiting').style.opacity = '1'
}
this.props.createGame(parsed).catch(reason => {
console.log('Error starting the game:', reason)
let s = stringify(reason)
document.getElementById('errors').innerText =
reason.client ? `Spieler ${reason.client} konnte nicht erfolgreich gestartet werden: ${stringify(reason.error)}` : `Fehler beim Starten des Spiels: ${s}`
Logger.getLogger().log('GameCreation', 'createGame', 'Failed to start game: ' + s)
})
}
private static isEmpty(v: string): boolean {
return v == null || v.trim() === ''
}
private static invalidPath(path: string): boolean {
return this.isEmpty(path) || !fs.existsSync(path)
}
// Validates form settings an sets appropriate error states for invalid states. Returns true if settings are valid, false if not.
private validate(state: FormState): boolean {
let valid = true
state.generalErrors = []
state.gameName.errors = []
if (GameCreation.isEmpty(state.gameName.value)) {
state.gameName.errors.push('Der Name des Spiels darf nicht leer sein.')
valid = false
}
state.players.map((player: PlayerFormState) => {
player.name.errors = []
if (GameCreation.isEmpty(player.name.value)) {
player.name.errors.push('Der Name des Spielers darf nicht leer sein.')
valid = false
}
player.path.errors = []
if (player.type.value == PlayerType.Computer) {
if (GameCreation.invalidPath(player.path.value)) {
player.path.errors.push('Bitte wähle einen Computerspieler aus.')
valid = false
}
}
})
return valid
}
private static hasErrors(field: FieldState<any>): boolean {
return field.errors.length > 0
}
// Returns the sub-form to make changes to the settings for each player. Takes a function which should select the player for which the sub-form should show and change the settings.
private playerControl(formState: FormState, player: (s: FormState) => PlayerFormState) {
let playerForm = player(formState)
switch (playerForm.type.value) {
case PlayerType.Computer:
if (require('electron').remote.getGlobal('kioskMode')) {
this.state.players[1].path.value = 'defaultplayer.jar'
return
}
return (<div>
Wähle ein Programm zum starten
<Button text="Computerspieler wählen"
onClick={() => this.clientFileSelectDialog((state, firstSelectedPath) => {
if (firstSelectedPath) {
player(state).path.value = firstSelectedPath
}
})}/>
<code className={GameCreation.hasErrors(playerForm.path) ? 'validation-errors' : ''}>{playerForm.path.value}</code>
<label className="validation-errors">{playerForm.path.errors}</label>
</div>)
case PlayerType.Manual:
return <p>Das Programm muss nach Erstellung des Spiels gestartet werden. Es sollte sich dann auf localhost,
Port {this.props.serverPort} verbinden.</p>
default:
return
}
}
render() {
console.log('GameCreation State:', JSON.stringify(this.state))
let kioskMode = require('electron').remote.getGlobal('kioskMode')
const playerTypes = (kioskMode ? [
{ label: 'Mitspieler', value: PlayerType.Human },
{ label: 'Computer', value: PlayerType.Computer },
] : [
{ label: 'Mensch', value: PlayerType.Human },
{ label: 'Computer', value: PlayerType.Computer },
{ label: 'Manuell gestarteter Client', value: PlayerType.Manual },
])
let playerForm = (player: integer) => (
<div>
<Input id={'input_playerName' + player} value={this.state.players[player].name.value}
onChange={this.handleControlChange((state, value) => state.players[player].name.value = value)}
invalid={GameCreation.hasErrors(this.state.players[player].name)}/>
<label htmlFor={'input_playerName' + player}
className="validation-errors">{this.state.players[player].name.errors}</label>
<br/>
<SelectBox value={this.state.players[player].type.value} items={playerTypes}
onChange={this.handleControlChange((state, value: PlayerType) => {
state.players[player].type.value = value
})}/>
{this.playerControl(this.state, s => s.players[player])}
</div>
)
let startControl = this.validate(this.state) ?
// current settings are valid, user may start the game
<Button text="Start!" pullRight={true} onClick={() => {
// game should be started, create a game configuration from the given settings
this.handleStartGame({
kind: GameType.Versus,
firstPlayer: GameCreation.createPlayer(this.state.players[0]),
secondPlayer: GameCreation.createPlayer(this.state.players[1]),
gameName: this.state.gameName.value,
gameId: Api.getGameManager().createGameId(this.state.gameName.value, false),
})
}}/>
:
<div className="validation-errors pull-right">
<p>Bitte korrigieren Sie die rot markierten Probleme, um ein Spiel zu starten.</p>
<ErrorList errors={this.state.generalErrors}/>
</div>
if (kioskMode) {
this.state.players[0].type.value = PlayerType.Human
return (
<div className="game-creation main-container">
<div className="content">
<div style={{ textAlign: 'center' }}>
<h3>Erstelle ein neues Spiel</h3>
</div>
<p style={{ marginBottom: '0' }}>Spieler 1:</p>
<div>
<Input id="input_playerName0" value={this.state.players[0].name.value}
onChange={this.handleControlChange((state, value) => state.players[0].name.value = value)}
invalid={GameCreation.hasErrors(this.state.players[0].name)}/>
<label htmlFor="input_playerName0"
className="validation-errors">{this.state.players[0].name.errors}</label>
<br/>
{this.playerControl(this.state, s => s.players[0])}
</div>
<div id="vs">spielt gegen</div>
<p style={{ marginBottom: '0' }}>Spieler 2:</p>
{playerForm(1)}
<div id="start">
<Button text="Start!" pullRight={true} onClick={() => {
// game should be started, create a game configuration from the given settings
this.handleStartGame({
kind: GameType.Versus,
firstPlayer: GameCreation.createPlayer(this.state.players[0]),
secondPlayer: GameCreation.createPlayer(this.state.players[1]),
gameName: this.state.gameName.value,
gameId: Api.getGameManager().createGameId(this.state.gameName.value, false),
})
}}/>
</div>
</div>
</div>
)
}
return (
<div className="game-creation main-container">
<div className="content">
<Input id="input_gameName" value={this.state.gameName.value}
onChange={this.handleControlChange((state, value) => state.gameName.value = value)}
invalid={GameCreation.hasErrors(this.state.gameName)}/>
<label htmlFor="input_gameName" className="validation-errors">{this.state.gameName.errors}</label>
<br/>
{playerForm(0)}
<div id="vs">gegen</div>
{playerForm(1)}
<div id="waiting">
Warte auf manuellen Spieler
(sollte sich auf Port {this.props.serverPort} verbinden)
</div>
<div id="start">
{startControl}
</div>
<div id="errors"/>
<div className="clearfix"/>
</div>
</div>
)
}
}