TouhouLS/Assets/RealCode/GameBoardExtension.cs

107 lines
3.0 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Hashtable = ExitGames.Client.Photon.Hashtable;
using BoardState = System.Collections.Generic.List<System.Collections.Generic.List<TileInfo>>;
using TileList = System.Collections.Generic.List<TileInfo>;
// TODO: Peel this into it's own file?
public static class BoardStateExtension {
public static BoardState Initialize() {
var bs = new BoardState();
for(var i = 0; i < GameBoard.COLUMN; ++i){
bs.Add(new TileList());
}
return bs;
}
public static Hashtable ToHashtable(this BoardState bs) {
var ht = new Hashtable();
for (int i = 0; i < bs.Count; ++i) {
var col = bs[i];
// Store a short[] representation of each column
ht.Add(i, col.Select(t => (short)t).ToArray());
}
return ht;
}
// Did you know that having TileInfo be a class makes this super expensive and complicated?
public static bool Matches(this BoardState bs, BoardState other) {
if (bs.Count != other.Count) return false;
for(int i = 0; i < bs.Count; ++i) {
var subListMine = bs[i].Flatten();
var subListTheirs = other[i].Flatten();
if (!subListMine.SequenceEqual(subListTheirs)) return false;
}
return true;
}
public static short[] Flatten(this List<TileInfo> tileList) {
return tileList.Select(t => t.dat).ToArray();
}
// Unpack and repack all tile infos
public static BoardState Copy(this BoardState bs) {
var copy = Initialize();
for(int i=0; i < bs.Count; ++i) {
copy[i] = bs[i].Select(t=>(TileInfo)t.dat).ToList();
}
return copy;
}
public static void FromHashtable(this BoardState bs, Hashtable ht) {
// The user deserves garbage collection anyways. Don't optimize it unless it's a problem?
for (int i = 0; i < bs.Count; ++i) {
var arr = (short[])ht[i];
bs[i] = arr.Select(t => (TileInfo)t).ToList();
}
}
public static int[] ToHashtable(this List<(int x, int y)> list) {
var array = new int[list.Count * 2];
for (var i = 0; i < list.Count; i++) {
var v = list[i];
array[i * 2] = v.x;
array[i * 2 + 1] = v.y;
}
return array;
}
public static void SetTile(this BoardState board,TileInfo value, int x, int y) {
try {
var col = board[x];
// Set value or append to end
if (y < col.Count) col[y] = value;
else col.Add(value); // Added else. Otherwises, any set would have grown board -- Ebony
} catch (System.Exception e) {
Debug.LogErrorFormat("Illegal placement on board at {0},{1}",x,y);
throw e;
}
}
public static TileInfo tile(this BoardState board, int x, int y) {
if (x < 0 || x >= board.Count) return null;
if (y < 0) return null;
var col = board[x];
if (y < col.Count) return col[y];
return null;
}
public static List<(int x, int y)> FromHashtable(int[] array) {
var list = new List<(int x, int y)>();
for (var i = 0; i < array.Length; i += 2) {
list.Add((array[i], array[i + 1]));
}
return list;
}
}