Pibd-14_Eredavkin.R.A_Cours.../CourseWorkEreda копия/StateStorage.cs

132 lines
3.9 KiB
C#
Raw Permalink Normal View History

2024-05-27 17:45:42 +04:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
namespace CourseWork_EredavkinRA
{
public class StateStorage
{
private List<ArrayDequeState> states;
public int CurrentStateIndex;
public int Count => states.Count;
public StateStorage()
{
states = new List<ArrayDequeState>();
CurrentStateIndex = 0;
}
public void AddState(ArrayDequeState state, bool nextState = true)
{
if (nextState)
{
CurrentStateIndex++;
}
MessageBox.Show(CurrentStateIndex.ToString());
states.Add(state);
}
public void ClearStates()
{
CurrentStateIndex--;
states.Clear();
}
public IEnumerable<ArrayDequeState> GetStates()
{
return states;
}
public void SaveToFile(string filePath)
{
using (StreamWriter writer = new StreamWriter(filePath))
{
foreach (var state in states)
{
string line = string.Join(",", state.Array) + ";" + state.Top;
writer.WriteLine(line);
}
}
}
public void LoadFromFile(string filePath)
{
states.Clear();
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
try
{
var parts = line.Split(';');
int[] array = parts[0].Split(',').Select(int.Parse).ToArray();
int top = int.Parse(parts[1]);
ArrayDequeState state = new ArrayDequeState(array, top);
states.Add(state);
}
catch (FormatException ex)
{
System.Diagnostics.Debug.WriteLine($"Error parsing line: {line}. Exception: {ex.Message}");
}
}
}
CurrentStateIndex = states.Count > 0 ? states.Count - 1 : -1;
}
public ArrayDequeState? GetLastState()
{
return states.LastOrDefault();
}
public ArrayDequeState? GetCurrentState()
{
if (CurrentStateIndex >= 0 && CurrentStateIndex < states.Count)
{
return states[CurrentStateIndex];
}
return null;
}
public ArrayDequeState GetNextState()
{
MessageBox.Show(CurrentStateIndex + " " + (states.Count - 1));
if (CurrentStateIndex < states.Count - 1)
{
CurrentStateIndex++;
MessageBox.Show(CurrentStateIndex.ToString());
return states[CurrentStateIndex];
}
return null;
}
public ArrayDequeState? GetPreviousState()
{
if (CurrentStateIndex > 0)
{
CurrentStateIndex--;
MessageBox.Show(CurrentStateIndex.ToString());
return states[CurrentStateIndex];
}
return null;
}
public int GetCurrentStateIndex()
{
return CurrentStateIndex;
}
public void StepForward()
{
if (CurrentStateIndex + 1 >= Count) return;
CurrentStateIndex++;
}
public void StepBackward()
{
if (CurrentStateIndex == 0) return;
CurrentStateIndex--;
}
}
}