1use soroban_sdk::{contracttype, Bytes, Env, Symbol};
2
3#[contracttype]
4#[derive(Debug, Clone)]
5pub struct Resource {
6 pub resource_type: Symbol,
7 pub data: Bytes,
8}
9impl Resource {
10 pub fn new(resource_type: Symbol, data: Bytes) -> Self {
11 Self {
12 resource_type,
13 data,
14 }
15 }
16 pub fn resource_type(&self) -> &Symbol {
17 &self.resource_type
18 }
19 pub fn data(&self) -> &Bytes {
20 &self.data
21 }
22 pub fn data_mut(&mut self) -> &mut Bytes {
23 &mut self.data
24 }
25}
26
27pub trait ResourceTrait: Send + Sync + 'static {
28 fn resource_type() -> Symbol;
29 fn serialize(&self, env: &Env) -> Bytes;
30 fn deserialize(env: &Env, data: &Bytes) -> Option<Self>
31 where
32 Self: Sized;
33}
34
35#[contracttype]
36#[derive(Clone)]
37pub struct GameState {
38 pub score: i32,
39 pub level: i32,
40 pub is_game_over: bool,
41}
42impl GameState {
43 pub fn new() -> Self {
44 Self {
45 score: 0,
46 level: 1,
47 is_game_over: false,
48 }
49 }
50 pub fn increment_score(&mut self, points: i32) {
51 self.score += points;
52 }
53 pub fn next_level(&mut self) {
54 self.level += 1;
55 }
56 pub fn game_over(&mut self) {
57 self.is_game_over = true;
58 }
59}
60impl_resource!(GameState, "gamestate", { score: i32, level: i32, is_game_over: bool });
61impl Default for GameState {
62 fn default() -> Self {
63 Self::new()
64 }
65}
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70 use soroban_sdk::{symbol_short, Env};
71
72 #[test]
73 fn test_resource_creation() {
74 let env = Env::default();
75 let resource_type = symbol_short!("testres");
76 let mut data = Bytes::new(&env);
77 data.append(&Bytes::from_array(&env, &[1, 2, 3, 4]));
78 let resource = Resource::new(resource_type, data.clone());
79
80 assert_eq!(resource.resource_type(), &symbol_short!("testres"));
81 assert_eq!(resource.data(), &data);
82 }
83
84 #[test]
85 fn test_game_state_serialization() {
86 let env = Env::default();
87 let mut game_state = GameState::new();
88 game_state.increment_score(100);
89 game_state.next_level();
90
91 let data = game_state.serialize(&env);
92 let deserialized = GameState::deserialize(&env, &data).unwrap();
93
94 assert_eq!(game_state.score, deserialized.score);
95 assert_eq!(game_state.level, deserialized.level);
96 assert_eq!(game_state.is_game_over, deserialized.is_game_over);
97 }
98}