forked from chris-hinson/waste
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbattle.rs
1602 lines (1489 loc) · 58 KB
/
battle.rs
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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::backgrounds::Tile;
use crate::camera::{MenuCamera, SlidesCamera};
use crate::monster::{
get_monster_sprite_for_type, Boss, Defense, Element, Enemy, Health, Level, MonsterStats,
PartyMonster, SelectedMonster, Strength,
};
use crate::player::Player;
use crate::quests::*;
use crate::world::{GameProgress, PooledText, TextBuffer, TypeSystem, SPECIALS_PER_BATTLE, item_index_to_name};
use crate::GameState;
use bevy::prelude::*;
use iyes_loopless::prelude::*;
use rand::*;
const BATTLE_BACKGROUND: &str = "backgrounds/battlescreen_desert_1.png";
#[derive(Component)]
pub(crate) struct BattleBackground;
#[derive(Component)]
pub(crate) struct Monster;
#[derive(Component)]
pub(crate) struct PlayerMonster;
#[derive(Component)]
pub(crate) struct EnemyMonster;
// Unit structs to help identify the specific UI components for player's or enemy's monster health/level
// since there may be many Text components
#[derive(Component)]
pub(crate) struct PlayerHealth;
#[derive(Component)]
pub(crate) struct EnemyHealth;
#[derive(Component)]
pub(crate) struct PlayerLevel;
#[derive(Component)]
pub(crate) struct EnemyLevel;
#[derive(Component)]
pub(crate) struct BattleUIElement;
pub(crate) struct BattlePlugin;
pub(crate) struct SwitchMonsterEvent(Entity);
impl Plugin for BattlePlugin {
fn build(&self, app: &mut App) {
app.add_event::<SwitchMonsterEvent>()
.add_enter_system_set(
GameState::Battle,
SystemSet::new()
.with_system(setup_battle)
.with_system(setup_battle_stats)
.with_system(spawn_player_monster)
.with_system(spawn_enemy_monster),
)
.add_system_set(
ConditionSet::new()
// TODO: Use events and system ordering
// Run these systems only when in Battle state
.run_in_state(GameState::Battle)
// addl systems go here
.with_system(update_battle_stats)
.with_system(key_press_handler)
.with_system(update_player_monster)
.into(),
)
.add_exit_system(GameState::Battle, despawn_battle);
}
}
macro_rules! end_battle {
($commands:expr, $game_progress:expr, $my_monster:expr, $enemy_monster:expr) => {
// remove the monster from the enemy stats
$game_progress.enemy_stats.remove(&$enemy_monster);
$game_progress.spec_moves_left[0] = SPECIALS_PER_BATTLE;
$game_progress.spec_moves_left[1] = SPECIALS_PER_BATTLE;
// reset selected monster back to the first one in our bag
let first_monster = $game_progress.monster_id_entity.get(&0).unwrap().clone();
$commands.entity($my_monster).remove::<SelectedMonster>();
$commands.entity(first_monster).insert(SelectedMonster);
// the battle is over, remove enemy from monster anyways
$commands.entity($enemy_monster).remove::<Enemy>();
$commands.insert_resource(NextState(GameState::Playing));
};
}
macro_rules! monster_level_up {
($commands:expr, $game_progress:expr, $my_monster:expr, $up_by:expr) => {
let mut stats = $game_progress
.monster_entity_to_stats
.get_mut(&$my_monster)
.unwrap();
stats.lvl.level += 1 * $up_by;
stats.hp.max_health += 10 * $up_by;
stats.hp.health = stats.hp.max_health as isize;
stats.stg.atk += 2 * $up_by;
stats.stg.crt += 5 * $up_by;
stats.def.def += 1 * $up_by;
// we have to remove the old stats and add the new one
// because we cannot change the stats in place
$commands.entity($my_monster).remove::<MonsterStats>();
$commands.entity($my_monster).insert_bundle(stats.clone());
};
}
pub(crate) fn setup_battle(
mut commands: Commands,
asset_server: Res<AssetServer>,
cameras: Query<
(&Transform, Entity),
(
With<Camera2d>,
Without<MenuCamera>,
Without<SlidesCamera>,
Without<Player>,
Without<Tile>,
),
>,
) {
// what is this??
if cameras.is_empty() {
error!("No spawned camera...?");
return;
}
let (ct, _) = cameras.single();
// Backgrounds overlayed on top of the game world (to prevent the background
// from being despawned and needing regenerated by WFC).
// Main background is on -1, so layer this at 0.
// Monsters can be layered at 1. and buttons/other UI can be 2.
commands
.spawn_bundle(SpriteBundle {
texture: asset_server.load(BATTLE_BACKGROUND),
transform: Transform::from_xyz(ct.translation.x, ct.translation.y, 0.),
..default()
})
.insert(BattleBackground);
}
// -----------------------------------------------------------------------------------------------------------
pub(crate) fn setup_battle_stats(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut set: ParamSet<(
Query<&mut Level, With<SelectedMonster>>,
Query<&mut Level, With<Enemy>>,
)>,
) {
let mut my_lvl = 0;
let mut enemy_lvl = 0;
for my_monster in set.p0().iter_mut() {
my_lvl = my_monster.level;
}
for enemy_monster in set.p1().iter_mut() {
enemy_lvl = enemy_monster.level;
}
commands
.spawn_bundle(
// Create a TextBundle that has a Text with a list of sections.
TextBundle::from_sections([
// health header for player's monster
TextSection::new(
"HEALTH:",
TextStyle {
font: asset_server.load("buttons/PressStart2P.ttf"),
font_size: 28.0,
color: Color::BLACK,
},
),
// health of player's monster
TextSection::from_style(TextStyle {
font: asset_server.load("buttons/PressStart2P.ttf"),
font_size: 28.0,
color: Color::BLACK,
}),
])
.with_style(Style {
align_self: AlignSelf::FlexEnd,
position_type: PositionType::Absolute,
position: UiRect {
top: Val::Px(5.0),
left: Val::Px(15.0),
..default()
},
..default()
}),
)
.insert(PlayerHealth)
.insert(BattleUIElement);
commands
.spawn_bundle(
// Create a TextBundle that has a Text with a list of sections.
TextBundle::from_sections([
// level header for player's monster
TextSection::new(
"LEVEL:",
TextStyle {
font: asset_server.load("buttons/PressStart2P.ttf"),
font_size: 28.0,
color: Color::BLACK,
},
),
// level of player's monster
TextSection::new(
my_lvl.to_string(),
TextStyle {
font: asset_server.load("buttons/PressStart2P.ttf"),
font_size: 28.0,
color: Color::BLACK,
},
),
])
.with_style(Style {
align_self: AlignSelf::FlexEnd,
position_type: PositionType::Absolute,
position: UiRect {
top: Val::Px(40.0),
left: Val::Px(15.0),
..default()
},
..default()
}),
)
.insert(PlayerLevel)
.insert(BattleUIElement);
commands
.spawn_bundle(
// Create a TextBundle that has a Text with a list of sections.
TextBundle::from_sections([
// health header for enemy's monster
TextSection::new(
"HEALTH:",
TextStyle {
font: asset_server.load("buttons/PressStart2P.ttf"),
font_size: 28.0,
color: Color::BLACK,
},
),
// health of enemy's monster
TextSection::from_style(TextStyle {
font: asset_server.load("buttons/PressStart2P.ttf"),
font_size: 28.0,
color: Color::BLACK,
}),
])
.with_style(Style {
align_self: AlignSelf::FlexEnd,
position_type: PositionType::Absolute,
position: UiRect {
top: Val::Px(5.0),
right: Val::Px(15.0),
..default()
},
..default()
}),
)
//.insert(MonsterBundle::default())
.insert(EnemyHealth)
.insert(BattleUIElement);
commands
.spawn_bundle(
// Create a TextBundle that has a Text with a list of sections.
TextBundle::from_sections([
// level header for player's monster
TextSection::new(
"LEVEL:",
TextStyle {
font: asset_server.load("buttons/PressStart2P.ttf"),
font_size: 28.0,
color: Color::BLACK,
},
),
// level of player's monster
TextSection::new(
enemy_lvl.to_string(),
TextStyle {
font: asset_server.load("buttons/PressStart2P.ttf"),
font_size: 28.0,
color: Color::BLACK,
},
),
])
.with_style(Style {
align_self: AlignSelf::FlexEnd,
position_type: PositionType::Absolute,
position: UiRect {
top: Val::Px(40.0),
right: Val::Px(15.0),
..default()
},
..default()
}),
)
.insert(EnemyLevel)
.insert(BattleUIElement);
}
pub(crate) fn update_battle_stats(
_commands: Commands,
_asset_server: Res<AssetServer>,
mut set: ParamSet<(
Query<&mut Health, With<SelectedMonster>>,
Query<&mut Health, With<Enemy>>,
)>,
mut enemy_health_text_query: Query<&mut Text, (With<EnemyHealth>, Without<PlayerHealth>)>,
mut player_health_text_query: Query<&mut Text, (With<PlayerHealth>, Without<EnemyHealth>)>,
) {
let mut my_health = 0;
let mut enemy_health = 0;
for my_monster in set.p0().iter_mut() {
my_health = my_monster.health;
}
for enemy_monster in set.p1().iter_mut() {
enemy_health = enemy_monster.health;
}
for mut text in &mut enemy_health_text_query {
text.sections[1].value = format!("{}", enemy_health);
}
for mut text in &mut player_health_text_query {
text.sections[1].value = format!("{}", my_health);
}
}
pub(crate) fn spawn_player_monster(
mut commands: Commands,
asset_server: Res<AssetServer>,
cameras: Query<
(&Transform, Entity),
(With<Camera2d>, Without<MenuCamera>, Without<SlidesCamera>),
>,
selected_monster_query: Query<(&Element, Entity), (With<SelectedMonster>, Without<Enemy>)>,
) {
if cameras.is_empty() {
error!("No spawned camera...?");
return;
}
if selected_monster_query.is_empty() {
error!("No selected monster...?");
return;
}
let (ct, _) = cameras.single();
let (selected_type, _selected_monster) = selected_monster_query.single();
commands
.spawn_bundle(SpriteBundle {
sprite: Sprite {
flip_y: false, // flips our little buddy, you guessed it, in the y direction
flip_x: true, // guess what this does
..default()
},
texture: asset_server.load(&get_monster_sprite_for_type(*selected_type)),
transform: Transform::from_xyz(ct.translation.x - 400., ct.translation.y - 100., 1.),
..default()
})
.insert(PlayerMonster)
.insert(Monster);
}
pub(crate) fn update_player_monster(
mut commands: Commands,
asset_server: Res<AssetServer>,
cameras: Query<
(&Transform, Entity),
(With<Camera2d>, Without<MenuCamera>, Without<SlidesCamera>),
>,
mut switch_event: EventReader<SwitchMonsterEvent>,
game_progress: ResMut<GameProgress>,
player_monster_sprites: Query<Entity, With<PlayerMonster>>,
) {
if cameras.is_empty() {
error!("No spawned camera...?");
return;
}
let mut new_entity: Option<Entity> = None;
for event in switch_event.iter() {
info!("Event fired");
// Despawn
for pm in player_monster_sprites.iter() {
commands.entity(pm).despawn_recursive();
}
new_entity = Some(event.0);
}
if new_entity.is_none() {
return;
}
let new_type = game_progress
.monster_entity_to_stats
.get(&new_entity.unwrap())
.unwrap()
.typing;
info!("got type {:?}", new_type);
let (ct, _) = cameras.single();
commands
.spawn_bundle(SpriteBundle {
sprite: Sprite {
flip_y: false, // flips our little buddy, you guessed it, in the y direction
flip_x: true, // guess what this does
..default()
},
texture: asset_server.load(&get_monster_sprite_for_type(new_type)),
transform: Transform::from_xyz(ct.translation.x - 400., ct.translation.y - 100., 1.),
..default()
})
.insert(PlayerMonster)
.insert(Monster);
}
pub(crate) fn spawn_enemy_monster(
mut commands: Commands,
asset_server: Res<AssetServer>,
cameras: Query<
(&Transform, Entity),
(With<Camera2d>, Without<MenuCamera>, Without<SlidesCamera>),
>,
selected_type_query: Query<&Element, (Without<SelectedMonster>, With<Enemy>)>,
) {
if cameras.is_empty() {
error!("No spawned camera...?");
return;
}
if selected_type_query.is_empty() {
error!("No selected monster...?");
return;
}
let selected_type = selected_type_query.single();
let (ct, _) = cameras.single();
commands
.spawn_bundle(SpriteBundle {
texture: asset_server.load(&get_monster_sprite_for_type(*selected_type)),
transform: Transform::from_xyz(ct.translation.x + 400., ct.translation.y - 100., 1.),
..default()
})
.insert(EnemyMonster)
.insert(Monster);
// .insert(monster_info.clone());
}
pub(crate) fn despawn_battle(
mut commands: Commands,
background_query: Query<Entity, With<BattleBackground>>,
monster_query: Query<Entity, With<Monster>>,
battle_ui_element_query: Query<Entity, With<BattleUIElement>>,
) {
if background_query.is_empty() {
error!("background is not here!");
}
background_query.for_each(|background| {
commands.entity(background).despawn();
});
if monster_query.is_empty() {
error!("monsters are here!");
}
monster_query.for_each(|monster| {
commands
.entity(monster)
.remove_bundle::<SpriteBundle>()
.remove::<PlayerMonster>()
.remove::<EnemyMonster>()
.remove::<Monster>();
});
if battle_ui_element_query.is_empty() {
error!("ui elements are here!");
}
battle_ui_element_query.for_each(|battle_ui_element| {
commands.entity(battle_ui_element).despawn_recursive();
});
}
/// Handler system to enact battle actions based on key presses
pub(crate) fn key_press_handler(
input: Res<Input<KeyCode>>,
mut commands: Commands,
mut game_progress: ResMut<GameProgress>,
// placeholder for another resource dedicated to battle
mut my_monster: Query<
(&mut Health, &mut Strength, &mut Defense, Entity, &Element),
(With<SelectedMonster>, Without<Enemy>),
>,
mut enemy_monster: Query<
(
&mut Health,
&mut Strength,
&mut Defense,
Entity,
Option<&Boss>,
&Element,
),
(Without<SelectedMonster>, With<Enemy>),
>,
mut party_monsters: Query<
(&mut Health, &mut Strength, &mut Defense, Entity, &Element),
(With<PartyMonster>, Without<SelectedMonster>, Without<Enemy>),
>,
type_system: Res<TypeSystem>,
camera: Query<
(&Transform, Entity),
(With<Camera2d>, Without<MenuCamera>, Without<SlidesCamera>),
>,
asset_server: Res<AssetServer>,
mut text_buffer: ResMut<TextBuffer>,
mut switch_event: EventWriter<SwitchMonsterEvent>,
) {
if my_monster.is_empty() || enemy_monster.is_empty() {
info!("Monsters are missing!");
commands.insert_resource(NextState(GameState::Playing));
return;
}
if camera.is_empty() {
error!("No spawned camera?");
commands.insert_resource(NextState(GameState::Playing));
return;
}
let (transform, _) = camera.single();
// Get player and enemy monster data out of the query
let (mut player_health, mut player_stg, player_def, player_entity, player_type) =
my_monster.single_mut();
let (mut enemy_health, enemy_stg, enemy_def, enemy_entity, enemy_boss, enemy_type) =
enemy_monster.single_mut();
if player_health.health <= 0 {
let next_monster = game_progress.next_monster_cyclic(player_entity);
if next_monster.is_none() {
let text = PooledText {
text: format!("Monster defeated!"),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
end_battle!(commands, game_progress, player_entity, enemy_entity);
} else {
let text = PooledText {
text: format!("Monster defeated! Switching..."),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
switch_event.send(SwitchMonsterEvent(*next_monster.unwrap()));
commands.entity(player_entity).remove::<SelectedMonster>();
commands
.entity(player_entity)
.remove_bundle::<SpriteBundle>();
commands
.entity(*next_monster.unwrap())
.insert(SelectedMonster);
}
}
if input.just_pressed(KeyCode::A) {
// ATTACK HANDLER
// Actions:
// 0: attack 1: defend: 2: elemental: 3: special
// Enemy reaction
let mut enemy_action = rand::thread_rng().gen_range(0..=3);
// Enemy cannot special if it is out of special moves
if enemy_action == 3 && game_progress.spec_moves_left[1] == 0 {
enemy_action = rand::thread_rng().gen_range(0..=2);
}
let enemy_act_string = if enemy_action == 0 {
format!("Enemy attacks!")
} else if enemy_action == 1 {
format!("Enemy defends!")
} else if enemy_action == 2 {
format!("Enemy elemental!")
} else {
game_progress.spec_moves_left[1] -= 1;
format!("Enemy special!")
};
let text = PooledText {
text: format!("You attack! {}", enemy_act_string),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
let str_buff_damage = if game_progress.turns_left_of_buff[0] > 0 {
let text = PooledText {
text: format!("Buffed! Extra damage..."),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
game_progress.turns_left_of_buff[0] -= 1;
game_progress.current_level
} else {
0
};
// Temporarily increase strength for the turn calculation
player_stg.atk += str_buff_damage;
let turn_result = calculate_turn(
&player_stg,
&player_def,
player_type,
0,
&enemy_stg,
&enemy_def,
enemy_type,
enemy_action,
*type_system,
);
// Reset strength for next turn
player_stg.atk -= str_buff_damage;
// Critical check
if turn_result.2 {
let text = PooledText {
text: "You crit!".to_string(),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
}
if turn_result.3 {
let text = PooledText {
text: "Enemy crits!".to_string(),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
}
player_health.health -= turn_result.1;
enemy_health.health -= turn_result.0;
if enemy_health.health <= 0 {
let text = PooledText {
text: format!("Enemy defeated! Level up!"),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
// at this point this monster is already "ours", we just need to register is with the resource
// get the stats from the monster
let mut new_monster_stats = *game_progress.enemy_stats.get(&enemy_entity).unwrap();
// Clamp health down so we don't keep boss health
new_monster_stats.hp.health = game_progress.current_level as isize * 10;
new_monster_stats.hp.max_health = game_progress.current_level * 10;
// remove the monster from the enemy stats
game_progress.enemy_stats.remove(&enemy_entity);
// add the monster to the monster bag
commands.entity(enemy_entity).insert(PartyMonster);
game_progress.new_monster(enemy_entity, new_monster_stats);
let text = PooledText {
text: format!(
"New monster: {:?}",
game_progress
.monster_entity_to_stats
.get(&enemy_entity)
.unwrap()
.typing
),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
// update game progress
// check for boss
if enemy_boss.is_some() {
// info!("Boss defeated!");
let text = PooledText {
text: "Boss defeated!".to_string(),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
if let Some((reward, reward_amount)) = game_progress.get_quest_rewards(*enemy_type) {
let text = PooledText {
text: format!(
"Quest complete! You obtain {} {} items!",
reward_amount,
item_index_to_name(reward)),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
}
game_progress.win_boss();
// if boss level up twice
for pm in party_monsters.iter_mut() {
monster_level_up!(commands, game_progress, pm.3, 1);
}
monster_level_up!(commands, game_progress, player_entity, 1);
monster_level_up!(commands, game_progress, enemy_entity, 1);
commands.entity(enemy_entity).remove::<Boss>();
// Spawn an NPC if enemy_boss is some and we won
let new_quest = Quest::random();
let text = PooledText {
text: format!("Someone appears from the dust..."),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
commands
.spawn_bundle(SpriteBundle {
texture: asset_server.load(NPC_PATH),
transform: Transform::from_xyz(
transform.translation.x,
transform.translation.y,
0.,
),
..default()
})
.insert(NPC { quest: new_quest });
} else {
game_progress.win_battle();
if let Some((reward, reward_amount)) = game_progress.get_quest_rewards(*enemy_type) {
let text = PooledText {
text: format!(
"Quest complete! You obtain {} {} items!",
reward_amount,
item_index_to_name(reward)),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
}
// if not boss level up once
for pm in party_monsters.iter_mut() {
monster_level_up!(commands, game_progress, pm.3, 1);
}
monster_level_up!(commands, game_progress, player_entity, 1);
monster_level_up!(commands, game_progress, enemy_entity, 1);
}
end_battle!(commands, game_progress, player_entity, enemy_entity);
} else if player_health.health <= 0 {
game_progress.num_living_monsters -= 1;
let next_monster = game_progress.next_monster_cyclic(player_entity);
if next_monster.is_none() {
let text = PooledText {
text: format!("Defeated."),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
end_battle!(commands, game_progress, player_entity, enemy_entity);
} else {
let text = PooledText {
text: format!("Monster defeated. Switching."),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
switch_event.send(SwitchMonsterEvent(*next_monster.unwrap()));
commands.entity(player_entity).remove::<SelectedMonster>();
commands
.entity(player_entity)
.remove_bundle::<SpriteBundle>();
commands
.entity(*next_monster.unwrap())
.insert(SelectedMonster);
}
}
} else if input.just_pressed(KeyCode::E) {
// ELEMENTAL ATTACK HANDLER
// Actions:
// 0: attack 1: defend: 2: elemental: 3: special
// Enemy reaction
let mut enemy_action = rand::thread_rng().gen_range(0..=3);
// Enemy cannot special if it is out of special moves
if enemy_action == 3 && game_progress.spec_moves_left[1] == 0 {
enemy_action = rand::thread_rng().gen_range(0..=2);
}
let enemy_act_string = if enemy_action == 0 {
format!("Enemy attacks!")
} else if enemy_action == 1 {
format!("Enemy defends!")
} else if enemy_action == 2 {
format!("Enemy elemental!")
} else {
game_progress.spec_moves_left[1] -= 1;
format!("Enemy special!")
};
let text = PooledText {
text: format!("{:?} elemental! {}", player_type, enemy_act_string),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
let str_buff_damage = if game_progress.turns_left_of_buff[0] > 0 {
let text = PooledText {
text: format!("Buffed! Extra damage..."),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
game_progress.turns_left_of_buff[0] -= 1;
game_progress.current_level
} else {
0
};
// Temporarily increase strength for the turn calculation
player_stg.atk += str_buff_damage;
let turn_result = calculate_turn(
&player_stg,
&player_def,
player_type,
2,
&enemy_stg,
&enemy_def,
enemy_type,
enemy_action,
*type_system,
);
// Reset strength for next turn
player_stg.atk -= str_buff_damage;
// Critical check
if turn_result.2 {
let text = PooledText {
text: "You crit!".to_string(),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
}
if turn_result.3 {
let text = PooledText {
text: "Enemy crits!".to_string(),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
}
player_health.health -= turn_result.1;
enemy_health.health -= turn_result.0;
if enemy_health.health <= 0 {
let text = PooledText {
text: format!("Enemy defeated! Level up!"),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
// at this point this monster is already "ours", we just need to register is with the resource
// get the stats from the monster
let mut new_monster_stats = *game_progress.enemy_stats.get(&enemy_entity).unwrap();
// Clamp health down so we don't keep boss health
new_monster_stats.hp.health = game_progress.current_level as isize * 10;
new_monster_stats.hp.max_health = game_progress.current_level * 10;
// remove the monster from the enemy stats
game_progress.enemy_stats.remove(&enemy_entity);
// add the monster to the monster bag
commands.entity(enemy_entity).insert(PartyMonster);
game_progress.new_monster(enemy_entity, new_monster_stats);
let text = PooledText {
text: format!(
"New monster: {:?}",
game_progress
.monster_entity_to_stats
.get(&enemy_entity)
.unwrap()
.typing
),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
// update game progress
// check for boss
if enemy_boss.is_some() {
// info!("Boss defeated!");
let text = PooledText {
text: "Boss defeated!".to_string(),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
if let Some((reward, reward_amount)) = game_progress.get_quest_rewards(*enemy_type) {
let text = PooledText {
text: format!(
"Quest complete! You obtain {} {} items!",
reward_amount,
item_index_to_name(reward)),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
}
game_progress.win_boss();
// if boss level up twice
for pm in party_monsters.iter_mut() {
monster_level_up!(commands, game_progress, pm.3, 1);
}
monster_level_up!(commands, game_progress, player_entity, 1);
monster_level_up!(commands, game_progress, enemy_entity, 1);
commands.entity(enemy_entity).remove::<Boss>();
// Spawn an NPC if enemy_boss is some and we won
let new_quest = Quest::random();
let text = PooledText {
text: format!("Someone appears from the dust..."),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
commands
.spawn_bundle(SpriteBundle {
texture: asset_server.load(NPC_PATH),
transform: Transform::from_xyz(
transform.translation.x,
transform.translation.y,
0.,
),
..default()
})
.insert(NPC { quest: new_quest });
} else {
game_progress.win_battle();
if let Some((reward, reward_amount)) = game_progress.get_quest_rewards(*enemy_type) {
let text = PooledText {
text: format!(
"Quest complete! You obtain {} {} items!",
reward_amount,
item_index_to_name(reward)),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
}
// if not boss level up once
for pm in party_monsters.iter_mut() {
monster_level_up!(commands, game_progress, pm.3, 1);
}
monster_level_up!(commands, game_progress, player_entity, 1);
monster_level_up!(commands, game_progress, enemy_entity, 1);
}
end_battle!(commands, game_progress, player_entity, enemy_entity);
} else if player_health.health <= 0 {
game_progress.num_living_monsters -= 1;
let next_monster = game_progress.next_monster_cyclic(player_entity);
if next_monster.is_none() {
let text = PooledText {
text: format!("Defeated."),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
end_battle!(commands, game_progress, player_entity, enemy_entity);
} else {
let text = PooledText {
text: format!("Monster defeated. Switching."),
pooled: false,
};
text_buffer.bottom_text.push_back(text);
switch_event.send(SwitchMonsterEvent(*next_monster.unwrap()));
commands.entity(player_entity).remove::<SelectedMonster>();
commands
.entity(player_entity)
.remove_bundle::<SpriteBundle>();
commands
.entity(*next_monster.unwrap())
.insert(SelectedMonster);
}
}
} else if input.just_pressed(KeyCode::S) {
// SPECIAL ATTACK HANDLER
// The way special/multi-move attacks work is we do the
// monster's unique elemental attack followed immediately by a base attack,
// WITHOUT giving the enemy the chance to respond twice, only once to the whole attack.
// If this seems overpowered, it's because it is. We only allow a special attack to be used
// twice per battle.
// Enemy reaction
let mut enemy_action = rand::thread_rng().gen_range(0..=3);
// Enemy cannot special if it is out of special moves
if enemy_action == 3 && game_progress.spec_moves_left[1] == 0 {
enemy_action = rand::thread_rng().gen_range(0..=2);
}
let enemy_act_string = if enemy_action == 0 {
format!("Enemy attacks!")
} else if enemy_action == 1 {
format!("Enemy defends!")
} else if enemy_action == 2 {
format!("Enemy elemental!")
} else {
game_progress.spec_moves_left[1] -= 1;
format!("Enemy special!")