Skip to content

Instantly share code, notes, and snippets.

@Lanse505
Last active January 9, 2022 11:38
Show Gist options
  • Save Lanse505/606c22225d2445efba192baaea6e573b to your computer and use it in GitHub Desktop.
Save Lanse505/606c22225d2445efba192baaea6e573b to your computer and use it in GitHub Desktop.
Please enter the target directory for the save: F:\Högskolan\Test
Please enter the name of the Save File: test
Unhandled exception. System.InvalidOperationException: Cannot write a JSON property within an array or as the first JSON token. Current token type is 'None'.
at System.Text.Json.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource, Int32 currentDepth, Byte token, JsonTokenType tokenType)
at System.Text.Json.Utf8JsonWriter.WriteStartByOptions(ReadOnlySpan`1 propertyName, Byte token)
at System.Text.Json.Utf8JsonWriter.WriteStartEscape(ReadOnlySpan`1 propertyName, Byte token)
at System.Text.Json.Utf8JsonWriter.WriteStartObject(ReadOnlySpan`1 propertyName)
at System.Text.Json.Utf8JsonWriter.WriteStartObject(String propertyName)
at GroupAssignment.serialization.PlayerStateConverter.Write(Utf8JsonWriter writer, Player value, JsonSerializerOptions options) in F:\RiderProjects\GroupAssignment\GroupAssignment\serialization\PlayerStateConverter.cs:line 24
at GroupAssignment.serialization.GameEngineStateSerializer.Write(Utf8JsonWriter writer, GameEngine value, JsonSerializerOptions options) in F:\RiderProjects\GroupAssignment\GroupAssignment\serialization\GameEngineStateConverte
r.cs:line 32
at GroupAssignment.GameEngine.SaveGame() in F:\RiderProjects\GroupAssignment\GroupAssignment\GameEngine.cs:line 194
at GroupAssignment.GameEngine.RunGame() in F:\RiderProjects\GroupAssignment\GroupAssignment\GameEngine.cs:line 85
at GroupAssignment.menu.NewGameMenu.RunProgram() in F:\RiderProjects\GroupAssignment\GroupAssignment\menu\NewGameMenu.cs:line 22
at GroupAssignment.Program.Main(String[] args) in F:\RiderProjects\GroupAssignment\GroupAssignment\Program.cs:line 24
Process finished with exit code -532,462,766.
using System;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using GroupAssignment.dungeon;
using GroupAssignment.dungeon.room;
using GroupAssignment.entity.player;
using GroupAssignment.serialization;
namespace GroupAssignment
{
public class GameEngine
{
private readonly Player _player;
private readonly Dungeon _dungeon;
private readonly Random _random;
private bool _lostGame = false;
private bool _wonGame = false;
public GameEngine(Player player)
{
_player = player;
_dungeon = new Dungeon();
_random = new Random(player.GetHashCode());
}
public GameEngine(Player player, Dungeon dungeon, bool hasWon, bool hasLost)
{
_player = player;
_dungeon = dungeon;
_random = new Random(player.GetHashCode());
_wonGame = hasWon;
_lostGame = hasLost;
}
public void RunGame()
{
Console.Clear();
Console.WriteLine("Welcome to your adventure!");
Console.WriteLine("You find yourself waking up in an unfamiliar place.");
Console.WriteLine("The damp air is almost nauseating, you look around to get your bearings.");
Console.WriteLine("You stand-up and try to get your bearings");
Console.WriteLine("[These are the valid options: ]");
Console.WriteLine("['go up', 'go down', 'go left', 'go right', 'exit', 'save_game']");
var firstRun = true;
for (;;)
{
if (_wonGame)
{
Console.Clear();
Console.WriteLine("Congratulations!");
Console.WriteLine("You have won the game!");
Console.WriteLine($"You successfully survived the adventure with {_player.GetPoints()} points!");
Console.WriteLine("Now see if you can beat your high-score!");
Console.ReadLine();
break;
}
if (_lostGame)
{
Console.Clear();
Console.WriteLine("Congratulations!");
Console.WriteLine("You have died!");
Console.WriteLine($"You didn't survive the adventure this time, and you died with {_player.GetPoints()} points!");
Console.WriteLine("Now see if you can beat your high-score and actually survive!");
Console.ReadLine();
}
if (!firstRun)
{
Console.WriteLine("['go up', 'go down', 'go left', 'go right', 'exit', 'save_game']");
}
Console.Write("What do you do?: ");
firstRun = false;
var input = Util.ReadLine<string>();
while (input == null)
{
Console.WriteLine("Error: Invalid Input");
Console.Write("What do you do?: ");
input = Util.ReadLine<string>();
}
if (input.Equals("exit")) break;
if (input.Equals("save_game")) SaveGame();
EnterRoom(_player.Movement(input, out _wonGame), out input);
}
}
private void EnterRoom(bool success, out string? input)
{
if (success)
{
Console.Clear();
Console.WriteLine($"You entered room [X:{_player.GetPosition().x + 1}, Y:{_player.GetPosition().y + 1}]");
Room room = _dungeon.GetRoom(_player.GetPosition().x, _player.GetPosition().y);
StringBuilder builder = new();
if (room.GetRoomMonsters() > 0)
{
builder.Append($"You enter a new room, inside you encounter {room.GetRoomMonsters()} monsters");
if (room.HasKey())
{
builder.Append(", You also see a key in the distance");
}
Console.WriteLine(builder.ToString());
Console.WriteLine($"The 1st out of {room.GetRoomMonsters()} approaches you");
Console.WriteLine("[Possible Options: attack, flee]");
Console.Write("What would you like to do?: ");
var option = Util.ReadLine<string>();
while (option == null)
{
Console.WriteLine("Error: Invalid Input");
Console.WriteLine("[Possible Options: attack, flee]");
Console.Write("What would you like to do?: ");
option = Util.ReadLine<string>();
}
switch (option)
{
case "attack":
_lostGame = Attack(_random, _player, room, out _wonGame);
break;
case "flee":
_player.FleePosition();
break;
}
}
}
input = null;
}
private static bool Attack(Random random, Player player, Room room, out bool wonGame)
{
Console.Clear();
Console.WriteLine("You enter Combat with the " + (room.GetRoomMonsters() > 1 ? "beasts." : "beast."));
var monstersInRoom = room.GetRoomMonsters();
var died = false;
for (var i = 0; i < monstersInRoom; i++)
{
Console.WriteLine();
Console.WriteLine($"You lunge at beast {i + 1}");
Console.WriteLine("The beast lets off a load groan and collapses defeated");
room.KillMonster(player);
if (random.Next(0, 5) != 0) continue;
Console.WriteLine("With a final burst of strength, the beast slashes you across the chest.");
died = player.TakeDamage();
Console.WriteLine($"10 Damage dealt to Player, Current Health: {player.GetLife()}");
Console.WriteLine();
}
if (room.HasKey())
{
Console.WriteLine("You gained a key!");
player.GainKey(out wonGame);
Console.WriteLine($"You now have {player.GetKeys()} keys!");
Console.WriteLine();
return died;
}
Console.WriteLine();
wonGame = false;
return died;
}
public void SaveGame()
{
Console.Clear();
Console.Write("Please enter the target directory for the save: ");
var target = Util.ReadLine<string>();
while (target == null)
{
Console.WriteLine("Error: Invalid string input");
Console.Write("Please enter the target directory for the save: ");
target = Util.ReadLine<string>();
}
Console.WriteLine();
Console.Write("Please enter the name of the Save File: ");
var name = Util.ReadLine<string>();
while (name == null)
{
Console.WriteLine("Error: Invalid string name");
Console.Write("Please enter the name of the Save File: ");
name = Util.ReadLine<string>();
}
string filePath = Path.Combine(target, name);
string file = filePath + ".json";
if (File.Exists(filePath))
File.Delete(filePath);
using var stream = new MemoryStream();
using var jsonWriter = new Utf8JsonWriter(stream, JsonOptions.INSTANCE.GetWriterOptions);
using var sw = new StreamWriter(file);
JsonConverter<GameEngine> serializer = new GameEngineStateSerializer();
serializer.Write(jsonWriter, this, JsonOptions.INSTANCE.GetSerializerOptions);
sw.Write(jsonWriter.ToString());
}
public Player GetPlayer => _player;
public Dungeon GetDungeon => _dungeon;
public bool HasWon => _wonGame;
public bool HasLost => _lostGame;
}
}
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using GroupAssignment.dungeon;
using GroupAssignment.entity.player;
namespace GroupAssignment.serialization
{
public class GameEngineStateSerializer : JsonConverter<GameEngine>
{
public override GameEngine? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
JsonConverter<Player> playerStateConverter = new PlayerStateConverter();
JsonConverter<Dungeon> dungeonStateConverter = new DungeonStateConverter();
Player? player = playerStateConverter.Read(ref reader, typeToConvert, options);
Dungeon? dungeon = dungeonStateConverter.Read(ref reader, typeToConvert, options);
bool hasWon = reader.GetBoolean();
bool hasLost = reader.GetBoolean();
return new GameEngine(player, dungeon, hasWon, hasLost);
}
public override void Write(Utf8JsonWriter writer, GameEngine value, JsonSerializerOptions options)
{
JsonConverter<Player> playerStateConverter = new PlayerStateConverter();
JsonConverter<Dungeon> dungeonStateConverter = new DungeonStateConverter();
Player player = value.GetPlayer;
Dungeon dungeon = value.GetDungeon;
var hasWon = value.HasWon;
var hasLost = value.HasLost;
playerStateConverter.Write(writer, player, options);
dungeonStateConverter.Write(writer, dungeon, options);
writer.WriteBoolean("has_won", hasWon);
writer.WriteBoolean("has_lost", hasLost);
}
}
}
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using GroupAssignment.entity.player;
namespace GroupAssignment.serialization
{
public class PlayerStateConverter : JsonConverter<Player>
{
public override Player? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
JsonConverter<Position> positionStateConverter = new PositionStateConverter();
var name = reader.GetString();
reader.TryGetInt32(out var points);
reader.TryGetInt32(out var life);
reader.TryGetInt32(out var keys);
var position = positionStateConverter.Read(ref reader, typeToConvert, options);
return new Player(name, points, life, keys, position);
}
public override void Write(Utf8JsonWriter writer, Player value, JsonSerializerOptions options)
{
JsonConverter<Position> positionStateConverter = new PositionStateConverter();
writer.WriteStartObject("player");
writer.WriteString("name", value.GetName());
writer.WriteNumber("points", value.GetPoints());
writer.WriteNumber("life", value.GetLife());
writer.WriteNumber("keys", value.GetKeys());
positionStateConverter.Write(writer, value.GetPosition(), options);
writer.WriteEndObject();
}
}
}
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using GroupAssignment.entity.player;
namespace GroupAssignment.serialization
{
public class PositionStateConverter : JsonConverter<Position>
{
public override Position? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
reader.TryGetInt32(out var x);
reader.TryGetInt32(out var y);
reader.TryGetInt32(out var xO);
reader.TryGetInt32(out var yO);
return new Position(x, y, xO, yO);
}
public override void Write(Utf8JsonWriter writer, Position value, JsonSerializerOptions options)
{
writer.WriteStartObject("positionalData");
writer.WriteNumber("xPos", value.x);
writer.WriteNumber("yPos", value.y);
writer.WriteNumber("xOPos", value.xO);
writer.WriteNumber("yOPos", value.yO);
writer.WriteEndObject();
}
}
}
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using GroupAssignment.dungeon;
using GroupAssignment.dungeon.room;
namespace GroupAssignment.serialization
{
public class DungeonStateConverter : JsonConverter<Dungeon>
{
public override Dungeon? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Room[,] _grid = new Room[10, 10];
JsonConverter<Room> roomStateConverter = new RoomStateConverter();
for (var i = 0; i < 100; i++)
{
var room = roomStateConverter.Read(ref reader, typeToConvert, options);
_grid[room.getXRef, room.getYRef] = room;
}
return new Dungeon(_grid);
}
public override void Write(Utf8JsonWriter writer, Dungeon value, JsonSerializerOptions options)
{
JsonConverter<Room> roomStateConverter = new RoomStateConverter();
writer.WriteStartArray("dungeon");
for (int x = 0; x < 10; x++)
for (int y = 0; y < 10; y++)
roomStateConverter.Write(writer, value.GetRoom(x, y), options);
writer.WriteEndArray();
}
}
}
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using GroupAssignment.dungeon.room;
namespace GroupAssignment.serialization
{
public class RoomStateConverter : JsonConverter<Room>
{
public override Room? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
reader.TryGetInt32(out var x);
reader.TryGetInt32(out var y);
reader.TryGetInt32(out var keys);
reader.TryGetInt32(out var monsters);
return new Room(x, y, keys, monsters);
}
public override void Write(Utf8JsonWriter writer, Room value, JsonSerializerOptions options)
{
writer.WriteStartObject("room");
writer.WriteNumber("x", value.getXRef);
writer.WriteNumber("y", value.getYRef);
writer.WriteNumber("keys", value.HasKey() ? 1 : 0);
writer.WriteNumber("monsters", value.GetRoomMonsters());
writer.WriteEndObject();
}
}
}
using System.Text.Json;
namespace GroupAssignment.serialization
{
public class JsonOptions
{
public static readonly JsonOptions INSTANCE = new();
private JsonWriterOptions options;
private JsonOptions()
{
// Init Writer Options
options = new JsonWriterOptions();
options.Indented = true;
// Init Serializer Options
GetSerializerOptions = new JsonSerializerOptions();
GetSerializerOptions.Converters.Add(new GameEngineStateSerializer());
GetSerializerOptions.Converters.Add(new PlayerStateConverter());
GetSerializerOptions.Converters.Add(new PositionStateConverter());
GetSerializerOptions.Converters.Add(new DungeonStateConverter());
GetSerializerOptions.Converters.Add(new RoomStateConverter());
}
public JsonWriterOptions GetWriterOptions => options;
public JsonSerializerOptions GetSerializerOptions { get; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment