This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathjs.go
491 lines (455 loc) · 11.2 KB
/
js.go
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
// +build js
package main
import (
"encoding/base64"
"errors"
"fmt"
"log"
"runtime"
"time"
"unicode/utf8"
"syscall/js"
)
func main() {
ui := &gameui{}
err := ui.Init()
if err != nil {
log.Fatalf("boohu: %v\n", err)
}
defer ui.Close()
GameConfig.Tiles = true
GameConfig.Version = Version
LinkColors()
GameConfig.DarkLOS = true
ApplyDarkLOS()
go func() {
for {
ui.ReqAnimFrame()
}
}()
for {
newGame(ui)
}
}
func newGame(ui *gameui) {
g := &game{}
ui.g = g
load, err := g.LoadConfig()
if load && err != nil {
log.Printf("Error loading config: %v\n", err)
err = g.SaveConfig()
if err != nil {
log.Printf("Error resetting config: %v\n", err)
}
} else if load {
CustomKeys = true
}
ApplyConfig()
ui.PostConfig()
if runtime.GOARCH != "wasm" {
ui.DrawWelcome()
} else {
again := ui.HandleStartMenu()
if again {
return
}
}
load, err = g.Load()
if !load {
g.InitLevel()
} else if err != nil {
g.InitLevel()
g.Printf("Error loading saved game… starting new game. (%v)", err)
} else {
ui.DrawBufferInit()
}
g.ui = ui
g.EventLoop()
ui.Clear()
ui.DrawColoredText("Do you want to collect some more simellas today?\n\n───Click or press any key to play again───", 7, 5, ColorFg)
ui.DrawText(SaveError, 0, 10)
ui.Flush()
ui.PressAnyKey()
}
func (ui *gameui) HandleStartMenu() (again bool) {
l := ui.DrawWelcomeCommon()
g := ui.g
for {
a := ui.StartMenu(l)
switch a {
case StartWatchReplay:
err := g.LoadReplay()
if err != nil {
ui.ColorLine(l+1, ColorRed)
ui.Flush()
time.Sleep(25 * time.Millisecond)
log.Printf("Load replay: %v", err)
return true
}
small := GameConfig.Small
GameConfig.Small = true
ui.ApplyToggleLayoutWithClear(false)
ui.RestartDrawBuffers()
ui.Replay()
if small {
GameConfig.Small = false
ui.ApplyToggleLayoutWithClear(false)
}
return true
default:
return false
}
}
}
var SaveError string
type gameui struct {
g *game
cursor position
display js.Value
cache map[UICell]js.Value
ctx js.Value
width int
height int
mousepos position
menuHover menu
itemHover int
}
func (ui *gameui) InitElements() error {
canvas := js.Global().Get("document").Call("getElementById", "gamecanvas")
canvas.Call("addEventListener", "contextmenu", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
e := args[0]
e.Call("preventDefault")
return nil
}), false)
canvas.Call("setAttribute", "tabindex", "1")
ui.ctx = canvas.Call("getContext", "2d")
ui.ctx.Set("imageSmoothingEnabled", false)
ui.width = 16
ui.height = 24
canvas.Set("height", 24*UIHeight)
canvas.Set("width", 16*UIWidth)
ui.cache = make(map[UICell]js.Value)
return nil
}
func (ui *gameui) Draw(cell UICell, x, y int) {
var canvas js.Value
if cv, ok := ui.cache[cell]; ok {
canvas = cv
} else {
canvas = js.Global().Get("document").Call("createElement", "canvas")
canvas.Set("width", 16)
canvas.Set("height", 24)
ctx := canvas.Call("getContext", "2d")
ctx.Set("imageSmoothingEnabled", false)
buf := getImage(cell).Pix
ua := js.Global().Get("Uint8Array").New(js.ValueOf(len(buf)))
js.CopyBytesToJS(ua, buf)
ca := js.Global().Get("Uint8ClampedArray").New(ua)
imgdata := js.Global().Get("ImageData").New(ca, 16, 24)
ctx.Call("putImageData", imgdata, 0, 0)
ui.cache[cell] = canvas
}
ui.ctx.Call("drawImage", canvas, x*ui.width, ui.height*y)
}
func (ui *gameui) GetMousePos(evt js.Value) (int, int) {
canvas := js.Global().Get("document").Call("getElementById", "gamecanvas")
rect := canvas.Call("getBoundingClientRect")
scaleX := canvas.Get("width").Float() / rect.Get("width").Float()
scaleY := canvas.Get("height").Float() / rect.Get("height").Float()
x := (evt.Get("clientX").Float() - rect.Get("left").Float()) * scaleX
y := (evt.Get("clientY").Float() - rect.Get("top").Float()) * scaleY
return (int(x) - 1) / ui.width, (int(y) - 1) / ui.height
}
// io compatibility functions
func (g *game) DataDir() (string, error) {
return "", nil
}
func (g *game) Save() error {
if runtime.GOARCH != "wasm" {
return errors.New("Saving games is not available in the web html version.") // TODO remove when it works
}
save, err := g.GameSave()
if err != nil {
SaveError = err.Error()
return err
}
storage := js.Global().Get("localStorage")
if storage.Type() != js.TypeObject {
SaveError = "localStorage not found"
return errors.New("localStorage not found")
}
s := base64.StdEncoding.EncodeToString(save)
storage.Call("setItem", "boohusave", s)
SaveError = ""
return nil
}
func (g *game) SaveConfig() error {
if runtime.GOARCH != "wasm" {
return nil
}
conf, err := GameConfig.ConfigSave()
if err != nil {
SaveError = err.Error()
return err
}
storage := js.Global().Get("localStorage")
if storage.Type() != js.TypeObject {
SaveError = "localStorage not found"
return errors.New("localStorage not found")
}
s := base64.StdEncoding.EncodeToString(conf)
storage.Call("setItem", "boohuconfig", s)
SaveError = ""
return nil
}
func (g *game) SaveReplay() error {
if runtime.GOARCH != "wasm" {
return nil
}
storage := js.Global().Get("localStorage")
if storage.Type() != js.TypeObject {
SaveError = "localStorage not found"
return errors.New("localStorage not found")
}
data, err := g.EncodeDrawLog()
if err != nil {
return err
}
s := base64.StdEncoding.EncodeToString(data)
storage.Call("setItem", "boohureplay", s)
SaveError = ""
return nil
}
func (g *game) RemoveSaveFile() error {
storage := js.Global().Get("localStorage")
storage.Call("removeItem", "boohusave")
return nil
}
func (g *game) RemoveDataFile(file string) error {
storage := js.Global().Get("localStorage")
storage.Call("removeItem", file)
return nil
}
func (g *game) Load() (bool, error) {
storage := js.Global().Get("localStorage")
if storage.Type() != js.TypeObject {
return true, errors.New("localStorage not found")
}
save := storage.Call("getItem", "boohusave")
if save.Type() != js.TypeString || runtime.GOARCH != "wasm" {
return false, nil
}
s, err := base64.StdEncoding.DecodeString(save.String())
if err != nil {
return true, err
}
lg, err := g.DecodeGameSave(s)
if err != nil {
return true, err
}
*g = *lg
// // XXX: gob encoding works badly with gopherjs, it seems, some maps get broken
return true, nil
}
func (g *game) LoadConfig() (bool, error) {
storage := js.Global().Get("localStorage")
if storage.Type() != js.TypeObject {
return true, errors.New("localStorage not found")
}
conf := storage.Call("getItem", "boohuconfig")
if conf.Type() != js.TypeString || runtime.GOARCH != "wasm" {
return false, nil
}
s, err := base64.StdEncoding.DecodeString(conf.String())
if err != nil {
return true, err
}
c, err := g.DecodeConfigSave(s)
if err != nil {
return true, err
}
if c.Version != GameConfig.Version {
return true, errors.New("Version mismatch, could not load old custom configuration.")
}
GameConfig = *c
return true, nil
}
func (g *game) LoadReplay() error {
storage := js.Global().Get("localStorage")
if storage.Type() != js.TypeObject {
return errors.New("localStorage not found")
}
save := storage.Call("getItem", "boohureplay")
if save.Type() != js.TypeString || runtime.GOARCH != "wasm" {
return errors.New("invalid storage")
}
data, err := base64.StdEncoding.DecodeString(save.String())
if err != nil {
return err
}
dl, err := g.DecodeDrawLog(data)
if err != nil {
return err
}
g.DrawLog = dl
return nil
}
func (g *game) WriteDump() error {
pre := js.Global().Get("document").Call("getElementById", "dump")
pre.Set("innerHTML", g.Dump())
err := g.SaveReplay()
if err != nil {
return fmt.Errorf("writing replay: %v", err)
}
return nil
}
// End of io compatibility functions
func (ui *gameui) Init() error {
canvas := js.Global().Get("document").Call("getElementById", "gamecanvas")
gamediv := js.Global().Get("document").Call("getElementById", "gamediv")
js.Global().Get("document").Call(
"addEventListener", "keydown", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
e := args[0]
if !e.Get("ctrlKey").Bool() && !e.Get("metaKey").Bool() {
e.Call("preventDefault")
} else {
return nil
}
s := e.Get("key").String()
if s == "F11" {
screenfull := js.Global().Get("screenfull")
if screenfull.Get("enabled").Bool() {
screenfull.Call("toggle", gamediv)
}
return nil
}
if s == "Unidentified" {
s = e.Get("code").String()
}
if len(ch) < cap(ch) {
ch <- uiInput{key: s}
}
return nil
}))
canvas.Call(
"addEventListener", "mousedown", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
e := args[0]
x, y := ui.GetMousePos(e)
if len(ch) < cap(ch) {
ch <- uiInput{mouse: true, mouseX: x, mouseY: y, button: e.Get("button").Int()}
}
return nil
}))
canvas.Call(
"addEventListener", "mousemove", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
if CenteredCamera {
return nil
}
e := args[0]
x, y := ui.GetMousePos(e)
if x != ui.mousepos.X || y != ui.mousepos.Y {
ui.mousepos.X = x
ui.mousepos.Y = y
if len(ch) < cap(ch) {
ch <- uiInput{mouse: true, mouseX: x, mouseY: y, button: -1}
}
}
return nil
}))
ui.menuHover = -1
ui.InitElements()
SolarizedPalette()
ui.HideCursor()
settingsActions = append(settingsActions, toggleTiles)
return nil
}
var ch chan uiInput
var interrupt chan bool
func init() {
ch = make(chan uiInput, 5)
interrupt = make(chan bool)
Flushdone = make(chan bool)
ReqFrame = make(chan bool)
}
func (ui *gameui) Close() {
// TODO
}
func (ui *gameui) Flush() {
ReqFrame <- true
<-Flushdone
}
func (ui *gameui) ReqAnimFrame() {
<-ReqFrame
js.Global().Get("window").Call("requestAnimationFrame",
js.FuncOf(func(this js.Value, args []js.Value) interface{} { ui.FlushCallback(args[0]); return nil }))
}
func (ui *gameui) ApplyToggleLayoutWithClear(clear bool) {
GameConfig.Small = !GameConfig.Small
if GameConfig.Small {
if clear {
ui.Clear()
ui.Flush()
}
UIHeight = 24
UIWidth = 80
} else {
UIHeight = 26
UIWidth = 100
}
canvas := js.Global().Get("document").Call("getElementById", "gamecanvas")
canvas.Set("height", 24*UIHeight)
canvas.Set("width", 16*UIWidth)
ui.g.DrawBuffer = make([]UICell, UIWidth*UIHeight)
ui.cache = make(map[UICell]js.Value)
if clear {
ui.Clear()
}
}
func (ui *gameui) ApplyToggleLayout() {
ui.ApplyToggleLayoutWithClear(true)
}
var Flushdone chan bool
var ReqFrame chan bool
func (ui *gameui) FlushCallback(t js.Value) {
ui.DrawLogFrame()
for _, cdraw := range ui.g.DrawLog[len(ui.g.DrawLog)-1].Draws {
cell := cdraw.Cell
ui.Draw(cell, cdraw.X, cdraw.Y)
}
Flushdone <- true
}
func (ui *gameui) PollEvent() (in uiInput) {
select {
case in = <-ch:
case in.interrupt = <-interrupt:
}
switch in.key {
case "Escape", "Space":
in.key = "\x1b"
case "Enter", "\r", "\n":
in.key = "."
case "ArrowLeft":
in.key = "4"
case "ArrowRight":
in.key = "6"
case "ArrowUp", "BackSpace":
in.key = "8"
case "ArrowDown":
in.key = "2"
case "Home":
in.key = "7"
case "End":
in.key = "1"
case "PageUp":
in.key = "9"
case "PageDown":
in.key = "3"
case "Numpad5", "Delete":
in.key = "5"
default:
if utf8.RuneCountInString(in.key) != 1 {
in.key = ""
}
}
return in
}