Skip to content

Commit

Permalink
Moves block definitions to yaml finally
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkSuckerberg committed Oct 10, 2023
1 parent 05bc4c4 commit ec5df93
Show file tree
Hide file tree
Showing 65 changed files with 226 additions and 417 deletions.
45 changes: 45 additions & 0 deletions .idea/.idea.Blocktest/.idea/jsonSchemas.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion Blocktest.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/UserDictionary/Words/=Adjacencies/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Blocktest/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Pucestone/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Pykrete/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Renderable/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=renderables/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Smoothable/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Smoothable/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=tilemap_0027s/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
26 changes: 3 additions & 23 deletions Blocktest/Code/Block System/BlockSpritesManager.cs
Original file line number Diff line number Diff line change
@@ -1,32 +1,12 @@
using System.Linq;
using Shared.Code.Block_System;
namespace Blocktest.Block_System;

public sealed class BlockSpritesManager {
/// <summary> Array which stores all blocksprites instances for referencing as if they were globals. </summary>
private static BlockSprites[] _allBlocksSprites;

/// <summary> List used to store the names of blocks. The indexes are the corresponding block's ID. </summary>
private static string[] _blockSpriteNames;

/// <summary> Array which stores all blocksprites instances for referencing as if they were globals. </summary>
public static BlockSprites[] AllBlocksSprites {
get => _allBlocksSprites;
private set => _allBlocksSprites = value;
}
/// <summary> List used to store the names of blocks. The indexes are the corresponding block's ID. </summary>
public static string[] BlockSpriteNames {
get => _blockSpriteNames;
private set => _blockSpriteNames = value;
}
public static Dictionary<string, BlockSprites> AllBlocksSprites { get; private set; }

Check warning on line 7 in Blocktest/Code/Block System/BlockSpritesManager.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'AllBlocksSprites' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

public static void LoadBlockSprites() {
AllBlocksSprites = new BlockSprites[BlockManagerShared.AllBlocks.Length];
BlockSpriteNames = new string[BlockManagerShared.AllBlocks.Length];

foreach (BlockShared block in BlockManagerShared.AllBlocks) {
BlockSprites newBlockSprites = new(block);
BlockSpriteNames[block.BlockId] = block.BlockName;
AllBlocksSprites[block.BlockId] = newBlockSprites;
}
AllBlocksSprites = BlockManagerShared.AllBlocks.ToDictionary(uid => uid.Key, block => new BlockSprites(block.Value));
}
}
6 changes: 3 additions & 3 deletions Blocktest/Code/Block System/RenderableTile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class RenderableTile : TileShared {
public RenderableTile(TileShared tile, bool background) : base(tile.SourceBlock,
tile.Transform.Position / GlobalsShared.GridSize) {
Renderable = new Renderable(Transform, background ? Layer.BackgroundBlocks : Layer.ForegroundBlocks,
BlockSpritesManager.AllBlocksSprites[tile.SourceBlock.BlockId].BlockSprite, tile.Color);
BlockSpritesManager.AllBlocksSprites[tile.SourceBlock.BlockUid].BlockSprite, tile.Color);
}

/// <summary>
Expand Down Expand Up @@ -38,7 +38,7 @@ public void UpdateAdjacencies(Vector2Int position, TilemapShared tilemap) {
bitmask += 8;
}

Renderable.Appearance = BlockSpritesManager.AllBlocksSprites[SourceBlock.BlockId].SpriteSheet
Renderable.Appearance = BlockSpritesManager.AllBlocksSprites[SourceBlock.BlockUid].SpriteSheet
.OrderedSprites[bitmask];
}

Expand All @@ -52,7 +52,7 @@ private bool HasSmoothableTile(Vector2Int position, TilemapShared tilemap) {
if (tilemap.TryGetTile(position, out TileShared? tile)) {
return SourceBlock.SmoothSelf
? IsSameTileType(tile)
: tile.SourceBlock.BlockId != 0; // Don't smooth with air, possibly find nicer way to do this later.
: tile.SourceBlock.BlockUid != "air"; // Don't smooth with air, possibly find nicer way to do this later.
}
return false;
}
Expand Down
6 changes: 2 additions & 4 deletions Blocktest/Code/Block System/RenderableTilemap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,9 @@ public RenderableTilemap(TilemapShared newTilemap, Camera camera) {
private void OnTilemapChanged(TileShared tile, Vector2Int location) {
_camera.RenderedComponents.Remove(_renderables[location.X, location.Y].Renderable);


foreach (Vector2Int dir in Adjacencies) {
if (location.X + dir.X < 0 ||
location.X + dir.X >= _tilemap.TilemapSize.X ||
location.Y + dir.Y < 0 ||
location.Y + dir.Y >= _tilemap.TilemapSize.Y) {
if (!_tilemap.TryGetTile(location + dir, out TileShared? adjacentTile)) {
continue;
}
_renderables[location.X + dir.X, location.Y + dir.Y].UpdateAdjacencies(location + dir, _tilemap);
Expand Down
26 changes: 8 additions & 18 deletions Blocktest/Code/Scenes/GameScene.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Linq;
using Blocktest.Block_System;
using Blocktest.Misc;
using Blocktest.Networking;
Expand All @@ -15,6 +16,7 @@ public sealed class GameScene : IScene {
private readonly Client _networkingClient;
private readonly SpriteBatch _spriteBatch;
private int _blockSelected = 1; //ID of the block to place
private string[] _blockStrings;

private readonly RenderableTilemap _backgroundTilemapSprites;
private readonly RenderableTilemap _foregroundTilemapSprites;
Expand All @@ -28,7 +30,6 @@ public sealed class GameScene : IScene {
public GameScene(BlocktestGame game, bool doConnect, string? ip) {
_connect = doConnect;
_spriteBatch = new SpriteBatch(game.GraphicsDevice);
game.Content.Load<SpriteFont>("Fonts/OpenSans");
_game = game;

_camera = new Camera(Vector2.Zero, new Vector2(512, 256), game.GraphicsDevice);
Expand All @@ -38,27 +39,16 @@ public GameScene(BlocktestGame game, bool doConnect, string? ip) {
_backgroundTilemapSprites = new RenderableTilemap(GlobalsShared.BackgroundTilemap, _camera);
_foregroundTilemapSprites = new RenderableTilemap(GlobalsShared.ForegroundTilemap, _camera);
_networkingClient = new Client();


_blockStrings = BlockManagerShared.AllBlocks.Keys.ToArray();

if (_connect && ip != null) {
_networkingClient.Start(ip, 9050, "testKey");
return;
}

WorldDownload testDownload = new();

int[,,] newWorld = new int[GlobalsShared.MaxX, GlobalsShared.MaxY, 2];
for (int i = 0; i < GlobalsShared.MaxX; i++) {
newWorld[i, 0, 1] = 4;
newWorld[i, 1, 1] = 2;
newWorld[i, 2, 1] = 2;
newWorld[i, 3, 1] = 2;
newWorld[i, 4, 1] = 2;
newWorld[i, 5, 1] = 3;
}
testDownload.World = newWorld;
testDownload.TickNum = 1;
var testDownload = WorldDownload.Default();
testDownload.Process();

}

public void Update(GameTime gameTime) {
Expand Down Expand Up @@ -90,7 +80,7 @@ public void Update(GameTime gameTime) {
if (currentKeyboardState.IsKeyDown(Keys.Q) &&
_previousKeyboardState.IsKeyUp(Keys.Q)) {
_blockSelected++;
if (_blockSelected >= BlockManagerShared.AllBlocks.Length) {
if (_blockSelected >= BlockManagerShared.AllBlocks.Count) {
_blockSelected = 1;
}
}
Expand Down Expand Up @@ -131,7 +121,7 @@ public void Update(GameTime gameTime) {
TickNum = _networkingClient.ClientTickBuffer.CurrTick,
Position = tilePos,
Foreground = foreground,
BlockId = _blockSelected
BlockUid = _blockStrings[_blockSelected]
};

_networkingClient.ClientTickBuffer.AddPacket(testChange);
Expand Down
8 changes: 7 additions & 1 deletion Blocktest/packages.lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,17 @@
"resolved": "2.2.0",
"contentHash": "u06nYzGcXCBcnF7cRe8Xa0KxBxGx8grhujZmb3PUiMVbds8d/I6qJ+waGn0IeC7Tdwmt0P6l3v7MqdYog5rJQg=="
},
"YamlDotNet": {
"type": "Transitive",
"resolved": "13.7.0",
"contentHash": "RKkoQSCyk/94N20SL3U15hWAqBVXHu+59upcPi8R2uhrcAalyVa4Y/vYdXQ7MXQ71Lut//DH0tLcYByAkGmXhA=="
},
"shared": {
"type": "Project",
"dependencies": {
"LiteNetLib": "[1.1.0, )",
"MonoGame.Framework.DesktopGL": "[3.8.1.303, )"
"MonoGame.Framework.DesktopGL": "[3.8.1.303, )",
"YamlDotNet": "[13.7.0, )"
}
}
}
Expand Down
17 changes: 2 additions & 15 deletions DedicatedServer/Code/WorldHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,8 @@ public WorldHandler() {
BlockManagerShared.Initialize();
GlobalsShared.BackgroundTilemap = new TilemapShared(GlobalsShared.MaxX, GlobalsShared.MaxY, true);
GlobalsShared.ForegroundTilemap = new TilemapShared(GlobalsShared.MaxX, GlobalsShared.MaxY, false);


int[,,] newWorld = new int[GlobalsShared.MaxX, GlobalsShared.MaxY, 2];
for (int i = 0; i < GlobalsShared.MaxX; i++) {
newWorld[i, 0, 1] = 4;
newWorld[i, 1, 1] = 2;
newWorld[i, 2, 1] = 2;
newWorld[i, 3, 1] = 2;
newWorld[i, 4, 1] = 2;
newWorld[i, 5, 1] = 3;
}
WorldDownload testDownload = new() {
World = newWorld,
TickNum = 1
};

var testDownload = WorldDownload.Default();
testDownload.Process();

_server = new Server();
Expand Down
72 changes: 25 additions & 47 deletions Shared/Code/Block System/BlockManagerShared.cs
Original file line number Diff line number Diff line change
@@ -1,66 +1,44 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using YamlDotNet.Serialization;

namespace Shared.Code.Block_System;

/// <summary>
/// The BlockManager contains all of the block types in <see cref="AllBlocks">an array of blocks</see> and a
/// <see cref="BlockNames">list of block names.</see>
/// The BlockManager contains all of the block types in <see cref="AllBlocks">a dictionary of blocks indexed by their name</see>
/// </summary>
public abstract class BlockManagerShared {
/// <summary> Array which stores all block instances for referencing as if they were globals. </summary>
private static BlockShared[] _allBlocks;


/// <summary> List used to store the names of blocks. The indexes are the corresponding block's ID. </summary>
private static string[] _blockNames;

/// <summary> Array which stores all block instances for referencing as if they were globals. </summary>
public static BlockShared[] AllBlocks {
get => _allBlocks;
private set => _allBlocks = value;
}

/// <summary> List used to store the names of blocks. The indexes are the corresponding block's ID. </summary>
public static string[] BlockNames {
get => _blockNames;
private set => _blockNames = value;
}
public static Dictionary<string, BlockShared> AllBlocks { get; private set; }

Check warning on line 13 in Shared/Code/Block System/BlockManagerShared.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable property 'AllBlocks' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.


/// <summary>
/// Compiles all block subtypes into <see cref="AllBlocks">an array of blocks</see> and a
/// <see cref="BlockNames">list of block names.</see>
/// Compiles all block subtypes into <see cref="AllBlocks">a dictionary of blocks indexed by their name</see>
/// </summary>
public static void Initialize() {
// This mess gets all subtypes of Block and puts the types in a list.
Type[] allBlockTypes = (
from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
from assemblyType in domainAssembly.GetTypes()
where assemblyType.IsSubclassOf(typeof(BlockShared))
select assemblyType).ToArray();

AllBlocks = new BlockShared[allBlockTypes.Length];
BlockNames = new string[allBlockTypes.Length];

// For loops to populate main allBlocks array.
for (int i = 0; i < allBlockTypes.Length; i++) {
Type newBlockType = allBlockTypes[i];
BlockShared? newBlock = (BlockShared?)Activator.CreateInstance(newBlockType);
if (newBlock == null) {
Console.WriteLine($"Failed to create instance of {newBlockType}!");
var deserialize = new DeserializerBuilder().Build();
var assembly = typeof(BlockManagerShared).Assembly;
var assemblyNames = assembly.GetManifestResourceNames();
var blockNames = assemblyNames.Where(x => x.StartsWith("Shared.Content.Blocks."));

AllBlocks = new Dictionary<string, BlockShared>();
foreach (string resourceName in blockNames) {
using var stream = assembly.GetManifestResourceStream(resourceName);
if (stream == null) {
continue;
}
newBlock.Initialize();
if (newBlock.BlockId == -1) {
newBlock.BlockId = i;
using StreamReader reader = new(stream);
string yaml = reader.ReadToEnd();
var block = deserialize.Deserialize<BlockShared?>(yaml);
if (block == null) {
continue;
}
if (AllBlocks[newBlock.BlockId] != null) {
Console.WriteLine(
$"Block {newBlock} conflicts with block {AllBlocks[newBlock.BlockId]}! (Block ID: {newBlock.BlockId})");
} else if (newBlock.BlockId > AllBlocks.Length || newBlock.BlockId < 0) {
Console.WriteLine($"Block {newBlock} has invalid ID {newBlock.BlockId}! (Max ID {AllBlocks.Length})");
block.BlockUid = block.BlockName.ToLower().Replace(" ", "_");

if (!AllBlocks.TryAdd(block.BlockUid, block)) {
Console.WriteLine($"File {resourceName} contains duplicate definition of block {block.BlockName}!");
}
BlockNames[newBlock.BlockId] = newBlock.BlockName;
AllBlocks[newBlock.BlockId] = newBlock;
}
}
}
18 changes: 7 additions & 11 deletions Shared/Code/Block System/BlockShared.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ namespace Shared.Code.Block_System;
/// Each block is a different type of tile which can be placed. The behaviours specified in each block class subtype
/// will be used for every tile of that type.
/// </summary>
public abstract class BlockShared {
/// <summary> The block's ID (index in the allblocks list). </summary>
/// <remarks> Leave as -1 for automatic assignment based on init order (probably not a good idea) </remarks>
public int BlockId = -1;
public sealed class BlockShared {
/// <summary>
/// The block's unique string ID, generated from the name without spaces and turned to lowercase.
/// </summary>
public string BlockUid = "error";

/// <summary> The block's name. </summary>
public string BlockName = "Error";
Expand All @@ -24,24 +25,19 @@ public abstract class BlockShared {

/* METHODS */

/// <summary>
/// Called whenever a block is first loaded by the block manager.
/// </summary>
public virtual void Initialize() { }

/// <summary>
/// Called whenever a block is placed.
/// </summary>
/// <param name="position">The position of the block being placed.</param>
/// <param name="foreground">Whether the block being placed is in the foreground or not.</param>
public virtual void OnPlace(Vector2Int position, bool foreground) { }
public void OnPlace(Vector2Int position, bool foreground) { }

/// <summary>
/// Called whenever a block is broken.
/// </summary>
/// <param name="position">The position of the block being broken.</param>
/// <param name="foreground">Whether the block being broken is in the foreground or not.</param>
public virtual void OnBreak(Vector2Int position, bool foreground) { }
public void OnBreak(Vector2Int position, bool foreground) { }

/// <inheritdoc />
public override string ToString() => BlockName;
Expand Down
Loading

0 comments on commit ec5df93

Please sign in to comment.