sunder/scripts/multiplayer/team.gd
2026-02-18 18:33:17 -05:00

85 lines
2.6 KiB
GDScript

# This file is part of sunder.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
## This class defines a Team.
class_name Team extends RefCounted
## Emitted when the [Team] is renamed.
signal renamed(team_name: String)
## Emitted when a peer_id is added to the [Team].
signal player_added(team_name: String, peer_id: int, username: String)
## Emitted when a peer_id is erased from the [Team].
signal player_erased(team_name: String, peer_id: int)
var name : String:
set(new_name):
name = new_name
renamed.emit(name)
var players: Dictionary = {}
## Constructor.
func _init(team_name: String, team_players: Dictionary = {}) -> void:
name = team_name
for peer_id : int in team_players:
add(peer_id, team_players[peer_id])
# This is the iterator index cursor.
var _iter_cursor : int = 0
# This method is an iterator initializer.
func _iter_init(_arg : Variant) -> bool:
_iter_cursor = 0 # reset
print(_iter_cursor < players.size())
return _iter_cursor < players.size()
# This method checks if the iterator has a next value.
func _iter_next(_arg : Variant) -> bool:
_iter_cursor += 1
return _iter_cursor < players.size()
# This method gets the next iterator value.
func _iter_get(_arg : Variant) -> int:
return players.keys()[_iter_cursor]
## Add [param peer_id] to the [Team] if not already present.
func add(peer_id: int, username : String = "") -> void:
if peer_id not in players:
players[peer_id] = username
player_added.emit(name, peer_id, username)
## Erase [param peer_id] from the [Team].
func erase(peer_id: int) -> bool:
if players.erase(peer_id):
player_erased.emit(name, peer_id)
return true
return false
## This method pops out the related [param peer_id] string.
func pop(peer_id: int) -> String:
var value : String = players[peer_id]
erase(peer_id)
return value
## Returns the size of the team.
func size() -> int:
return players.size()
func serialize() -> Variant:
return [name, players]
func _to_string() -> String:
return "<Team(%s)#%s>" % [name, get_instance_id()]