TinyAdventure/ui/item_slot.gd

118 lines
2.7 KiB
GDScript

class_name ItemSlot
extends Panel
signal mouse_entered_slot
signal mouse_left_pressed
enum {
ALLOW_DRAG = 1,
ALLOW_DROP = 2
}
@onready var select_panel = %SelectPanel
@onready var highlight_panel = %HighlightPanel
@onready var texture_rect:TextureRect = %TextureRect
@onready var count_label = %CountLabel
var drag_drop_flags:int = 0
var _item_stack:ItemStack = null
var highlighted:bool = false : set = _set_highlighted
var selected:bool = false : set = _set_selected
func _set_highlighted(new_state):
highlight_panel.visible = new_state
func _set_selected(new_state):
select_panel.visible = new_state
func set_drag_drop_flags(flags:int) -> void:
drag_drop_flags = flags
func get_item() -> Item:
if _item_stack == null:
return null
return _item_stack.item
func display(item_stack):
_item_stack = item_stack
func _process(_delta)->void:
if _item_stack == null:
return
theme_type_variation = "PanelHighlighted"
if _item_stack.count == 0:
texture_rect.texture = null
update_quantity_text(0)
else:
texture_rect.texture = _item_stack.item.icon
update_quantity_text(_item_stack.count)
func update_quantity_text(stack_size) -> void:
if stack_size <= 1:
count_label.hide()
else:
count_label.text = str(stack_size)
count_label.show()
func _get_drag_data(_at_position:Vector2)->Variant:
if drag_drop_flags & ALLOW_DRAG == 0:
return null
if _item_stack == null:
return null
var drag_data:ItemDrag = ItemDrag.new(self, self)
var drag_preview = load("res://ui/item_slot.tscn").instantiate()
var drag_stack = ItemStack.new()
drag_stack.item = _item_stack.item
drag_stack.count = _item_stack.count
drag_preview.display(drag_stack)
set_drag_preview(drag_preview)
return drag_data
func _can_drop_data(_at_position:Vector2, data:Variant)->bool:
if drag_drop_flags & ALLOW_DROP == 0:
return false
if !data is ItemDrag:
return false
return _item_stack.count == 0
func _drop_data(_at_position:Vector2, data:Variant)->void:
if drag_drop_flags & ALLOW_DROP == 0:
return
if !data is ItemDrag:
return
var drag_data := data as ItemDrag
drag_data.destination = self
if drag_data.source is ItemSlot:
var source_slot := drag_data.source as ItemSlot
# add stuff to the destination
self._item_stack.item = source_slot._item_stack.item
self._item_stack.count = source_slot._item_stack.count
# remove it from the source
source_slot._item_stack.count = 0
func _on_mouse_entered():
emit_signal("mouse_entered_slot", self)
func _on_gui_input(event):
var mouse_button_event = event as InputEventMouseButton
if mouse_button_event and mouse_button_event.button_index == MOUSE_BUTTON_LEFT and mouse_button_event.pressed:
emit_signal("mouse_left_pressed", self)