{***********************************************************

Project:    C-evo External Map Generator
Copyright:  1999-2024 P Blackman
License:    GPLv3+

Deadlands should be within a viable city site

***********************************************************}

function tMap.CheckDeadLand (const C : tTileptr; T : tTerrain; out DLW, DLH : Integer) : Boolean;
var N, W, H : Integer;
begin
    DLW := 0;
    DLH := 0;

    for N := 1 to 20 do
    begin
        GetCityNeighbour (C^.Wid, C^.Hgt, N, W, H);
        if (T = GetTerrain(W,H)) and (GetBonus (W,H) = Nothing) then
        begin
            DLW := W;
            DLH := H;
        end;
    end;

    result := DLW <> 0;
end;

procedure tMap.SetDeadTile(D,W,H : Integer);
Var DT : tSpecial;
begin
    case D of
        { can build a space ship with first three only }
        1,4,7:    DT := Cobalt;
        2,5,8:    DT := Uranium;
        3,6,9:    DT := Mercury;
      otherwise DT := DeadLands;
    end;

    SetTerrain (W, H, Desert, False);
    Tiles [W, H].Special := DT;
end;

procedure tMap.SetDeadLand (const C : tTileptr; Cn, D : Integer);
var W,H : Integer;
begin
    If CheckDeadLand (C, Desert, W, H) then
        SetDeadTile (D,W,H)
    else
    If CheckDeadLand (C, Arctic, W, H) then
        SetDeadTile (D,W,H)
    else
    If CheckDeadLand (C, Mountain, W, H) then
        SetDeadTile (D,W,H)
    else
    begin
        ShowMessage ('Logic error in DeadLands ' + IntToStr(Cn) + ' ' +IntToStr(D));
        Halt (1);
    end;
end;

procedure tMap.AllocateDeadLands;
var C,D : Integer;
    CitySite : tTileptr;
begin
    D := 0;

    // Start using sites right after the starting position sites
    C := NumStartPos;
    while (C < Citylist.Count) and (D < NumDeadlands)do
    begin
        CitySite := Citylist.Items[C];

        If CitySite^.DeadLand then
        begin
            inc (D);
            SetDeadLand (CitySite, C, D);
        end;
        inc (C);
    end;

    // If needed, use the player positions for the dead lands
    C := min (NumStartPos, Citylist.Count) -1;
    while (C >= 0) and (D < NumDeadlands)do
    begin
        CitySite := Citylist.Items[C];

        If CitySite^.DeadLand then
        begin
            inc (D);
            SetDeadLand (CitySite, C, D);
        end;
        dec (C);
    end;

    CityList.Pack;
end;
