Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
global using Godot;
global using DungeonRoyale.Shared.Scripts;
global using DungeonRoyale.Shared.Scripts.Extensions;
8 changes: 8 additions & 0 deletions Modules/Game/Resources/mapSettings.tres
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[gd_resource type="Resource" load_steps=2 format=3 uid="uid://cslplb3s5se2m"]

[ext_resource type="Script" uid="uid://c2q15i1u3gl3y" path="res://Modules/Map/Scripts/MapSettingsResource.cs" id="1_bcgwb"]

[resource]
script = ExtResource("1_bcgwb")
Width = 500
Height = 500
32 changes: 21 additions & 11 deletions Modules/Game/Scenes/Game.tscn

Large diffs are not rendered by default.

41 changes: 41 additions & 0 deletions Modules/Game/Scripts/Game.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using DungeonRoyale.Modules.GameManagers.Scripts;
using DungeonRoyale.Modules.Map.Scripts;

namespace DungeonRoyale.Modules.Game.Scripts;

public partial class Game : Node2D
{
private static TilesManager _tilesManager => TilesManager.Instance!;

[Export] public MapSettingsResource MapSettings { get; private set; } = new MapSettingsResource();

private bool MapIsLoading { get; set; } = true;

public override void _Ready()
{
_tilesManager.SetUpTiles(MapSettings.Width, MapSettings.Height);

if (FindChild(nameof(MapScanner), true) is not MapScanner mapScanner)
{
GD.PrintErr("MapScanner node not found.");
return;
}

mapScanner.MapScanned += OnMapScanned;
mapScanner.Scan(MapSettings.Width, MapSettings.Height);
}

public void OnMapScanned()
{
MapIsLoading = false;

// Do something with the scanned map
}

public void OnMapGenerated()
{
MapIsLoading = false;

// Do something with the generated map
}
}
1 change: 1 addition & 0 deletions Modules/Game/Scripts/Game.cs.uid
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
uid://doeo50prutum0
40 changes: 40 additions & 0 deletions Modules/GameManagers/Scripts/TileMapManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
namespace DungeonRoyale.Modules.GameManagers.Scripts;

public partial class TileMapManager : Node2D
{
public static TileMapManager? Instance { get; private set; }

public TileMapLayer GroundTileMap { get; private set; } = null!;
public TileMapLayer SpawnTileMap { get; private set; } = null!;

public override void _Ready()
{
if (Instance is null)
{
Instance = this;
}
else
{
GD.PrintErr("There is already an instance of TileMapManager in the scene.");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sugestão (risco_de_bug): Considere lançar exceções para falhas de inicialização em vez de apenas registrar erros

Quando o gerenciador não pode ser inicializado corretamente (instância duplicada ou TileMaps necessários ausentes), o tratamento de erro atual permite que continue em um estado inválido. Isso pode levar a exceções de referência nula posteriormente.

Implementação sugerida:

public class TileMapManagerInitializationException : Exception
{
    public TileMapManagerInitializationException(string message) : base(message) { }
}

public partial class TileMapManager : Node2D
{
    public static TileMapManager? Instance { get; private set; }
        if (Instance is not null)
        {
            throw new TileMapManagerInitializationException("Já existe uma instância de TileMapManager na cena.");
        }

        Instance = this;

O desenvolvedor precisará:

  1. Adicionar tratamento de erro onde o TileMapManager é instanciado para capturar a nova TileMapManagerInitializationException
  2. Adicionar de forma semelhante o lançamento e tratamento de exceções para o caso em que os TileMaps necessários estão ausentes (não mostrado no código fornecido)
  3. Atualizar quaisquer testes de unidade para esperar exceções em vez de erros registrados
Original comment in English

suggestion (bug_risk): Consider throwing exceptions for initialization failures instead of just logging errors

When the manager can't be properly initialized (duplicate instance or missing required TileMaps), the current error handling allows it to continue in an invalid state. This could lead to null reference exceptions later.

Suggested implementation:

public class TileMapManagerInitializationException : Exception
{
    public TileMapManagerInitializationException(string message) : base(message) { }
}

public partial class TileMapManager : Node2D
{
    public static TileMapManager? Instance { get; private set; }
        if (Instance is not null)
        {
            throw new TileMapManagerInitializationException("There is already an instance of TileMapManager in the scene.");
        }

        Instance = this;

The developer will need to:

  1. Add error handling where TileMapManager is instantiated to catch the new TileMapManagerInitializationException
  2. Similarly add exception throwing and handling for the case where required TileMaps are missing (not shown in the provided code)
  3. Update any unit tests to expect exceptions rather than logged errors

}

var tileMapLayers = this.GetRecursivelyNodesOfType<TileMapLayer>();

foreach (var tileMapLayer in tileMapLayers)
{
if (tileMapLayer.Name == nameof(GroundTileMap))
{
GroundTileMap = tileMapLayer;
}
else if (tileMapLayer.Name == nameof(SpawnTileMap))
{
SpawnTileMap = tileMapLayer;
}
}

if (GroundTileMap is null || SpawnTileMap is null)
{
GD.PrintErr("TileMapLayers not found.");
}
}
}
1 change: 1 addition & 0 deletions Modules/GameManagers/Scripts/TileMapManager.cs.uid
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
uid://bt46ejg3cyafl
6 changes: 6 additions & 0 deletions Modules/GameManagers/Scripts/TilesManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ public void SetUpTiles(int width, int height)
_height = height;

Tiles = new DRTileData[_width, _height];

for (int x = 0; x < _width; x++)
for (int y = 0; y < _height; y++)
{
Tiles[x, y] = new DRTileData(x, y);
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
Expand Down
39 changes: 39 additions & 0 deletions Modules/Map/Scripts/MapScanner.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using DungeonRoyale.Modules.GameManagers.Scripts;

namespace DungeonRoyale.Modules.Map.Scripts;

public partial class MapScanner : Node2D
{
private TileMapManager _tileMapManager => TileMapManager.Instance!;
private TilesManager _tilesManager => TilesManager.Instance!;

[Signal] public delegate void MapScannedEventHandler();

public void Scan(int width, int height)
{
GD.Print("Scanning map...");
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
{
var groundTile = _tileMapManager.GroundTileMap.GetCellTileData(new Vector2I(x, y));

if (groundTile is null)
continue;

if (!_tilesManager.TryGetTileAt(x, y, out var tileData))
continue;

tileData.IsWalkable = groundTile.GetCustomData("IsWalkable").AsBool();

var spawnTile = _tileMapManager.SpawnTileMap.GetCellTileData(new Vector2I(x, y));

if (spawnTile is null)
continue;

tileData.IsSpawnPoint = true;
}

GD.Print("Map scanned.");
EmitSignal(SignalName.MapScanned);
}
}
1 change: 1 addition & 0 deletions Modules/Map/Scripts/MapScanner.cs.uid
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
uid://di6j7dxqlb03e
7 changes: 7 additions & 0 deletions Modules/Map/Scripts/MapSettingsResource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace DungeonRoyale.Modules.Map.Scripts;

public partial class MapSettingsResource : Resource
{
[Export] public int Width { get; private set; } = 100;
[Export] public int Height { get; private set; } = 100;
}
1 change: 1 addition & 0 deletions Modules/Map/Scripts/MapSettingsResource.cs.uid
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
uid://c2q15i1u3gl3y
4 changes: 2 additions & 2 deletions Modules/Tiles/Scripts/DRTileData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ public partial class DRTileData
public int X { get; private set; }
public int Y { get; private set; }

public bool IsWalkable { get; private set; }
public bool IsWalkable { get; set; }

public bool IsSpawnPoint { get; private set; }
public bool IsSpawnPoint { get; set; }

public DRTileData()
{
Expand Down
26 changes: 26 additions & 0 deletions Shared/Scripts/Extensions/NodeExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System.Collections.Generic;

namespace DungeonRoyale.Shared.Scripts.Extensions;

public static class NodeExtensions
{
public static List<T> GetRecursivelyNodesOfType<T>(this Node node, List<T>? nodesList = null) where T : Node
{
nodesList ??= [];

foreach (Node child in node.GetChildren())
{
if (child is T t)
{
nodesList.Add(t);
}

if (child.GetChildCount() > 0)
{
child.GetRecursivelyNodesOfType(nodesList);
}
}

return nodesList;
}
}
Loading