-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_wasm.go
106 lines (87 loc) · 2.28 KB
/
main_wasm.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
//go:build tinygo
// +build tinygo
package main
import (
"encoding/json"
"fmt"
"syscall/js"
"github.com/marianogappa/truco/examplebot/newbot"
"github.com/marianogappa/truco/truco"
)
func main() {
js.Global().Set("trucoNew", js.FuncOf(trucoNew))
js.Global().Set("trucoRunAction", js.FuncOf(trucoRunAction))
js.Global().Set("trucoBotRunAction", js.FuncOf(trucoBotRunAction))
select {}
}
var (
state *truco.GameState
bot truco.Bot
)
type rules struct {
MaxPoints int `json:"maxPoints"`
IsFlorEnabled bool `json:"isFlorEnabled"`
}
func trucoNew(this js.Value, p []js.Value) interface{} {
jsonBytes := make([]byte, p[0].Length())
js.CopyBytesToGo(jsonBytes, p[0])
var r rules
// ignore rules if unmarshal fails
_ = json.Unmarshal(jsonBytes, &r)
opts := []func(*truco.GameState){}
if r.MaxPoints > 0 {
opts = append(opts, truco.WithMaxPoints(r.MaxPoints))
}
if r.IsFlorEnabled {
opts = append(opts, truco.WithFlorEnabled(r.IsFlorEnabled))
}
state = truco.New(opts...)
bot = (newbot.New())
nbs, err := json.Marshal(state.ToClientGameState(0))
if err != nil {
panic(err)
}
buffer := js.Global().Get("Uint8Array").New(len(nbs))
js.CopyBytesToJS(buffer, nbs)
return buffer
}
func trucoRunAction(this js.Value, p []js.Value) interface{} {
jsonBytes := make([]byte, p[0].Length())
js.CopyBytesToGo(jsonBytes, p[0])
newBytes := _runAction(jsonBytes)
buffer := js.Global().Get("Uint8Array").New(len(newBytes))
js.CopyBytesToJS(buffer, newBytes)
return buffer
}
func trucoBotRunAction(this js.Value, p []js.Value) interface{} {
if !state.IsGameEnded {
action := bot.ChooseAction(state.ToClientGameState(1))
// fmt.Println("Action chosen by bot:", action)
err := state.RunAction(action)
if err != nil {
panic(fmt.Errorf("running action: %w", err))
}
}
nbs, err := json.Marshal(state.ToClientGameState(0))
if err != nil {
panic(fmt.Errorf("marshalling game state: %w", err))
}
buffer := js.Global().Get("Uint8Array").New(len(nbs))
js.CopyBytesToJS(buffer, nbs)
return buffer
}
func _runAction(bs []byte) []byte {
action, err := truco.DeserializeAction(bs)
if err != nil {
panic(err)
}
err = state.RunAction(action)
if err != nil {
panic(err)
}
nbs, err := json.Marshal(state.ToClientGameState(0))
if err != nil {
panic(err)
}
return nbs
}