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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
use crate::config::{Config, ConfigBuilderInterface, ConfigInterface};
use crate::data::item_data::ItemData;
use crate::data::location_data::LocationData;
use crate::data::species_data::SpeciesData;
use crate::database::{Database, DatabaseInterface};
use crate::dto::inventory::Inventory;
use crate::dto::user_location_unlock::UserLocationUnlock;
use crate::game::errors::resource::GameResourceError;
use crate::game::errors::GameResult;
use crate::game::interface::GameInterface;
use crate::game::repositories::fishing_history_entry_repository::FishingHistoryEntryRepositoryInterface;
use crate::game::repositories::item_repository::ItemRepositoryInterface;
use crate::game::repositories::pond_repository::PondRepositoryInterface;
use crate::game::repositories::specimen_repository::SpecimenRepositoryInterface;
use crate::game::repositories::user_repository::UserRepositoryInterface;
use crate::game::service_provider::{ServiceProvider, ServiceProviderInterface};
use crate::game::services::encounter_service::EncounterServiceInterface;
use crate::game::services::fishing_history_service::FishingHistoryServiceInterface;
use crate::game::services::item_service::ItemServiceInterface;
use crate::game::services::location_service::LocationServiceInterface;
use crate::game::services::pond_service::PondServiceInterface;
use crate::game::services::species_service::SpeciesServiceInterface;
use crate::game::services::specimen_service::SpecimenServiceInterface;
use crate::game::services::user_service::UserServiceInterface;
use crate::game::services::weather_service::WeatherServiceInterface;
use crate::game::systems::weather_system::weather::Weather;
use crate::models::fishing_history_entry::FishingHistoryEntry;
use crate::models::item::properties_container::ItemPropertiesContainerInterface;
use crate::models::item::Item;
use crate::models::specimen::Specimen;
use crate::models::user::User;
use std::sync::{Arc, RwLock};
pub mod errors;
pub mod interface;
pub mod prelude;
pub mod repositories;
pub mod service_provider;
pub mod services;
pub mod systems;
/// # Game
/// Primary interface for all game operations.
///
/// The Game struct implements [`GameInterface`] and serves as the main entry point
/// for interacting with the game system. All game functionality is accessed
/// through this struct's implementation.
pub struct Game {
service_provider: Arc<dyn ServiceProviderInterface>,
}
impl Game {
pub fn new(db_url: &str, config: Option<Arc<dyn ConfigInterface>>) -> GameResult<Self> {
let config = config.unwrap_or(Config::builder().build().unwrap());
let db = Database::create();
db.write()
.expect("Failed to get database write lock")
.connect(db_url)?;
let service_provider = ServiceProvider::create(config, db);
let game = Game { service_provider };
Ok(game)
}
}
impl GameInterface for Game {
/// Get [ItemData] for the specified item ID.
///
/// # Arguments
///
/// * `item_id`: The ID of the item to get the data of. (See [Config])
///
/// # Returns
///
/// Result<Arc<[ItemData], Global>, [errors::GameError]>
/// - The [ItemData], if an item with the given ID exists
/// - An error, if no item with the given id exists
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use std::env;
/// use fish_lib::config::{Config, ConfigBuilderInterface};
/// use fish_lib::data::item_data::ItemData;
/// use fish_lib::game::prelude::*;
/// use fish_lib::game::service_provider::ServiceProviderInterface;
///
/// const ITEM_ID: i32 = 1;
/// const ITEM_NAME: &str = "Super Bad Rod";
///
/// // Define some item data
/// let item_data = ItemData {
/// name: ITEM_NAME.to_string(),
/// ..Default::default()
/// };
/// let item_data_map = HashMap::from([(ITEM_ID, item_data)]);
///
/// // Add the location data to the config
/// let config = Config::builder().items(item_data_map).build().unwrap();
///
/// // Create game and clear database for a blank test state
/// let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
/// let game = Game::new(&database_url, Some(config)).unwrap();
/// game.database().write().unwrap().clear().unwrap();
///
/// // Finding the item data
/// let found_item_data = game.item_find(ITEM_ID).unwrap();
/// assert_eq!(&found_item_data.name, ITEM_NAME);
///
/// // Searching for non-existent item data
/// let error = game.item_find(ITEM_ID + 1).unwrap_err();
/// assert!(error.is_not_found());
/// if let Some(resource_error) = error.as_resource_error() {
/// assert!(resource_error.is_item_not_found());
/// assert_eq!(resource_error.get_item_type_id(), Some(ITEM_ID + 1));
/// } else {
/// panic!("{:?}", error);
/// }
/// ```
fn item_find(&self, item_id: i32) -> GameResult<Arc<ItemData>> {
match self.config().get_item_data(item_id) {
Some(item_data) => Ok(item_data.clone()),
None => Err(GameResourceError::item_not_found(item_id).into()),
}
}
/// Get [LocationData] for the specified location ID.
///
/// # Arguments
///
/// * `location_id`: The ID of the location to get the data of. (See [Config])
///
/// # Returns
///
/// Result<Arc<[LocationData], Global>, [errors::GameError]>
/// - The [LocationData], if the location with the given ID exists
/// - An error, if no location with the given ID exists
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use std::env;
/// use fish_lib::config::{Config, ConfigBuilderInterface};
/// use fish_lib::game::prelude::*;
/// use fish_lib::data::location_data::LocationData;
/// use fish_lib::game::service_provider::ServiceProviderInterface;
///
/// const LOCATION_ID: i32 = 1;
/// const LOCATION_NAME: &str = "Central Europe";
///
/// // Define some location data
/// let location_data = LocationData {
/// name: LOCATION_NAME.to_string(),
/// ..Default::default()
/// };
/// let location_data_map = HashMap::from([(LOCATION_ID, location_data)]);
///
/// // Add the location data to the config
/// let config = Config::builder().locations(location_data_map).build().unwrap();
///
/// // Create game and clear database for a blank test state
/// let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
/// let game = Game::new(&database_url, Some(config)).unwrap();
/// game.database().write().unwrap().clear().unwrap();
///
/// // Finding the location data
/// let found_location_data = game.location_find(LOCATION_ID).unwrap();
/// assert_eq!(&found_location_data.name, LOCATION_NAME);
///
/// // Searching for non-existent location data
/// let error = game.location_find(LOCATION_ID + 1).unwrap_err();
/// assert!(error.is_not_found());
/// if let Some(resource_error) = error.as_resource_error() {
/// assert!(resource_error.is_location_not_found());
/// assert_eq!(resource_error.get_location_id(), Some(LOCATION_ID + 1));
/// } else {
/// panic!("{:?}", error);
/// }
/// ```
fn location_find(&self, location_id: i32) -> GameResult<Arc<LocationData>> {
match self.config().get_location_data(location_id) {
Some(data) => Ok(data.clone()),
None => Err(GameResourceError::location_not_found(location_id).into()),
}
}
/// Get the current [Weather] of a specified location.
/// You will be able to get the weather for all locations specified by you in your [Config].
///
/// # Arguments
///
/// * `location_id`: The ID of the location to get the current [Weather] from. (See [Config])
///
/// # Returns
/// Result<[Weather], [errors::GameError]>
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use std::env;
/// use fish_lib::config::{Config, ConfigBuilderInterface};
/// use fish_lib::data::location_data::LocationData;
/// use fish_lib::data::season_data::SeasonData;
/// use fish_lib::game::prelude::*;
/// use fish_lib::game::service_provider::ServiceProviderInterface;
///
/// const LOCATION_ID: i32 = 1;
///
/// // For simplicity in testing, create a location with constant weather
/// let every_season = SeasonData {
/// min_temp_c: 10.0,
/// max_temp_c: 10.0,
/// ..Default::default()
/// };
///
/// let location_data = LocationData {
/// spring: every_season.clone(),
/// summer: every_season.clone(),
/// autumn: every_season.clone(),
/// winter: every_season.clone(),
/// ..Default::default()
/// };
///
/// let location_data_map = HashMap::from([(LOCATION_ID, location_data)]);
/// let config = Config::builder().locations(location_data_map).build().unwrap();
///
/// // Create game and clear database for a blank test state
/// let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
/// let game = Game::new(&database_url, Some(config)).unwrap();
/// game.database().write().unwrap().clear().unwrap();
///
/// // Get the current weather
/// let location_data = game.location_find(LOCATION_ID).unwrap();
/// let weather = game.location_weather_current(location_data).unwrap();
/// assert_eq!(weather.temperature_c, 10.0);
/// ```
fn location_weather_current(&self, location: Arc<LocationData>) -> GameResult<Weather> {
self.weather_service().get_current_weather(location)
}
/// Get [SpeciesData] for the specified species ID.
///
/// # Arguments
///
/// * `species_id`: The ID of the species to get the data of. (See [Config])
///
/// # Returns
///
/// Result<Arc<[SpeciesData], Global>, [errors::GameError]>
/// - The [SpeciesData], if the species with the given ID exists
/// - An error, if no species with the given ID exists
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use std::env;
/// use fish_lib::config::{Config, ConfigBuilderInterface};
/// use fish_lib::data::species_data::SpeciesData;
/// use fish_lib::game::prelude::*;
/// use fish_lib::game::service_provider::ServiceProviderInterface;
///
/// const SPECIES_ID: i32 = 1;
/// const SPECIES_NAME: &str = "Salmon";
///
/// // Define some species data
/// let species_data = SpeciesData {
/// name: SPECIES_NAME.to_string(),
/// ..Default::default()
/// };
/// let species_data_map = HashMap::from([(SPECIES_ID, species_data)]);
///
/// // Add the species data to the config
/// let config = Config::builder().species(species_data_map).build().unwrap();
///
/// // Create game and clear database for a blank test state
/// let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
/// let game = Game::new(&database_url, Some(config)).unwrap();
/// game.database().write().unwrap().clear().unwrap();
///
/// // Finding the species data
/// let found_species_data = game.species_find(SPECIES_ID).unwrap();
/// assert_eq!(&found_species_data.name, SPECIES_NAME);
///
/// // Searching for non-existent species data
/// let error = game.species_find(SPECIES_ID + 1).unwrap_err();
/// assert!(error.is_not_found());
/// if let Some(resource_error) = error.as_resource_error() {
/// assert!(resource_error.is_species_not_found());
/// assert_eq!(resource_error.get_species_id(), Some(SPECIES_ID + 1));
/// } else {
/// panic!("{:?}", error);
/// }
/// ```
fn species_find(&self, species_id: i32) -> GameResult<Arc<SpeciesData>> {
match self.config().get_species_data(species_id) {
Some(data) => Ok(data.clone()),
None => Err(GameResourceError::species_not_found(species_id).into()),
}
}
/// Generate a random [Specimen] of the given species ID and assign it to the given [User].
///
/// # Arguments
///
/// * `user`: The [User] for which the catch is to be registered
/// * `species_id`: The species ID of the [Specimen] to be caught (See [Config])
///
/// # Returns
/// Result<([Specimen], [FishingHistoryEntry]), [errors::GameError]>
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use std::env;
/// use fish_lib::config::{Config, ConfigBuilderInterface};
/// use fish_lib::data::species_data::SpeciesData;
/// use fish_lib::game::prelude::*;
/// use fish_lib::game::repositories::user_repository::UserRepository;
/// use fish_lib::game::service_provider::ServiceProviderInterface;
/// use fish_lib::models::user::User;
///
/// const USER_EXTERNAL_ID: i64 = 1337;
/// const SPECIES_ID: i32 = 1;
/// const SPECIES_NAME: &str = "Salmon";
///
/// // Define some species data
/// let species_data = SpeciesData {
/// name: SPECIES_NAME.to_string(),
/// ..Default::default()
/// };
/// let species_data_map = HashMap::from([(SPECIES_ID, species_data)]);
///
/// // Add the species data to the config
/// let config = Config::builder().species(species_data_map).build().unwrap();
///
/// // Create game and clear database for a blank test state
/// let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
/// let game = Game::new(&database_url, Some(config)).unwrap();
/// game.database().write().unwrap().clear().unwrap();
///
/// // Fetch the species data
/// let species = game.species_find(1).unwrap();
///
/// // Create a user
/// let user = game.user_register(USER_EXTERNAL_ID).unwrap();
///
/// // Let the user catch a specimen of the specified species ID
/// let (specimen, history_entry) = game.user_catch_specific_specimen(&user, species.clone()).unwrap();
/// assert_eq!(specimen.species_id, SPECIES_ID);
/// assert_eq!(specimen.user_id, user.id);
/// assert_eq!(history_entry.species_id, SPECIES_ID);
/// assert_eq!(history_entry.caught_count, 1);
///
/// // Catch a specimen for a user that doesn't exist
/// let dummy_user = User {
/// id: -1,
/// external_id: USER_EXTERNAL_ID + 1,
/// ..Default::default()
/// };
/// let user_error = game.user_catch_specific_specimen(&dummy_user, species).unwrap_err();
/// if let Some(resource_error) = user_error.as_resource_error() {
/// assert!(resource_error.is_user_not_found());
/// assert_eq!(resource_error.get_external_id(), Some(USER_EXTERNAL_ID + 1));
/// } else {
/// panic!("{:?}", user_error);
/// }
///
/// ```
fn user_catch_specific_specimen(
&self,
user: &User,
species: Arc<SpeciesData>,
) -> GameResult<(Specimen, FishingHistoryEntry)> {
let specimen = self.specimen_service().process_catch(user, species)?;
let entry = self.fishing_history_service().register_catch(&specimen)?;
Ok((specimen, entry))
}
/// Check the fishing history of a [User] with a specified species ID
///
/// # Arguments
///
/// * `user`: The [User] to check the fishing history of
/// * `species_id`: Fishing history species ID to check for the giving [User] (See [Config])
///
/// # Returns
///
/// Result<[FishingHistoryEntry], [errors::GameError]>
/// - The fishing history of the given [User] with a specified species, if it exists
/// - An error, if it does not exist, aka if the [User] did not catch that species yet or the [User] does not exist
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use std::env;
/// use fish_lib::config::{Config, ConfigBuilderInterface};
/// use fish_lib::data::species_data::SpeciesData;
/// use fish_lib::game::prelude::*;
/// use fish_lib::game::repositories::user_repository::UserRepository;
/// use fish_lib::game::service_provider::ServiceProviderInterface;
/// use fish_lib::models::user::User;
///
/// const USER_EXTERNAL_ID: i64 = 1337;
/// const SPECIES_ID: i32 = 1;
/// const SPECIES_NAME: &str = "Salmon";
///
/// // Define some species data
/// let species_data = SpeciesData {
/// name: SPECIES_NAME.to_string(),
/// ..Default::default()
/// };
/// let species_data2 = SpeciesData {
/// ..Default::default()
/// };
/// let species_data_map = HashMap::from([(SPECIES_ID, species_data), (SPECIES_ID + 1, species_data2)]);
///
/// // Add the species data to the config
/// let config = Config::builder().species(species_data_map).build().unwrap();
///
/// // Create game and clear database for a blank test state
/// let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
/// let game = Game::new(&database_url, Some(config)).unwrap();
/// game.database().write().unwrap().clear().unwrap();
///
/// // Create a user
/// let user = game.user_register(USER_EXTERNAL_ID).unwrap();
///
/// // Get species data
/// let species = game.species_find(SPECIES_ID).unwrap();
/// let species2 = game.species_find(SPECIES_ID + 1).unwrap();
///
/// // Let the user catch a specimen
/// game.user_catch_specific_specimen(&user, species.clone()).unwrap();
///
/// // Fetch the fishing history of the user with the given species ID
/// let history_entry = game.user_get_fishing_history(&user, species.clone()).unwrap();
/// assert_eq!(history_entry.species_id, SPECIES_ID);
/// assert_eq!(history_entry.user_id, user.id);
/// assert_eq!(history_entry.caught_count, 1);
/// assert_eq!(history_entry.sold_count, 0);
///
/// // Trying to fetch the fishing history with a species the user didn't catch yet
/// let error = game.user_get_fishing_history(&user, species2).unwrap_err();
/// assert!(error.is_not_found());
/// if let Some(resource_error) = error.as_resource_error() {
/// assert!(resource_error.is_no_fishing_history());
/// assert_eq!(resource_error.get_external_id(), Some(USER_EXTERNAL_ID));
/// assert_eq!(resource_error.get_species_id(), Some(SPECIES_ID + 1));
/// } else {
/// panic!("{:?}", error);
/// }
/// ```
fn user_get_fishing_history(
&self,
user: &User,
species: Arc<SpeciesData>,
) -> GameResult<FishingHistoryEntry> {
match self
.fishing_history_entry_repository()
.find_by_user_and_species_id(user.id, species.id)?
{
Some(entry) => Ok(entry),
None => Err(GameResourceError::no_fishing_history(user.external_id, species.id).into()),
}
}
/// Find a [User] by their external ID.
///
/// # Arguments
///
/// * `external_id`: A freely selectable ID that your system will use to identify this [User].
///
/// # Returns
///
/// Result<[User], [errors::GameError]>
/// - A [User] with the given external ID
/// - An error, if:
/// - The [User] is not found
/// - Database operations fail
///
/// # Examples
///
/// ```
/// use std::env;
/// use fish_lib::game::prelude::*;
/// use fish_lib::game::service_provider::ServiceProviderInterface;
///
/// const EXTERNAL_ID: i64 = 1337;
///
/// // Create game and clear database for a blank test state
/// let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
/// let game = Game::new(&database_url, None).unwrap();
/// game.database().write().unwrap().clear().unwrap();
///
/// // Finding an existing user
/// let new_user = game.user_register(EXTERNAL_ID).unwrap();
/// let found_user = game.user_find(EXTERNAL_ID).unwrap();
/// assert_eq!(new_user, found_user);
///
/// // Searching for a non-existent user
/// let error = game.user_find(EXTERNAL_ID + 1).unwrap_err();
/// assert!(error.is_not_found());
/// if let Some(resource_error) = error.as_resource_error() {
/// assert!(resource_error.is_user_not_found());
/// assert_eq!(resource_error.get_external_id(), Some(EXTERNAL_ID + 1));
/// } else {
/// panic!("{:?}", error);
/// }
/// ```
fn user_find(&self, external_id: i64) -> GameResult<User> {
match self.user_repository().find_by_external_id(external_id)? {
Some(user) => Ok(user),
None => Err(GameResourceError::user_not_found(external_id).into()),
}
}
/// Fetch the unlocked locations of a given user.
///
/// # Arguments
///
/// * `user`: The [User] to get the unlocked locations ([UserLocationUnlock]) from.
///
/// # Returns
/// Result<Vec<[UserLocationUnlock], Global>, [errors::GameError]>
/// - A vector with information about all location unlocks
/// - An error, if database operations fail
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use std::env;
/// use fish_lib::config::{Config, ConfigBuilderInterface};
/// use fish_lib::data::location_data::LocationData;
/// use fish_lib::game::prelude::*;
/// use fish_lib::game::service_provider::ServiceProviderInterface;
///
/// const EXTERNAL_ID: i64 = 1337;
/// const LOCATION_ID: i32 = 13;
/// const LOCATION_NAME: &str = "Island";
///
/// // Define some location data
/// let location_data = LocationData {
/// name: LOCATION_NAME.to_string(),
/// ..Default::default()
/// };
/// let location_data_map = HashMap::from([(LOCATION_ID, location_data)]);
///
/// // Add the location data to the config
/// let config = Config::builder().locations(location_data_map).build().unwrap();
///
/// // Create game and clear database for a blank test state
/// let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
/// let game = Game::new(&database_url, Some(config)).unwrap();
/// game.database().write().unwrap().clear().unwrap();
///
/// // Registering a new user
/// let user = game.user_register(EXTERNAL_ID).unwrap();
///
/// // Let the user unlock a location
/// let island_location = game.location_find(LOCATION_ID).unwrap();
/// let unlocked_location = game.user_unlock_location(&user, island_location).unwrap();
///
/// // Get unlocked locations
/// let unlocked_locations = game.user_get_unlocked_locations(&user).unwrap();
/// assert_eq!(unlocked_locations.len(), 1);
/// assert_eq!(unlocked_locations[0], unlocked_location);
/// ```
fn user_get_unlocked_locations(&self, user: &User) -> GameResult<Vec<UserLocationUnlock>> {
let user_locations = self.user_service().get_unlocked_locations(user)?;
let location_unlocks =
UserLocationUnlock::from_user_locations(user_locations, |location_id| {
self.location_find(location_id).ok()
});
Ok(location_unlocks)
}
/// Get the [Inventory] of a specified [User].
///
/// # Arguments
///
/// * `user`: The [User] to get the [Inventory] from.
///
/// # Returns
///
/// Result<[Inventory], [errors::GameError]>
/// - The user's inventory, if the user exists
/// - An error, if a database error occurred
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use std::env;
/// use fish_lib::config::{Config, ConfigBuilderInterface};
/// use fish_lib::data::item_data::ItemData;
/// use fish_lib::game::prelude::*;
/// use fish_lib::game::service_provider::ServiceProviderInterface;
///
/// const EXTERNAL_ID: i64 = 1337;
/// const ITEM_ID: i32 = 1;
/// const ITEM_NAME: &str = "Super Bad Rod";
///
/// // Define some item data
/// let item_data = ItemData {
/// name: ITEM_NAME.to_string(),
/// ..Default::default()
/// };
/// let item_data_map = HashMap::from([(ITEM_ID, item_data)]);
///
/// // Add the location data to the config
/// let config = Config::builder().items(item_data_map).build().unwrap();
///
/// // Create game and clear database for a blank test state
/// let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
/// let game = Game::new(&database_url, Some(config)).unwrap();
/// game.database().write().unwrap().clear().unwrap();
///
/// // Registering a new user
/// let user = game.user_register(EXTERNAL_ID).unwrap();
/// assert_eq!(user.external_id, EXTERNAL_ID);
///
/// /// Giving the user an item
/// let item_data = game.item_find(ITEM_ID).unwrap();
/// let item = game.user_item_give(&user, item_data, 1).unwrap();
///
/// let inventory = game.user_inventory(&user).unwrap();
/// let items = inventory.get_items();
/// assert_eq!(items[0], item);
///
/// ```
fn user_inventory(&self, user: &User) -> GameResult<Inventory> {
self.item_service().get_inventory(user)
}
/// Give a [User] a specified [ItemData].
///
/// # Arguments
///
/// * `user`: The [User] to give the item to.
/// * `item_data`: The [ItemData] to give the user. (See [Config])
/// * `count`: How much of the item to give the user.
/// 0 or 1 results in the default specified count if the item is stackable.
/// If the item is not stackable (unique) it'll be added once (no matter the specified count).
///
/// # Returns
///
/// Result<[Item], [errors::GameError]>
/// - The newly created item when the operation was successful
/// - An error, if there was an error stacking the item or database operations failed
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use std::env;
/// use fish_lib::config::{Config, ConfigBuilderInterface};
/// use fish_lib::data::item_data::ItemData;
/// use fish_lib::game::prelude::*;
/// use fish_lib::game::service_provider::ServiceProviderInterface;
///
/// const EXTERNAL_ID: i64 = 1337;
/// const ITEM_ID: i32 = 1;
/// const ITEM_NAME: &str = "Super Bad Rod";
///
/// // Define some item data
/// let item_data = ItemData {
/// name: ITEM_NAME.to_string(),
/// ..Default::default()
/// };
/// let item_data_map = HashMap::from([(ITEM_ID, item_data)]);
///
/// // Add the location data to the config
/// let config = Config::builder().items(item_data_map).build().unwrap();
///
/// // Create game and clear database for a blank test state
/// let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
/// let game = Game::new(&database_url, Some(config)).unwrap();
/// game.database().write().unwrap().clear().unwrap();
///
/// // Registering a new user
/// let user = game.user_register(EXTERNAL_ID).unwrap();
/// assert_eq!(user.external_id, EXTERNAL_ID);
///
/// // Giving the user an item
/// let item_data = game.item_find(ITEM_ID).unwrap();
/// let item = game.user_item_give(&user, item_data, 1).unwrap();
///
/// let inventory = game.user_inventory(&user).unwrap();
/// let items = inventory.get_items();
/// assert_eq!(items[0], item);
/// ```
fn user_item_give(
&self,
user: &User,
item_data: Arc<ItemData>,
count: u64,
) -> GameResult<Item> {
let item = if count <= 1 || !item_data.is_stackable() {
self.item_service().create_and_save_item(item_data, user)?
} else {
self.item_service()
.create_and_save_item_with_count(item_data, user, count)?
};
Ok(item)
}
/// Register a new [User] by their external ID.
///
/// # Arguments
///
/// * `external_id`: A freely selectable ID that your system will use to identify this [User].
///
/// # Returns
///
/// Result<[User], [errors::GameError]>
/// - A newly created [User] with the given external id
/// - An error, if:
/// - A [User] with the given external id already exists
/// - Database operations fail
///
/// # Examples
///
/// ```
/// use std::env;
/// use fish_lib::game::prelude::*;
/// use fish_lib::game::service_provider::ServiceProviderInterface;
///
/// const EXTERNAL_ID: i64 = 1337;
///
/// // Create game and clear database for a blank test state
/// let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
/// let game = Game::new(&database_url, None).unwrap();
/// game.database().write().unwrap().clear().unwrap();
///
/// // Registering a new user
/// let user = game.user_register(EXTERNAL_ID).unwrap();
/// assert_eq!(user.external_id, EXTERNAL_ID);
///
/// // Registering an already existing user
/// let error = game.user_register(EXTERNAL_ID).unwrap_err();
/// assert!(error.is_already_exists());
/// if let Some(resource_error) = error.as_resource_error() {
/// assert!(resource_error.is_user_already_exists());
/// assert_eq!(resource_error.get_external_id(), Some(EXTERNAL_ID));
/// } else {
/// panic!("{:?}", error);
/// }
/// ```
fn user_register(&self, external_id: i64) -> GameResult<User> {
match self.user_repository().find_by_external_id(external_id)? {
Some(_) => Err(GameResourceError::user_already_exists(external_id).into()),
None => Ok(self.user_service().create_and_save_user(external_id)?),
}
}
/// Save a [User].
///
/// # Arguments
///
/// * `user`: The [User] to save
///
/// # Returns
/// Result<[User], [errors::GameError]>
/// - The updated [User] entity, if saving succeeded
/// - An error, if saving failed (database errors, or the user doesn't exist)
///
/// # Examples
///
/// ```
/// use std::env;
/// use fish_lib::game::prelude::*;
/// use fish_lib::game::service_provider::ServiceProviderInterface; ///
///
/// use fish_lib::models::user::User;
///
/// const DUMMY_USER_ID: i64 = 64;
/// const USER_EXTERNAL_ID: i64 = 1337;
/// const USER_CREDITS: i64 = 293;
///
/// // Create game and clear database for a blank test state
/// let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
/// let game = Game::new(&database_url, None).unwrap();
/// game.database().write().unwrap().clear().unwrap();
///
/// // Create a new user and update their credits
/// let mut user = game.user_register(USER_EXTERNAL_ID).unwrap();
/// user.credits = USER_CREDITS;
///
/// // Save the user and check if the credits were updated properly
/// let updated_user = game.user_save(user).unwrap();
/// assert_eq!(updated_user.credits, USER_CREDITS);
///
/// // Find user again and check if credits are updated properly
/// let found_user = game.user_find(USER_EXTERNAL_ID).unwrap();
/// assert_eq!(found_user.credits, USER_CREDITS);
///
/// // Try to save a non-existent user
/// let dummy_user = User {
/// id: DUMMY_USER_ID,
/// ..Default::default()
/// };
///
/// let error_not_found = game.user_save(dummy_user).unwrap_err();
/// assert!(error_not_found.is_not_found())
/// ```
fn user_save(&self, user: User) -> GameResult<User> {
Ok(self.user_repository().save(user)?)
}
/// Unlocks a given location for a given user
///
/// # Arguments
///
/// * `user`: The [User] to unlock a location for
/// * `location`: The location to unlock for the given [User]
///
/// # Returns
/// Result<[UserLocationUnlock], [errors::GameError]>
/// - Information about the location unlock, if it succeeded
/// - An error, if:
/// - unlock conditions were not met
/// - the location was already unlocked
/// - the location does not exist
/// - database operations fail
///
/// # Examples
///
/// ```
/// use fish_lib::game::prelude::*;
/// use std::collections::HashMap;
/// use std::env;
/// use fish_lib::config::{Config, ConfigBuilderInterface};
/// use fish_lib::data::location_data::LocationData;
/// use fish_lib::game::prelude::*;
/// use fish_lib::game::service_provider::ServiceProviderInterface;
///
/// const EXTERNAL_ID: i64 = 1337;
/// const LOCATION_ID: i32 = 13;
/// const LOCATION_NAME: &str = "Island";
///
/// // Define some location data
/// let location_data = LocationData {
/// name: LOCATION_NAME.to_string(),
/// ..Default::default()
/// };
/// let location_data2 = LocationData {
/// required_locations_unlocked: vec![LOCATION_ID + 2],
/// ..Default::default()
/// };
/// let location_data3 = LocationData::default();
///
/// let location_data_map = HashMap::from([
/// (LOCATION_ID, location_data),
/// (LOCATION_ID + 1, location_data2),
/// (LOCATION_ID + 2, location_data3)
/// ]);
///
/// // Add the location data to the config
/// let config = Config::builder().locations(location_data_map).build().unwrap();
///
/// // Create game and clear database for a blank test state
/// let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
/// let game = Game::new(&database_url, Some(config)).unwrap();
/// game.database().write().unwrap().clear().unwrap();
///
/// // Registering a new user
/// let user = game.user_register(EXTERNAL_ID).unwrap();
///
/// // Unlock a location for the user
/// let island = game.location_find(LOCATION_ID).unwrap();
/// let location_unlock = game.user_unlock_location(&user, island).unwrap();
///
/// // Find unlocked locations
/// let unlocked_locations = game.user_get_unlocked_locations(&user).unwrap();
/// assert_eq!(unlocked_locations.len(), 1);
/// assert_eq!(unlocked_locations[0], location_unlock);
///
/// // Unmet requirements
/// let location2 = game.location_find(LOCATION_ID + 1).unwrap();
/// let unlock_error = game.user_unlock_location(&user, location2).unwrap_err();
///
/// assert!(unlock_error.is_unmet_requirements());
/// if let Some(resource_error) = unlock_error.as_resource_error() {
/// assert!(resource_error.is_unmet_location_unlock_requirements());
/// assert_eq!(resource_error.get_location_id(), Some(LOCATION_ID + 1));
/// } else {
/// panic!("{:?}", unlock_error);
/// }
/// ```
fn user_unlock_location(
&self,
user: &User,
location: Arc<LocationData>,
) -> GameResult<UserLocationUnlock> {
let user_location = self
.user_service()
.unlock_location(user, location.clone())?;
let user_location_unlock =
UserLocationUnlock::from_user_location(user_location, &|location_id| {
self.location_find(location_id).ok()
});
match user_location_unlock {
Some(location_unlock) => Ok(location_unlock),
None => Err(GameResourceError::location_not_found(location.id).into()),
}
}
}
impl ServiceProviderInterface for Game {
fn config(&self) -> Arc<dyn ConfigInterface> {
self.service_provider.config()
}
fn database(&self) -> Arc<RwLock<dyn DatabaseInterface>> {
self.service_provider.database()
}
fn fishing_history_entry_repository(&self) -> Arc<dyn FishingHistoryEntryRepositoryInterface> {
self.service_provider.fishing_history_entry_repository()
}
fn item_repository(&self) -> Arc<dyn ItemRepositoryInterface> {
self.service_provider.item_repository()
}
fn pond_repository(&self) -> Arc<dyn PondRepositoryInterface> {
self.service_provider.pond_repository()
}
fn specimen_repository(&self) -> Arc<dyn SpecimenRepositoryInterface> {
self.service_provider.specimen_repository()
}
fn user_repository(&self) -> Arc<dyn UserRepositoryInterface> {
self.service_provider.user_repository()
}
fn encounter_service(&self) -> Arc<dyn EncounterServiceInterface> {
self.service_provider.encounter_service()
}
fn fishing_history_service(&self) -> Arc<dyn FishingHistoryServiceInterface> {
self.service_provider.fishing_history_service()
}
fn item_service(&self) -> Arc<dyn ItemServiceInterface> {
self.service_provider.item_service()
}
fn location_service(&self) -> Arc<dyn LocationServiceInterface> {
self.service_provider.location_service()
}
fn pond_service(&self) -> Arc<dyn PondServiceInterface> {
self.service_provider.pond_service()
}
fn species_service(&self) -> Arc<dyn SpeciesServiceInterface> {
self.service_provider.species_service()
}
fn specimen_service(&self) -> Arc<dyn SpecimenServiceInterface> {
self.service_provider.specimen_service()
}
fn user_service(&self) -> Arc<dyn UserServiceInterface> {
self.service_provider.user_service()
}
fn weather_service(&self) -> Arc<dyn WeatherServiceInterface> {
self.service_provider.weather_service()
}
}