simple_state.gd(檔案已創建)
@@ -0,0 +1,67 @@ | |||
1 | + | extends Node | |
2 | + | class_name _SimpleState | |
3 | + | ||
4 | + | signal state_changed(name, state) | |
5 | + | ||
6 | + | var state := { } | |
7 | + | ||
8 | + | ||
9 | + | func register(state_name: String, inital_state: Dictionary = {}) -> void: | |
10 | + | state[state_name] = inital_state | |
11 | + | ||
12 | + | ||
13 | + | func replace(state_name: String, new_state: Dictionary) -> void: | |
14 | + | state[state_name] = new_state.duplicate(true) | |
15 | + | emit_signal("state_changed", state_name, state) | |
16 | + | ||
17 | + | ||
18 | + | func update(state_name: String, new_state: Dictionary) -> void: | |
19 | + | state[state_name] = _SimpleState.merge(get_state(state_name), new_state) | |
20 | + | emit_signal("state_changed", state_name, state) | |
21 | + | ||
22 | + | ||
23 | + | func update_deep(state_name: String, new_state: Dictionary) -> void: | |
24 | + | state[state_name] = _SimpleState.merge_deep(get_state(state_name), new_state) | |
25 | + | emit_signal("state_changed", state_name, state) | |
26 | + | ||
27 | + | ||
28 | + | func update_mut(state_name: String, new_state: Dictionary) -> void: | |
29 | + | _SimpleState.copy_to(state[state_name], new_state) | |
30 | + | emit_signal("state_changed") | |
31 | + | ||
32 | + | ||
33 | + | func _on_update_state(data: Dictionary) -> void: | |
34 | + | update(data.state_name, data.state) | |
35 | + | ||
36 | + | ||
37 | + | func get_state(state_name: String) -> Dictionary: | |
38 | + | return state[state_name].duplicate() | |
39 | + | ||
40 | + | ||
41 | + | static func copy_to(a: Dictionary, b: Dictionary) -> void: | |
42 | + | for key in b: | |
43 | + | a[key] = b[key] | |
44 | + | ||
45 | + | ||
46 | + | ||
47 | + | static func copy_to_deep(a: Dictionary, b: Dictionary) -> void: | |
48 | + | for k in b: | |
49 | + | if process_recursively(a, b, k): | |
50 | + | copy_to_deep(a[k], b[k]) | |
51 | + | else: | |
52 | + | a[k] = b[k] | |
53 | + | ||
54 | + | ||
55 | + | static func process_recursively(a, b, k) -> bool: | |
56 | + | return a.has(k) and a[k] is Dictionary and b[k] is Dictionary | |
57 | + | ||
58 | + | static func merge(a: Dictionary, b: Dictionary) -> Dictionary: | |
59 | + | var c := a.duplicate(true) | |
60 | + | copy_to(c, b) | |
61 | + | return c | |
62 | + | ||
63 | + | ||
64 | + | static func merge_deep(a: Dictionary, b: Dictionary) -> Dictionary: | |
65 | + | var c := a.duplicate(true) | |
66 | + | copy_to_deep(c, b) | |
67 | + | return c |
上一頁
下一頁