-
Notifications
You must be signed in to change notification settings - Fork 0
/
gameplay.gd
944 lines (860 loc) · 33.4 KB
/
gameplay.gd
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
extends Node3D
class_name Gameplay
enum GameState {
HUMAN_TURN,
CPU_TURN,
}
var state_text = {
GameState.HUMAN_TURN: "Your turn",
GameState.CPU_TURN: "Enemy turn",
}
enum HumanTurnState {
# When turn starts. So we can differentiate beginning of turn transitions
# to WAITING.
STARTING,
# Waiting for move or action to be chosen.
# During this move we show move paths based on mouse pointer.
WAITING,
# Executing a move. No actions can be chosen, no character change, etc
MOVING,
# An action has been chosen and we are waiting to choose a target.
ACTION_TARGET,
# Playing a card. No actions can be chosen, no character change, etc.
PLAYING_CARD,
# Teleporting as part of playing a card.
PLAY_TELEPORTING,
}
var turn_number = 0
var portrait_scene = preload("res://character_portrait.tscn")
var card_ui_scene = preload("res://card_ui.tscn")
var active_character: Character
var active_character_index: int
# Direction of mouse position respect active character.
# E.g. Vector2.right if it's more to the right than up/down.
var direction: Vector2
var state: GameState
var human_turn_state = HumanTurnState.STARTING
var map_manager = MapManager.new()
var current_path: PackedVector2Array = PackedVector2Array()
var valid_path: bool = false
var too_long_path: bool = false
# Whether the current tile is a valid target (in ACTION_TARGET mode).
var valid_target: bool = false
var tile_map_pos: Vector2i = Vector2i(0, 0)
var current_card: Card
var target_cursor: CardTargetHighlight
var single_cursor: SingleCursorHighlight
var target_area: AreaDistanceHighlight
var player_move_area: TilesHighlight
var enemy_move_area: TilesHighlight
var enemy_attack_area: TilesHighlight
var objective_highlight: TilesHighlight
var camera_panning_speed = 15
var camera_rotation_speed = 100
# Move somewhere where it can be used from anywhere or figure out how to pass.
var tile_size: int = 2
var enemy_moving = false
var card_simulation_manager = CardSimulationManager.new()
var enemy_turn_manager = EnemyTurnManager.new()
var animation_manager = AnimationManager.new()
var stage_trigger_manager: StageTriggerManager
var card_player: CardPlayer
# New stages are added to this node.
@export var world: Node
# Effects go under this node.
@export var effects: Node
# Enemies are under this node.
@export var enemies_node: Node
@export var doors_node: Node
@export var damage_labels_node: Node
@export var hand_ui: HandUI
@export var deck_ui: Control
@export var discard_ui: Control
@export var character_state_ui: Control
@export var camera: Camera3D
@export var camera_pivot: Node3D
@export var end_turn_button: Button
@export var undo_button: Button
@export var treasures: Node
@export var stage_info: Label
@export var objective_info: Label
@export var turn_state_info: Label
@export var enemy_portrait: CharacterPortrait
@export var treasure_info: RichTextLabel
@export var shared_bag_gold_ui: SharedBagGoldUI
@export var move_path: Line2D
class UndoState:
var position
var move_points
var undo_states: Dictionary
var party: Node
var shared_bag: SharedBag
var teleport_distance: int
signal teleport_finished
var enemy_walkable_cache: Dictionary
var enemy_attackable_cache: Dictionary
var restored_from_save = false
signal enemy_died
signal character_moved(pos: Vector2i)
signal all_enemies_died
signal new_turn_started(turn: int)
signal stage_done
signal game_over
# Called when the node enters the scene tree for the first time.
func _ready():
undo_button.hide()
hand_ui.card_selected.connect(_on_card_selected)
func initialize(stage: Stage, character_party: Node, shared_bag: SharedBag, combat_state: CombatSaveState = null):
self.shared_bag = shared_bag
shared_bag_gold_ui.set_shared_bag(shared_bag)
party = character_party
var i = 0
for character in party.get_children():
var character_portrait = portrait_scene.instantiate() as CharacterPortrait
character_portrait.set_mode(CharacterPortrait.PortraitMode.COMBAT)
# Add portraits in UI.
character_state_ui.add_child(character_portrait)
# Set portrait on character so it can update when e.g. move points change
character_portrait.set_character(character)
character.made_active.connect(character_portrait.set_active)
# Hook character selection.
character_portrait.pressed.connect(_on_character_portrait_pressed.bind(i))
i += 1
initialize_stage(stage, combat_state)
func initialize_stage(stage: Stage, combat_state: CombatSaveState):
if combat_state == null:
stage.initialize(enemies_node)
var i = 0
for character in party.get_children():
character.begin_stage(self)
character.set_id_position(stage.starting_positions[i])
i += 1
# Usually "turn stats" are created at beginning of enemy turn, create here the first time.
StatsManager.add_level(Enum.StatsLevel.TURN)
turn_number = 0
else:
# Usually initialized in begin_stage().
for character in party.get_children():
character.gameplay = self
for enemy_data in combat_state.enemies:
var enemy = EnemyLoader.restore(enemy_data)
enemies_node.add_child(enemy)
# To show healthbar if they are hurt.
enemy.refresh()
turn_number = combat_state.turn_number
restored_from_save = true
# Update doors' state in stage ahead of creating them.
var updated_doors = 0
assert(combat_state.doors.size() == stage.doors.size())
for door_def in combat_state.doors:
for stage_door_def in stage.doors:
if door_def.pos == stage_door_def.pos:
stage_door_def.state = door_def.state
updated_doors += 1
break
assert(updated_doors == combat_state.doors.size())
for character in party.get_children():
character.set_damage_labels_node(damage_labels_node)
character.destroyed.connect(handle_character_death.bind(character))
for enemy in enemies_node.get_children():
enemy.set_damage_labels_node(damage_labels_node)
enemy.destroyed.connect(_on_enemy_death.bind(enemy))
enemy_died.connect(stage.enemy_died_handler)
character_moved.connect(stage.character_moved_handler)
all_enemies_died.connect(stage.all_enemies_died_handler)
new_turn_started.connect(stage.new_turn_started_handler)
stage.stage_completed.connect(next_stage)
initialize_stage_trigger_manager(stage.triggers)
world.add_child(stage)
initialize_map_manager(stage)
card_player = CardPlayer.new(map_manager, effects)
if combat_state != null:
for treasure_state in combat_state.treasures:
var treasure = TreasureLoader.restore(treasure_state)
map_manager.add_treasure(treasure)
treasures.add_child(treasure)
card_simulation_manager.initialize(map_manager)
card_simulation_manager.invalidated.connect(on_card_simulation_invalidated)
card_simulation_manager.calculated.connect(on_card_simulation_calculated)
enemy_turn_manager.initialize(map_manager, effects)
enemy_turn_manager.invalidated.connect(on_enemy_turn_invalidated)
enemy_turn_manager.calculated.connect(on_enemy_turn_calculated)
player_move_area = TilesHighlight.new(map_manager)
enemy_move_area = TilesHighlight.new(map_manager)
enemy_attack_area = TilesHighlight.new(map_manager)
enemy_move_area.set_color(Color(1, 0, 0, 1))
enemy_attack_area.set_color(Color(1, 1, 1, 1))
world.add_child(player_move_area)
world.add_child(enemy_move_area)
world.add_child(enemy_attack_area)
if stage.stage_completion_type == stage.StageCompletionType.REACH_POSITION:
objective_highlight = TilesHighlight.new(map_manager, [stage.reach_position_target])
objective_highlight.set_color(Color(0, 0, 1, 1))
objective_highlight.set_width(4)
objective_highlight.refresh.call_deferred()
stage.add_child(objective_highlight)
stage_info.text = "Stage"
objective_info.text = stage.get_objective_string()
# As of now, some bits of the game require active_character to be set,
# so set it now before changing state.
set_active_character(0)
change_state(GameState.HUMAN_TURN)
func initialize_stage_trigger_manager(triggers: Array[StageTrigger]):
stage_trigger_manager = StageTriggerManager.new(triggers)
enemy_died.connect(stage_trigger_manager.on_enemy_died)
new_turn_started.connect(stage_trigger_manager.on_begin_turn)
stage_trigger_manager.spawn_treasure_cb = spawn_treasure
stage_trigger_manager.open_door_cb = open_door
stage_trigger_manager.close_door_cb = close_door
func on_card_simulation_calculated(damage_taken: Array):
# This can include characters, for now focus on enemies, we may want to do something later.
for info in damage_taken:
var loc = info[0]
var damage = info[1]
if loc in map_manager.enemy_locs:
map_manager.enemy_locs[loc].set_pending_damage(damage)
func on_card_simulation_invalidated():
for enemy in enemies_node.get_children():
enemy.clear_pending_damage()
func on_enemy_turn_calculated(damage_taken: Array):
for info in damage_taken:
var loc = info[0]
var damage = info[1]
map_manager.character_locs[loc].set_pending_damage(damage)
func on_enemy_turn_invalidated():
for character in party.get_children():
character.clear_pending_damage()
func next_stage():
StatsManager.remove_level(Enum.StatsLevel.TURN)
stage_done.emit()
func initialize_map_manager(stage: Stage):
map_manager.initialize(stage, doors_node)
map_manager.set_party(party.get_children())
map_manager.set_enemies(enemies_node.get_children())
map_manager.initialize_a_star()
func open_door(pos: Vector2i):
map_manager.open_door(pos)
func close_door(pos: Vector2i):
map_manager.close_door(pos)
func _on_character_portrait_pressed(index: int):
# Only allow to change active character during human turn on waiting state.
if state != GameState.HUMAN_TURN or human_turn_state != HumanTurnState.WAITING:
return
if not party.get_child(index).is_destroyed:
set_active_character(index)
func draw_deck():
# Clear discard.
for child in discard_ui.get_children():
child.queue_free()
# Display last discarded card.
if not active_character.deck.discard.is_empty():
var new_card = card_ui_scene.instantiate() as CardUI
new_card.initialize(active_character.deck.discard.back(), active_character)
discard_ui.add_child(new_card)
new_card.tooltip_text = "%d cards on discard pile" % active_character.deck.discard.size()
# Set deck tooltip.
deck_ui.tooltip_text = "%d cards on deck" % active_character.deck.stage_deck_size()
func set_active_character(index: int):
var i = 0
for character in party.get_children():
if i == index:
active_character = party.get_child(i)
assert(not active_character.is_destroyed)
active_character.set_active(true)
hand_ui.reset(active_character)
else:
character.set_active(false)
character.clear_pending_move_cost()
i += 1
active_character_index = index
change_human_turn_state(HumanTurnState.WAITING)
func next_live_character_index() -> int:
for i in range(active_character_index + 1, party.get_child_count()):
if not party.get_child(i).is_destroyed:
return i
for i in range(0, active_character_index):
return i
assert(false)
return -1
func _on_card_selected(card: Card):
if current_card != null:
target_area.queue_free()
target_cursor.queue_free()
active_character.clear_pending_action_cost()
current_card = card
# Update prospective cost in character.
active_character.set_pending_action_cost(current_card.cost)
change_human_turn_state(HumanTurnState.ACTION_TARGET)
func create_cursor(pos: Vector2i, direction: Vector2):
var cursor_pos = pos
if current_card.target_mode == Enum.TargetMode.SELF:
cursor_pos = active_character.get_id_position()
target_cursor = CardTargetHighlight.new(map_manager, cursor_pos, direction, current_card)
target_cursor.set_width(3)
target_cursor.refresh()
world.add_child(target_cursor)
func create_single_cursor(pos: Vector2i):
single_cursor = SingleCursorHighlight.new(map_manager, pos)
single_cursor.set_width(3)
single_cursor.refresh()
world.add_child(single_cursor)
func add_unprojected_point(line: Line2D, world_pos: Vector3):
var unprojected = camera.unproject_position(world_pos)
line.add_point(unprojected)
func create_target_area(pos: Vector2i, distance: int):
# TODO: Optionally (parameter) respect line-of-sight here.
if is_instance_valid(target_area):
target_area.queue_free()
target_area = AreaDistanceHighlight.new(map_manager, pos, distance, true)
target_area.refresh()
world.add_child(target_area)
func offsets_within_distance(distance: int) -> Array[Vector2i]:
var tiles: Array[Vector2i] = []
var zero = Vector2i(0, 0)
var i = -distance
while i <= distance:
var j = -distance
while j <= distance:
var tile = Vector2i(i, j)
if map_manager.distance(zero, tile) <= distance:
tiles.push_back(tile)
j += 1
i += 1
return tiles
func get_attack_cells(enemy: Enemy, positions: Array) -> Array:
var attack_positions = {}
var offsets = offsets_within_distance(enemy.max_attack_distance())
for pos in positions:
var visible_tiles = map_manager.fov.get_fov(pos)
for offset in offsets:
var tile = pos + offset
if map_manager.in_bounds(tile) and not map_manager.is_solid(tile, false, false, false) and tile in visible_tiles:
attack_positions[tile] = true
return attack_positions.keys()
func update_move_area(move_positions: Array, attack_positions: Array):
enemy_move_area.set_tiles(move_positions)
enemy_move_area.visible = true
enemy_attack_area.set_tiles(attack_positions)
enemy_attack_area.visible = true
func path_cost(path: PackedVector2Array) -> int:
var cost = 0
for i in path.size()-1:
var path_diff = path[i+1] - path[i]
if path_diff[0] == 0 or path_diff[1] == 0:
cost += 2
else:
cost += 3
return cost
func clear_path():
current_path.clear()
move_path.clear_points()
player_move_area.hide()
func calculate_path(tile_map_pos):
# Active character position
var pos = active_character.get_id_position()
# Calculate mouse pointer position on the tilemap
current_path = map_manager.get_path(pos, tile_map_pos)
valid_path = !current_path.is_empty()
var cost = path_cost(current_path)
too_long_path = (cost > active_character.move_points)
# Update prospective cost in character.
if !valid_path or too_long_path:
active_character.clear_pending_move_cost()
else:
active_character.set_pending_move_cost(cost)
# Draw path.
move_path.clear_points()
if valid_path:
for point in current_path:
var location = map_manager.get_world_position(point)
add_unprojected_point(move_path, location)
if too_long_path:
move_path.default_color = Color(1, 0, 0, 1)
player_move_area.hide()
else:
move_path.default_color = Color(1, 1, 1, 1)
var walkable_cells = map_manager.get_walkable_cells(tile_map_pos, active_character.move_points - cost, [active_character.get_id_position()])
player_move_area.set_tiles(walkable_cells)
player_move_area.show()
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
var camera_move = delta * camera_panning_speed
var camera_rotate = delta * camera_rotation_speed
var camera_forward = -camera_pivot.transform.basis.z
camera_forward.y = 0
var forward = camera_forward.normalized() * camera_move
var camera_modified = false
if Input.is_action_pressed("ui_right"):
camera_pivot.position += forward.cross(Vector3.UP)
camera_modified = true
if Input.is_action_pressed("ui_left"):
camera_pivot.position -= forward.cross(Vector3.UP)
camera_modified = true
if Input.is_action_pressed("ui_up"):
camera_pivot.position += forward
camera_modified = true
if Input.is_action_pressed("ui_down"):
camera_pivot.position -= forward
camera_modified = true
if Input.is_action_pressed("ui_rotate_left"):
camera_pivot.rotate_y(-camera_rotate*delta)
camera_modified = true
if Input.is_action_pressed("ui_rotate_right"):
camera_pivot.rotate_y(camera_rotate*delta)
camera_modified = true
if Input.is_action_just_released("ui_zoom_in"):
camera.fov -= 1
if camera.fov < 10:
camera.fov = 10
if Input.is_action_just_released("ui_zoom_out"):
camera.fov += 1
# Update if needed to zoom out more.
if camera.fov > 100:
camera.fov = 100
if camera_modified:
update_position_direction(get_viewport().get_mouse_position())
if state == GameState.CPU_TURN:
if enemy_turn_manager.fresh and not enemy_moving:
# Consider adding a CpuTurnState if needed.
enemy_moving = true
await enemy_turn_manager.execute_moves(map_manager)
enemy_moving = false
if map_manager.enemy_locs.is_empty():
all_enemies_died.emit()
change_state(GameState.HUMAN_TURN)
func reset_undo():
undo_button.hide()
for character in party.get_children():
var undo_state = UndoState.new()
undo_state.position = character.get_id_position()
undo_state.move_points = character.move_points
undo_states[character] = undo_state
func apply_undo():
for character in undo_states:
var undo_state = undo_states[character]
map_manager.move_character(character.get_id_position(), undo_state.position)
character.set_id_position(undo_state.position)
# If no move to undo for this character, move on to next. Otherwise
# it could crash if there are no stats for this character in the stage.
if undo_state.move_points == character.move_points:
continue
var reverted_move_points = undo_state.move_points - character.move_points
character.move_points = undo_state.move_points
StatsManager.remove(character.character_type, Stats.Field.MP_USED, reverted_move_points)
# No need to reset as it should now match.
undo_button.hide()
enemy_turn_manager.update()
func begin_turn():
for enemy in enemies_node.get_children():
enemy.end_turn()
clear_enemy_info_cache()
turn_number += 1
for character in party.get_children():
character.begin_turn()
character.snap()
for card in character.next_turn_cards:
var unit_card = UnitCard.new(character, card)
card_player.play_card_next_turn_effects(unit_card)
character.clear_next_turn_cards()
reset_undo()
draw_deck()
for treasure in treasures.get_children():
treasure.turns_left -= 1
if treasure.turns_left == 0:
var pos = treasure.get_id_position()
map_manager.remove_treasure(pos)
new_turn_started.emit(turn_number)
# To trigger beginning of turn effects.
change_human_turn_state(HumanTurnState.STARTING)
change_human_turn_state(HumanTurnState.WAITING)
func spawn_treasure():
var treasure = TreasureLoader.create()
treasure.initialize()
treasure.set_id_position(map_manager.get_random_empty_tile())
map_manager.add_treasure(treasure)
treasures.add_child(treasure)
func change_state(new_state):
state = new_state
if state == GameState.HUMAN_TURN:
# If restored_from_save, don't trigger begin_turn on first human turn.
if restored_from_save:
# Need to go through STARTING to trigger enemy updater.
change_human_turn_state(HumanTurnState.STARTING)
change_human_turn_state(HumanTurnState.WAITING)
restored_from_save = false
else:
begin_turn()
elif state == GameState.CPU_TURN:
end_turn_button.disabled = true
hand_ui.disabled = true
# Re-start turn stats so we can use enemy turn stats in cards next run.
StatsManager.remove_level(Enum.StatsLevel.TURN)
StatsManager.add_level(Enum.StatsLevel.TURN)
for character in party.get_children():
character.end_turn()
turn_state_info.text = "%s: %d" % [state_text[state], turn_number]
func change_human_turn_state(new_state):
if new_state == HumanTurnState.WAITING:
card_simulation_manager.stop()
hand_ui.disabled = false
end_turn_button.disabled = false
if human_turn_state in [HumanTurnState.ACTION_TARGET]:
hand_ui.unselect()
current_card = null
target_cursor.queue_free()
target_area.queue_free()
active_character.clear_pending_action_cost()
if human_turn_state in [HumanTurnState.STARTING, HumanTurnState.MOVING, HumanTurnState.PLAYING_CARD]:
enemy_turn_manager.update()
clear_path()
elif new_state == HumanTurnState.ACTION_TARGET:
hand_ui.disabled = false
end_turn_button.disabled = true
clear_path()
create_target_area(active_character.get_id_position(), current_card.target_distance)
create_cursor(tile_map_pos, direction)
elif new_state == HumanTurnState.MOVING:
hand_ui.disabled = true
end_turn_button.disabled = true
elif new_state == HumanTurnState.PLAYING_CARD:
hand_ui.disabled = true
end_turn_button.disabled = true
elif new_state == HumanTurnState.PLAY_TELEPORTING:
hand_ui.disabled = true
create_target_area(active_character.get_id_position(), teleport_distance)
create_single_cursor(tile_map_pos)
human_turn_state = new_state
func _on_end_turn_button_pressed():
change_state(GameState.CPU_TURN)
func handle_move():
# Current path is empty, so we can't move. Do nothing.
if !valid_path or too_long_path:
return
change_human_turn_state(HumanTurnState.MOVING)
# Save positions as they change.
var final_pos = tile_map_pos
await active_character.move(map_manager, final_pos)
var move_cost = path_cost(current_path)
active_character.reduce_move(move_cost)
StatsManager.add(active_character.character_type, Stats.Field.MP_USED, move_cost)
await handle_after_move()
character_moved.emit(final_pos)
clear_enemy_info_cache()
change_human_turn_state(HumanTurnState.WAITING)
func handle_teleport():
# Allow to "skip" by allowing teleporting to current location.
if tile_map_pos != active_character.get_id_position():
# Don't teleport on top of something, except a treasure.
if map_manager.is_solid(tile_map_pos, true, true, false):
return
var distance = map_manager.distance(active_character.get_id_position(), tile_map_pos)
if distance > teleport_distance:
return
# TODO: Handle teleport "animation".
map_manager.move_character(active_character.get_id_position(), tile_map_pos)
active_character.set_id_position(tile_map_pos)
await handle_after_move()
character_moved.emit(tile_map_pos)
clear_enemy_info_cache()
target_area.queue_free()
single_cursor.queue_free()
change_human_turn_state(HumanTurnState.PLAYING_CARD)
teleport_finished.emit()
func handle_after_move():
var can_undo = true
if map_manager.treasure_locs.has(active_character.get_id_position()):
can_undo = false
await pick_up_treasure(active_character.get_id_position())
if can_undo:
undo_button.show()
else:
reset_undo()
func pick_up_treasure(pos: Vector2i):
var treasure: Treasure = map_manager.treasure_locs[pos]
for effect in treasure.def.effects:
await UnitCard.apply_effect_target(active_character, effect, active_character)
map_manager.remove_treasure(pos)
active_character.add_stat(Stats.Field.CHESTS_ACQUIRED, 1)
func _input(event):
if Input.is_action_just_released("ui_cancel"):
if state == GameState.HUMAN_TURN:
if human_turn_state == HumanTurnState.ACTION_TARGET:
get_viewport().set_input_as_handled()
change_human_turn_state(HumanTurnState.WAITING)
if Input.is_action_pressed("ui_showenemymove"):
show_enemy_moves()
if Input.is_action_just_released("ui_showenemymove"):
clear_enemy_info()
if Input.is_action_just_released("ui_focus_next"):
if state == GameState.HUMAN_TURN and human_turn_state in [HumanTurnState.WAITING, HumanTurnState.ACTION_TARGET]:
if live_characters().size() > 1:
set_active_character(next_live_character_index())
func show_enemy_moves():
var final_walkable_cells = Dictionary()
var final_attackable_cells = Dictionary()
for enemy in enemies_node.get_children():
var walkable_cells = get_enemy_walkable_cells(enemy)
for cell in walkable_cells:
if cell not in final_attackable_cells:
final_walkable_cells[cell] = true
var attackable_cells = get_enemy_attackable_cells(enemy)
for cell in attackable_cells:
if not cell in final_attackable_cells:
final_attackable_cells[cell] = 0
final_attackable_cells[cell] += 1
if final_walkable_cells.has(cell):
final_walkable_cells.erase(cell)
enemy_move_area.set_tiles(final_walkable_cells.keys())
enemy_move_area.visible = true
enemy_attack_area.set_labeled_tiles(final_attackable_cells)
enemy_attack_area.visible = true
func get_enemy_walkable_cells(enemy: Enemy):
if enemy_walkable_cache.has(enemy):
return enemy_walkable_cache[enemy]
var walkable_cells = map_manager.get_walkable_cells(enemy.get_id_position(), enemy.move_points)
enemy_walkable_cache[enemy] = walkable_cells
return walkable_cells
func get_enemy_attackable_cells(enemy: Enemy):
if enemy_attackable_cache.has(enemy):
return enemy_attackable_cache[enemy]
var walkable_cells = get_enemy_walkable_cells(enemy)
var attackable_cells = get_attack_cells(enemy, walkable_cells)
enemy_attackable_cache[enemy] = attackable_cells
return attackable_cells
func get_enemy_attackable_not_walkable_cells(enemy: Enemy):
var walkable_cells = get_enemy_walkable_cells(enemy)
var walkable = {}
for cell in walkable_cells:
walkable[cell] = true
var attackable_cells = get_attack_cells(enemy, walkable_cells)
var attackable_not_walkable = []
for cell in attackable_cells:
if not walkable.has(cell):
attackable_not_walkable.push_back(cell)
return attackable_not_walkable
func clear_enemy_info_cache():
enemy_walkable_cache.clear()
enemy_attackable_cache.clear()
func update_enemy_info(enemy: Enemy):
if Input.is_action_pressed("ui_showenemymove"):
return
enemy_portrait.set_character(enemy)
enemy_portrait.set_mode(CharacterPortrait.PortraitMode.COMBAT)
enemy_portrait.show()
var walkable_cells = get_enemy_walkable_cells(enemy)
var attackable_cells = get_enemy_attackable_not_walkable_cells(enemy)
update_move_area(walkable_cells, attackable_cells)
func clear_enemy_info():
if Input.is_action_pressed("ui_showenemymove"):
return
enemy_move_area.visible = false
enemy_attack_area.visible = false
func _on_enemy_death(enemy: Enemy):
active_character.add_stat(Stats.Field.ENEMIES_KILLED, 1)
var pos = enemy.get_id_position()
map_manager.remove_enemy(pos)
if enemy_portrait.unit == enemy:
enemy_portrait.hide()
enemy.queue_free()
enemy_died.emit()
func live_characters():
var characters = []
for character in party.get_children():
if not character.is_destroyed:
characters.push_back(character)
return characters
func handle_character_death(character: Character):
var pos = character.get_id_position()
character.hide()
map_manager.remove_character(pos)
var characters = live_characters()
if not characters.is_empty():
set_active_character(next_live_character_index())
reset_undo()
else:
handle_game_over()
func handle_game_over():
StatsManager.remove_level(Enum.StatsLevel.TURN)
game_over.emit()
func clear_effects():
for effect in effects.get_children():
effect.queue_free()
func play_card():
# If we are in this function, the target was valid.
change_human_turn_state(HumanTurnState.PLAYING_CARD)
var unit_card = UnitCard.new(active_character, current_card)
# Discard card first.
if current_card.should_exhaust():
active_character.deck.exhaust_card(hand_ui.selected_index)
else:
active_character.deck.discard_card(hand_ui.selected_index)
# Take snapshot of current state before playing card.
active_character.snap()
# All card playing logic is in here.
await card_player.play_card(unit_card, tile_map_pos, direction)
active_character.add_stat(Stats.Field.CARDS_PLAYED, 1)
active_character.add_stat(Stats.Field.AP_USED, current_card.cost)
active_character.action_points -= current_card.cost
active_character.card_played.emit(active_character, current_card)
if unit_card.card.is_attack():
active_character.attacked.emit(active_character)
# Consider wrapping all this into a method.
target_area.queue_free()
target_cursor.queue_free()
active_character.clear_pending_action_cost()
reset_undo()
clear_enemy_info_cache()
draw_deck()
current_card = null
if not hand_ui.animation_finished.is_null():
await hand_ui.animation_finished
if map_manager.enemy_locs.is_empty():
all_enemies_died.emit()
change_human_turn_state(HumanTurnState.WAITING)
func teleport(character: Character, distance: int):
teleport_distance = distance
change_human_turn_state(HumanTurnState.PLAY_TELEPORTING)
await teleport_finished
func update_target(new_tile_map_pos: Vector2i, new_direction: Vector2):
valid_target = false
# For target mode SELF, allow clicking anywhere.
if current_card.target_mode == Enum.TargetMode.SELF:
valid_target = true
elif current_card.target_mode in [Enum.TargetMode.ENEMY, Enum.TargetMode.ALLY, Enum.TargetMode.SELF_ALLY]:
target_cursor.update(new_tile_map_pos, new_direction)
var distance = map_manager.distance(active_character.get_id_position(), new_tile_map_pos)
var visible_tiles = map_manager.fov.get_fov(active_character.get_id_position())
if distance > current_card.target_distance or not new_tile_map_pos in visible_tiles:
valid_target = false
target_cursor.set_color(Color(0, 0, 0, 1))
else:
match current_card.target_mode:
Enum.TargetMode.ENEMY:
if map_manager.enemy_locs.has(new_tile_map_pos):
target_cursor.set_color(Color(1, 0, 0, 1))
valid_target = true
else:
target_cursor.set_color(Color(1, 1, 1, 1))
Enum.TargetMode.ALLY:
if new_tile_map_pos != active_character.get_id_position() and map_manager.character_locs.has(new_tile_map_pos):
target_cursor.set_color(Color(0, 1, 0, 1))
valid_target = true
else:
target_cursor.set_color(Color(1, 1, 1, 1))
Enum.TargetMode.SELF_ALLY:
if map_manager.character_locs.has(new_tile_map_pos):
target_cursor.set_color(Color(0, 1, 0, 1))
valid_target = true
else:
target_cursor.set_color(Color(1, 1, 1, 1))
elif current_card.target_mode == Enum.TargetMode.AREA:
target_cursor.update(new_tile_map_pos, new_direction)
var distance = map_manager.distance(active_character.get_id_position(), new_tile_map_pos)
var visible_tiles = map_manager.fov.get_fov(active_character.get_id_position())
if distance > current_card.target_distance or not new_tile_map_pos in visible_tiles:
valid_target = false
target_cursor.set_color(Color(0, 0, 0, 1))
else:
target_cursor.set_color(Color(1, 0, 0, 1))
valid_target = true
func snap_to_direction(vector: Vector2) -> Vector2:
var min_distance = null
var direction = null
for v in [Vector2.UP, Vector2.DOWN, Vector2.RIGHT, Vector2.LEFT]:
var distance = vector.distance_squared_to(v)
if min_distance == null:
min_distance = distance
direction = v
else:
if distance < min_distance:
min_distance = distance
direction = v
return direction
func mouse_pos_to_plane_pos(mouse_pos: Vector2) -> Vector3:
var camera_from = camera.project_ray_origin(mouse_pos)
var camera_to = camera.project_ray_normal(mouse_pos)
var n = Vector3(0, 1, 0) # plane normal
var p = camera_from
var v = camera_to
# distance from plane
var d = -2
var t = - (n.dot(p) + d) / n.dot(v)
return p + t * v
func plane_pos_to_tile_pos(plane_pos: Vector3) -> Vector2i:
return Vector2i(floor(plane_pos.x / tile_size), floor(plane_pos.z / tile_size))
func handle_tile_change(new_tile_map_pos: Vector2i, new_direction: Vector2):
var tile_changed = tile_map_pos != new_tile_map_pos
var direction_changed = direction != new_direction
# Ideally instead of this long method we can make all those
# cursors, etc different objects, and have tile_changed,
# direction_changed signal and have them react to that on their own.
if tile_changed:
if map_manager.enemy_locs.has(new_tile_map_pos):
update_enemy_info(map_manager.enemy_locs[new_tile_map_pos])
else:
clear_enemy_info()
if map_manager.treasure_locs.has(new_tile_map_pos):
var treasure = map_manager.treasure_locs[new_tile_map_pos]
var description = UnitCard.join_effects_text(active_character, treasure.def.effects)
treasure_info.text = "Treasure: %s (%d turns left)" % [description, treasure.turns_left]
else:
treasure_info.text = ""
if state == GameState.HUMAN_TURN:
if human_turn_state == HumanTurnState.WAITING:
calculate_path(new_tile_map_pos)
elif human_turn_state == HumanTurnState.PLAY_TELEPORTING:
single_cursor.update(new_tile_map_pos)
if tile_changed or direction_changed:
if state == GameState.HUMAN_TURN:
if human_turn_state == HumanTurnState.ACTION_TARGET:
update_target(new_tile_map_pos, new_direction)
if valid_target:
card_simulation_manager.update(active_character.get_id_position(), current_card, new_tile_map_pos, new_direction)
else:
card_simulation_manager.stop()
func update_position_direction(mouse_position: Vector2):
var plane_pos = mouse_pos_to_plane_pos(mouse_position)
var new_tile_map_pos = plane_pos_to_tile_pos(plane_pos)
var offset = plane_pos - active_character.get_position()
var new_direction = snap_to_direction(Vector2(offset.x, offset.z))
if new_tile_map_pos != tile_map_pos or new_direction != direction:
handle_tile_change(new_tile_map_pos, new_direction)
tile_map_pos = new_tile_map_pos
direction = new_direction
func _unhandled_input(event):
if state == GameState.HUMAN_TURN:
if state == HumanTurnState.MOVING or state == HumanTurnState.PLAYING_CARD:
return
if event is InputEventMouseButton:
var mouse_event = event as InputEventMouseButton
# left click
if mouse_event.button_index == 1 and mouse_event.pressed:
# move
if human_turn_state == HumanTurnState.WAITING:
handle_move()
elif human_turn_state == HumanTurnState.PLAY_TELEPORTING:
handle_teleport()
elif human_turn_state == HumanTurnState.ACTION_TARGET:
if valid_target:
await play_card()
elif event is InputEventMouseMotion:
update_position_direction(event.position)
func _on_undo_button_pressed():
apply_undo()
func get_save_state():
var combat_state = CombatSaveState.new()
combat_state.turn_number = turn_number
for enemy in enemies_node.get_children():
combat_state.enemies.push_back(enemy.get_save_state())
for treasure in treasures.get_children():
combat_state.treasures.push_back(treasure.get_save_state())
for loc in map_manager.door_locs:
var door = map_manager.door_locs[loc]
var door_def = DoorDef.create(loc, door.state, DoorDef.WallType.NORMAL)
combat_state.doors.push_back(door_def)
return combat_state
func can_save():
return state == GameState.HUMAN_TURN and human_turn_state == HumanTurnState.WAITING
# Invoked when abandoning run while this stage is on.
func cleanup():
StatsManager.remove_level(Enum.StatsLevel.TURN)