-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata.go
99 lines (90 loc) · 1.89 KB
/
data.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
package main
import (
"encoding/json"
"fmt"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/data/binding"
"io"
"os"
"path"
)
const fileName = "data.json"
type data struct {
Award int
Credit int
Bet int
}
func user2data(info *userInfo) (res *data) {
res = new(data)
res.Bet, _ = info.bet.Get()
res.Credit, _ = info.credit.Get()
res.Award, _ = info.award.Get()
return
}
func data2user(res *data) (info *userInfo) {
if res.Bet == 0 {
res.Bet = len(lines)
}
if res.Credit == 0 {
res.Credit = 1e5
}
info = &userInfo{
credit: binding.NewInt(),
bet: binding.NewInt(),
award: binding.NewInt(),
}
// info.award.Set(res.Award)
info.credit.Set(res.Credit)
info.bet.Set(res.Bet)
info.history = append(info.history, []string{"credit", "bet", "award"})
return
}
// saveData 用于保存数据
func (g *slotGame) saveData() {
res := user2data(g.userInfo)
marshal, err := json.Marshal(res)
if err != nil {
fmt.Println("Marshal err:", err)
}
file, err := os.Create(getDataPath())
if err != nil {
fmt.Println("无法创建文件:", err)
return
}
defer file.Close()
file.WriteString(string(marshal))
}
// loadData 用于加载数据
func (g *slotGame) loadData() {
res := new(data)
defer func() {
g.userInfo = data2user(res) // 最后赋值就行
}()
file, err := os.Open(getDataPath())
if err != nil {
fmt.Println("无法打开文件:", err)
return
}
defer file.Close()
byteValue, err := io.ReadAll(file)
if err != nil {
fmt.Println("读取文件错误:", err)
return
}
if len(byteValue) > 0 {
err = json.Unmarshal(byteValue, res)
if err != nil {
fmt.Println("Unmarshal err:", err)
return
}
}
}
func getDataPath() string {
storageRootURI := fyne.CurrentApp().Storage().RootURI()
println(storageRootURI.Path())
return path.Join(storageRootURI.Path(), fileName)
}
func fileExists(filename string) bool {
_, err := os.Stat(filename)
return !os.IsNotExist(err)
}