implement game config support

This commit is contained in:
Slavasil 2025-03-23 21:50:47 +03:00
parent 3f7adfd417
commit 44700b1ece
3 changed files with 72 additions and 1 deletions

5
App/Data/GameConfig.cs Normal file
View File

@ -0,0 +1,5 @@
namespace Game.Data {
internal record GameConfig {
public string databasePath;
}
}

50
App/Data/GameFiles.cs Normal file
View File

@ -0,0 +1,50 @@
using System.Text;
namespace Game.Data {
internal class GameFiles {
private const string CONFIG_FILENAME = "quiz_game_config.dat";
private const string DEFAULT_DATABASE_PATH = "bank.txt";
private static readonly byte[] CONFIG_FILE_MAGIC_BYTES = new byte[] { 0x7f, 0x57, 0x77, 0x74, 0x42, 0x00 };
public static bool IsFirstTimePlaying() {
return IsValidConfigFilePresent();
}
public static bool IsValidConfigFilePresent() {
return File.Exists(CONFIG_FILENAME);
}
public static GameConfig? ReadGameConfig() {
try {
using FileStream configFile = new FileStream(CONFIG_FILENAME, FileMode.Open, FileAccess.Read);
using BinaryReader rd = new BinaryReader(configFile);
if (configFile.Length < 6) return null;
byte[] magic = rd.ReadBytes(6);
if (magic.Equals(CONFIG_FILE_MAGIC_BYTES)) {
return null;
}
ushort version = rd.ReadUInt16();
if (version == 1) return ReadConfigV1(rd);
else return null;
} catch (FileNotFoundException) {
return null;
}
}
public static GameConfig CreateDefaultGameConfig() {
using FileStream configFile = new FileStream(CONFIG_FILENAME, FileMode.OpenOrCreate, FileAccess.Write);
using BinaryWriter wr = new BinaryWriter(configFile, Encoding.UTF8);
wr.Write(CONFIG_FILE_MAGIC_BYTES);
wr.Write((ushort)1); // config file version
wr.Write(DEFAULT_DATABASE_PATH);
return new GameConfig() { databasePath = DEFAULT_DATABASE_PATH };
}
public static GameConfig? ReadConfigV1(BinaryReader rd) {
FileStream file = (FileStream)rd.BaseStream;
string databasePath = rd.ReadString();
return new GameConfig() { databasePath = databasePath };
}
}
}

View File

@ -1,4 +1,5 @@
using Game.UI;
using Game.Data;
using Game.UI;
namespace Game {
internal class Program {
@ -14,6 +15,21 @@ namespace Game {
display.ShowSplash();
Thread.Sleep(2500);
GameConfig gameConfig;
try {
GameConfig? existingGameConfig = GameFiles.ReadGameConfig();
if (existingGameConfig == null) {
gameConfig = GameFiles.CreateDefaultGameConfig();
} else {
gameConfig = existingGameConfig;
}
} catch {
display.ShowFatalError("Произошла неизвестная ошибка при чтении/создании файла настроек");
Console.ReadKey();
return 2;
}
string databaseFileName = gameConfig.databasePath;
display.ResetWindow();