Skip to content

Commit 9aae4e3

Browse files
committed
feat: add swap animation
1 parent e3e4609 commit 9aae4e3

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

models/array_model.gd

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
class_name ArrayModel
22
extends Reference
33

4+
signal swapped(i, j) # where i <= j
5+
46
var array = []
57
var size = 0
68

@@ -27,6 +29,7 @@ func swap(i, j):
2729
var temp = array[i]
2830
array[i] = array[j]
2931
array[j] = temp
32+
emit_signal("swapped", min(i, j), max(i, j))
3033

3134
func sort(i, j):
3235
"""Sort the subarray starting at i and up to but not including j."""

views/array_view.gd

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,27 @@ Visualization of an array as rectangles of varying heights.
55
class_name ArrayView
66
extends HBoxContainer
77

8+
const SWAP_DURATION = 0.1
9+
const TRANS_TYPE = Tween.TRANS_LINEAR
10+
const EASE_TYPE = Tween.EASE_IN_OUT
11+
12+
var _tween = Tween.new()
813
var _level: ComparisonSort
914
var _rects = []
1015

1116
func _init(level):
1217
"""Add colored rectangles."""
1318
_level = level
1419
_level.connect("mistake", self, "_on_Level_mistake")
20+
_level.array.connect("swapped", self, "_on_ArrayModel_swapped")
1521
add_child(_level) # NOTE: This is necessary for it to read input
1622
for i in range(level.array.size):
1723
var rect = ColorRect.new()
1824
rect.size_flags_horizontal = Control.SIZE_EXPAND_FILL
1925
rect.size_flags_vertical = Control.SIZE_SHRINK_END
2026
_rects.append(rect)
2127
add_child(rect)
28+
add_child(_tween) # NOTE: This is necessary for it to animate
2229

2330
func _process(delta):
2431
"""Update heights of rectangles based on array values."""
@@ -30,3 +37,14 @@ func _process(delta):
3037
func _on_Level_mistake():
3138
"""Flash the border red on mistakes."""
3239
get_parent().flash()
40+
41+
func _on_ArrayModel_swapped(i, j):
42+
"""Produce a swapping animation."""
43+
_tween.interpolate_property(_rects[i], "rect_position",
44+
null, _rects[j].rect_position, SWAP_DURATION, TRANS_TYPE, EASE_TYPE)
45+
_tween.interpolate_property(_rects[j], "rect_position",
46+
null, _rects[i].rect_position, SWAP_DURATION, TRANS_TYPE, EASE_TYPE)
47+
var temp = _rects[i]
48+
_rects[i] = _rects[j]
49+
_rects[j] = temp
50+
_tween.start()

0 commit comments

Comments
 (0)