public void ConstructorWithCapacityAndResizable() { //Resizable SimpleList <string> strings = new SimpleList <string>(2, true); Assert.AreEqual(2, strings.Capacity); Assert.AreEqual(0, strings.Count); strings.Add("Trying to "); Assert.AreEqual(1, strings.Count); strings.Add(" add three "); Assert.AreEqual(2, strings.Count); strings.Add(" strings."); Assert.AreEqual(3, strings.Count); //Not Resizable strings = new SimpleList <string>(2, false); strings.Add("Trying to "); Assert.AreEqual(1, strings.Count); strings.Add(" add three "); Assert.AreEqual(2, strings.Count); Assert.ThrowsException <InvalidOperationException>(() => strings.Add(" could not be added.")); }
public void CopyTo() { SimpleList <string> strings = new SimpleList <string>(3); strings.Add("Hello "); strings.Add("world!"); string[] stringsArr = new string[2]; strings.CopyTo(stringsArr, 0); Assert.AreEqual("Hello ", stringsArr[0]); Assert.AreEqual("world!", stringsArr[1]); Assert.AreEqual(2, strings.Count); Assert.AreEqual(2, stringsArr.Length); Assert.ThrowsException <ArgumentNullException>(() => { strings.CopyTo(null, 0); }); Assert.ThrowsException <ArgumentException>(() => { stringsArr = new string[0]; strings.CopyTo(stringsArr, 0); }); }
public void GetEnumerator() { SimpleList <decimal> decs = new SimpleList <decimal>(10); decs.Add(10.00M); decs.Add(11.01M); decs.Add(12.02M); decs.Add(13.03M); decs.Add(14.04M); IEnumerator <decimal> decimalEnumerator = decs.GetEnumerator(); int index = 0; while (decimalEnumerator.MoveNext()) { Assert.AreEqual(decs[index], decimalEnumerator.Current); index++; } decimalEnumerator.MoveNext(); Assert.AreEqual(10.00M, decimalEnumerator.Current); decimalEnumerator.MoveNext(); Assert.AreEqual(11.01M, decimalEnumerator.Current); decimalEnumerator.Reset(); decimalEnumerator.MoveNext(); Assert.AreEqual(10.00M, decimalEnumerator.Current); decimalEnumerator.Reset(); Assert.AreEqual(Decimal.Zero, decimalEnumerator.Current); }
/// <summary> /// <paramref name="n"/> の約数を返します。 /// </summary> public static long[] Divisor(long n) { if (n == 1) { return new long[] { 1 } } ; var left = new SimpleList <long>(); var right = new SimpleList <long>(); left.Add(1); right.Add(n); for (long i = 2, d = Math.DivRem(n, i, out long amari); i <= d; i++, d = Math.DivRem(n, i, out amari)) { if (amari == 0) { left.Add(i); if (i != d) { right.Add(d); } } } right.Reverse(); var res = new long[left.Count + right.Count]; left.CopyTo(res, 0); right.CopyTo(res, left.Count); return(res); }
public Result LoadCommaFile(string Path) { var result = new Result(String.Format("Loading comma separated file \"{0}\"", SubDirectory)); StreamReader reader; try { reader = new StreamReader(Path + SubDirectory, App.UTF8Encoding); } catch (Exception ex) { result.ProblemAdd(ex.Message); return(result); } while (!reader.EndOfStream) { var line = reader.ReadLine(); line = line.Trim(); if (line.Length > 0) { string[] lineFields = line.Split(','); for (var a = 0; a <= lineFields.GetUpperBound(0); a++) { lineFields[a] = lineFields[a].Trim(); } ResultData.Add(lineFields); } } reader.Close(); return(result); }
public void AllAwake() { var it = sleepList.GetForward(); for (int i = 0, n = sleepList.Count; i < n; ++i) { activeList.Add(it.Ref()); it.Ref().Init(); sleepList.Delete(ref it); } }
public void IndexOf() { SimpleList <string> strings = new SimpleList <string>(3); strings.Add("Hello "); strings.Add("world!"); Assert.AreEqual(0, strings.IndexOf("Hello ")); Assert.AreEqual(1, strings.IndexOf("world!")); Assert.AreEqual(-1, strings.IndexOf(null)); Assert.AreEqual(-1, strings.IndexOf("abc")); }
public void should_be_able_to_add_items_to_the_list() { var sut = new SimpleList<ShopItem>(); var item1 = new ShopItem {Id = 1, Name = "Megaphone", Price = 200m}; sut.Add(item1); sut.Add(item1); sut.Add(item1); Assert.That(sut.Count(), Is.EqualTo(3)); }
public void TestIterator() { SimpleList <object> list = new SimpleList <object>(); list.Add(new Object()); list.Add(new Object()); Iterator <object> it = list.Iterator(); it.Next(); it.Remove(); it.Next(); }
public void AddAllPurchasesToBasket(ShopItem[] purchases) { if ((_basket as DistinctList <ShopItem>) != null) { DistinctListHack(purchases); } for (int itemCount = 0; itemCount < purchases.Length; itemCount++) { _basket.Add(purchases[itemCount]); } }
public void Remove() { SimpleList <string> strings = new SimpleList <string>(4); strings.Add("A"); strings.Add("B"); strings.Add("C"); strings.Add("D"); strings.Remove("A"); Assert.AreEqual("B", strings[0]); Assert.AreEqual("C", strings[1]); Assert.AreEqual("D", strings[2]); strings = new SimpleList <string>(4); strings.Add("A"); strings.Add("B"); strings.Add("C"); strings.Add("D"); strings.Remove("B"); Assert.AreEqual("A", strings[0]); Assert.AreEqual("C", strings[1]); Assert.AreEqual("D", strings[2]); strings = new SimpleList <string>(4); strings.Add("A"); strings.Add("B"); strings.Add("C"); strings.Add("D"); strings.Remove("C"); Assert.AreEqual("A", strings[0]); Assert.AreEqual("B", strings[1]); Assert.AreEqual("D", strings[2]); strings = new SimpleList <string>(4); strings.Add("A"); strings.Add("B"); strings.Add("C"); strings.Add("D"); strings.Remove("D"); Assert.AreEqual("A", strings[0]); Assert.AreEqual("B", strings[1]); Assert.AreEqual("C", strings[2]); Assert.ThrowsException <ArgumentOutOfRangeException>(() => { strings.Remove("W"); }); Assert.ThrowsException <ArgumentOutOfRangeException>(() => { strings.Remove("Y"); }); }
public void should_be_able_to_add_items_to_the_list() { var sut = new SimpleList <ShopItem>(); var item1 = new ShopItem { Id = 1, Name = "Megaphone", Price = 200m }; sut.Add(item1); sut.Add(item1); sut.Add(item1); Assert.That(sut.Count(), Is.EqualTo(3)); }
public void Solve(uint value, SudokuRegion first, SudokuRegion second, SudokuRegionType otherType, SudokuState state, ICollection <IEvent> events) { buffer.Clear(); for (var index = 0; index < 9; index++) { var indexFirst = first[index]; var indexSecond = second[index]; var joinFirst = state[indexFirst] & value; var joinSecond = state[indexSecond] & value; if (joinFirst == 0) { if (joinSecond != 0) { return; } } else { if (joinSecond == 0 || buffer.Count > 3) { return; } buffer.Add(indexFirst); buffer.Add(indexSecond); } } if (buffer.Count == 4) { var reducded = Fetch( value, first.Intersected.FirstOrDefault(r => r.RegionType == otherType), state, events); reducded |= Fetch( value, second.Intersected.FirstOrDefault(r => r.RegionType == otherType), state, events); if (reducded) { events.Add(ReducedOptions.Ctor <ReduceXWing>()); } } }
/// <summary> /// グラフを連結成分に分け、その情報を返します。 /// </summary> /// <para>計算量: O(n)</para> /// <returns>「一つの連結成分の頂点番号のリスト」のリスト。</returns> public int[][] Groups() { int[] leaderBuf = new int[_n]; int[] id = new int[_n]; var resultList = new SimpleList <int[]>(_n); for (int i = 0; i < leaderBuf.Length; i++) { leaderBuf[i] = Leader(i); if (i == leaderBuf[i]) { id[i] = resultList.Count; resultList.Add(new int[-_parentOrSize[i]]); } } var result = resultList.ToArray(); int[] ind = new int[result.Length]; for (int i = 0; i < leaderBuf.Length; i++) { var leaderID = id[leaderBuf[i]]; result[leaderID][ind[leaderID]] = i; ind[leaderID]++; } return(result); }
public TypeInfo GetTypeInfo(Type type) { if (!_typeInfos.ContainsKey(type)) { var typeInfo = new TypeInfo { Id = _typeInfos.Count, TypeName = type.AssemblyQualifiedName, IsEnumerable = type.IsImplOf<IEnumerable>() }; if (!typeInfo.IsEnumerable) { var propertyInfos = type.GetProperties(); var propertyNames = new SimpleList<string>(); foreach (var propertyInfo in propertyInfos) { if (!IsAValidProperty(propertyInfo)) continue; propertyNames.Add(propertyInfo.Name); } typeInfo.PropertyNames = propertyNames; } _typeInfos.Add(type, typeInfo); return typeInfo; } return _typeInfos[type]; }
static SimpleList <T> LCSSearch(int[][] dp, ReadOnlySpan <T> s, int i, int j) { var list = new SimpleList <T>(); while (i > 0 && j > 0) { while (dp[i][j] == dp[i - 1][j]) { if (--i <= 0) { return(list); } } while (dp[i][j] == dp[i][j - 1]) { if (--j <= 0) { return(list); } } list.Add(s[i - 1]); i--; j--; } return(list); }
public void TestListIterator() { Object tempValue; List <Object> list = new ArrayList <Object>(); list.Add(3); list.Add(5); list.Add(5); list.Add(1); list.Add(7); ListIterator <Object> lit = list.ListIterator(); Assert.IsTrue(!lit.HasPrevious, "Should not have previous"); Assert.IsTrue(lit.HasNext, "Should have next"); tempValue = lit.Next(); Assert.IsTrue(tempValue.Equals(3), "next returned wrong value. Wanted 3, got: " + tempValue); tempValue = lit.Previous(); SimpleList <Object> list2 = new SimpleList <Object>(); list2.Add(new Object()); ListIterator <Object> lit2 = list2.ListIterator(); lit2.Add(new Object()); lit2.Next(); list = new MockArrayList <Object>(); ListIterator <Object> it = list.ListIterator(); it.Add("one"); it.Add("two"); Assert.AreEqual(2, list.Size()); }
static void Main(string[] args) { SimpleList<int> _strings = new SimpleList<int>(); _strings.Add(1); _strings.Add(2); _strings.Add(3); _strings.Add(4); _strings.Add(5); var count = _strings.Count; var number5 = _strings[4]; _strings[4] = 6; var number6 = _strings[4]; _strings.Insert(4, 5); var number1 = _strings.RemoveAt(0); _strings.Clear(); }
public void CanIndex() { var sourceNode = new Node(Utils.Id("foo")); var simpleList = new SimpleList <I32>(); simpleList.Init(sourceNode, db); for (int i = 0; i < 100; i++) { simpleList.Add(new I32 { v = i }); } for (int i = 0; i < 100; i++) { Assert.Equal(simpleList[i], new I32 { v = i }); simpleList[i] = new I32 { v = -i }; Assert.Equal(simpleList[i], new I32 { v = -i }); } }
/// <summary>Parses <see cref="CharPixel"/>'s.</summary> public static CharPixels Parse(string input) { Guard.NotNull(input, nameof(input)); var col = 0; var row = 0; var cols = 0; var rows = 0; var hasMissingColumns = false; var buffer = new SimpleList <CharPixel>(input.Length); foreach (var ch in input) { if (ch == '\n') { if (col != 0) { hasMissingColumns |= row != 0 && col != cols; row++; } col = 0; } else if (!char.IsWhiteSpace(ch)) { buffer.Add(new CharPixel(new Point(col, row), ch)); cols = Math.Max(cols, ++col); rows = Math.Max(rows, row); } } return(new CharPixels(buffer, cols, rows + 1, hasMissingColumns)); }
public void CanAddAndRemove() { var sourceNode = new Node(Utils.Id("foo")); var simpleList = new SimpleList <I32>(); simpleList.Init(sourceNode, db); for (int i = 0; i < 100; i++) { simpleList.Add(new I32 { v = i }); } for (int i = 0; i < 100; i += 2) { simpleList.Remove(new I32 { v = i }); } for (int i = 0; i < 100; i++) { if (i % 2 == 1) { Assert.Contains(new I32 { v = i }, simpleList); } else { Assert.DoesNotContain(new I32 { v = i }, simpleList); } } }
private void ReduceRegion(uint pair, SudokuRegion region, SudokuState state, ICollection <IEvent> events) { HiddenPairs.Clear(); foreach (var index in region) { var and = state[index] & pair; // at least on of the two is pressent. if (and != 0) { // If not both are present or we already had 2, return. if (and != pair || HiddenPairs.Count > 1) { return; } HiddenPairs.Add(index); } } if (HiddenPairs.Count == 2) { Fetch(pair, HiddenPairs, state, events); } }
private void ReduceRegion(int skip, SudokuRegion region, SudokuState state, ICollection <IEvent> events) { var quad = 0u; buffer.Clear(); foreach (var index in region.Skip(skip)) { var value = state[index]; if (SudokuCell.Count(value) < 4) { quad |= value; // Joined the represent more then 3 values. if (SudokuCell.Count(quad) > 4 || buffer.Count > 3) { return; } buffer.Add(index); } } if (buffer.Count == 4) { Fetch(quad, buffer, region, state, events); } }
/// <summary> /// Lists all the possible moves a player can make /// </summary> /// <returns>The list of move locations</returns> public static SimpleList<Move> FindPossibleMoves(int player, params int[] filter) { int tempX = Battle.X; int tempY = Battle.Y; int limit = 1; if (player == 2) limit = Battle.Foe.SkillLimit; if (filter.Length > 0) limit = filter[0]; SimpleList<Move> list = new SimpleList<Move>(); for (int a = 0; a < 100; ++a) { Battle.X = a % 10; Battle.Y = a / 10; for (int x = 0; x < limit; ++x) { Type type = Type.GetType(actionPrefix + actionNames[x]); if ((Boolean)type.InvokeMember("CanPerform", BindingFlags.InvokeMethod, null, null, null)) list.Add(new Move(a, x)); } } Battle.X = tempX; Battle.Y = tempY; return list; }
public SimpleList <int> ToList() { var list = new SimpleList <int>(); foreach (var item in this) { list.Add(item); } return(list); }
public void Get_WhenObjectRetrievedByIndex_ShouldReturnCorrectObject() { var simpleList = new SimpleList <object>(); var toAdd = new object(); simpleList.Add(toAdd); var retrieved = simpleList.Get(0); Assert.Equal(toAdd, retrieved); }
public void Get_WhenRetrievingObjectOutsideOfRange_ShouldReturnNull() { var simpleList = new SimpleList <object>(); var toAdd = new object(); simpleList.Add(toAdd); var retrieved = simpleList.Get(1); //outside of range - returns default value for type Assert.Null(retrieved); }
public void Insert() { SimpleList <string> strings = new SimpleList <string>(3, true); strings.Add("first"); strings.Add("second"); strings.Insert(2, "fourth"); strings.Insert(2, "third"); strings.Insert(4, "fifth"); Assert.AreEqual(0, strings.IndexOf("first")); Assert.AreEqual(1, strings.IndexOf("second")); Assert.AreEqual(2, strings.IndexOf("third")); Assert.AreEqual(3, strings.IndexOf("fourth")); Assert.AreEqual(4, strings.IndexOf("fifth")); Assert.ThrowsException <ArgumentOutOfRangeException>(() => { strings.Insert(6, "sixth"); }); }
public void PropertyIndex() { SimpleList <decimal> list = new SimpleList <decimal>(5); list.Add(100M); Assert.AreEqual(100M, list[0]); Assert.ThrowsException <ArgumentOutOfRangeException>(() => { decimal value = list[-1]; }); Assert.ThrowsException <ArgumentOutOfRangeException>(() => { decimal value = list[1]; }); }
public SimpleList<int> GetIndexes() { var current = this; var indexes = new SimpleList<int>(); while (current != null) { indexes.Add(current.Index); current = current.Parent; } indexes.Reverse(); return indexes; }
public static void Main(string[] args) { Application.Init(); var list = new SimpleList(); var label = new Label("Hello World"); foreach (var str in new string[] { "A very long sentence indeeed", "Hello", "World", "No", "Yes" }) { var b = new Button(str) { Height = 1 }; b.PressEvent += () => label.Text = str; list.Add(b); } list.Add(label); Application.Run(list); }
public ComplexTypeItems GetItems(object complexItem) { var dictionary = complexItem.CastObj<IDictionary>(); var keys = new SimpleList<object>(); var values = new SimpleList<object>(); foreach (dynamic item in dictionary) { keys.Add(item.Key); values.Add(item.Value); } return new DictionaryItems { Keys = keys, Values = values }; }
public void Contains() { SimpleList <StringBuilder> builders = new SimpleList <StringBuilder>(2); StringBuilder firstBuilder = new StringBuilder(); StringBuilder secondBuilder = new StringBuilder(); builders.Add(firstBuilder); builders.Add(secondBuilder); Assert.AreEqual(true, builders.Contains(firstBuilder)); Assert.AreEqual(false, builders.Contains(new StringBuilder())); SimpleList <int> numbers = new SimpleList <int>(new int[] { 1, 2, 3 }); Assert.AreEqual(true, numbers.Contains(3)); Assert.AreEqual(false, numbers.Contains(4)); SimpleList <string> nulls = new SimpleList <string>(new string[] { null, null, null }); Assert.ThrowsException <NullReferenceException>(() => nulls.Contains(null)); }
public void Get_WhenCalled_ValueOrDefaultReturned() { var simpleList = new SimpleList <int>(); simpleList.Add(3); var retrieved = simpleList.Get(0); Assert.Equal(3, retrieved); retrieved = simpleList.Get(1); //out of range - returns default value of type Assert.Equal(0, retrieved); }
public static char[] Flatten(this string[] strs) { var res = new SimpleList <char>(strs.Length * Math.Max(strs[0].Length, 1)); for (int i = 0; i < strs.Length; i++) { for (int j = 0; j < strs[i].Length; j++) { res.Add(strs[i][j]); } } return(res.ToArray()); }
public static T[] Flatten <T>(this IEnumerable <IEnumerable <T> > collection) { var res = new SimpleList <T>(); foreach (var col in collection) { foreach (var item in col) { res.Add(item); } } return(res.ToArray()); }
public static T[] Flatten <T>(this ReadOnlySpan <T[]> span) { var res = new SimpleList <T>(span.Length * Math.Max(span[0].Length, 1)); for (int i = 0; i < span.Length; i++) { for (int j = 0; j < span[i].Length; j++) { res.Add(span[i][j]); } } return(res.ToArray()); }
public static SimpleList<Type> GetTypes(this AppDomain appDomain, Func<Type, bool> func) { var simpleList = new SimpleList<Type>(); var assemblies = appDomain.GetAssemblies(); foreach (var assembly in assemblies) { var types = assembly.GetTypes(); foreach (var type in types) { if (!func(type)) continue; simpleList.Add(type); } } return simpleList; }
/// <summary> /// Uses a template according to the given parameters to generate a room /// </summary> /// <param name="typeInt">A randomed integer that determines the type</param> /// <param name="l">The room length</param> /// <param name="w">The room width</param> /// <returns>The room layout</returns> public static char[,] CreateRoom(int typeInt, int l, int w) { // Get the list of templates SimpleList<string> types = new SimpleList<string>(); var q = from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsClass && t.Namespace == templateTypes select t; q.ToList().ForEach(t => types.Add(t.Name)); // Choose the template according to the type given int moduloType = typeInt % types.Size; // Apply the corresponding template Type type = Type.GetType(templateTypes + "." + types[moduloType]); return (char[,])type.InvokeMember("Create", BindingFlags.InvokeMethod, null, null, new object[] {l, w, typeInt % 2}); }
public ComplexTypeItems GetItems(object complexItem) { var type = complexItem.GetTypeOfObj(); var propertyInfos = type.GetProperties(); var names = new SimpleList<string>(); var values = new SimpleList<object>(); foreach (var propertyInfo in propertyInfos) { if (!IsAValidProperty(propertyInfo)) continue; names.Add(propertyInfo.Name); values.Add(propertyInfo.GetValue(complexItem)); } return new UserDefinedItems { Names = names, Values = values }; }
public void SetItems(object complexItem, ComplexTypeItems complexTypeItems) { var arrayItems = complexTypeItems.CastObj<ArrayItems>(); var items = arrayItems.Items; var array = complexItem.CastObj<Array>(); var rankLengths = array.GetIndicies(); var recursiveFor = RecursiveFor.Prepare(rankLengths); var allCombinations = new SimpleList<SimpleList<int>>(); recursiveFor.Begin(info => allCombinations.Add(info.GetIndexes())); if (allCombinations.Count != items.Count) throw new Exception(string.Format("Array instance says there should be more than {0} items in this array", items.Count)); for (var i = 0; i < allCombinations.Count; i++) { var combination = allCombinations[i]; var item = items[i]; array.SetValue(item, combination.ToArray()); } }
public void UndoPerform() { clsUndo ThisUndo = default(clsUndo); UndoStepCreate("Incomplete Action"); //make another redo step incase something has changed, such as if user presses undo while still dragging a tool UndoPosition--; ThisUndo = Undos[UndoPosition]; sXY_int SectorNum = new sXY_int(); clsShadowSector CurrentSector = default(clsShadowSector); clsShadowSector UndoSector = default(clsShadowSector); SimpleList<clsShadowSector> NewSectorsForThisUndo = new SimpleList<clsShadowSector>(); foreach ( clsShadowSector tempLoopVar_UndoSector in ThisUndo.ChangedSectors ) { UndoSector = tempLoopVar_UndoSector; SectorNum = UndoSector.Num; //store existing state for redo CurrentSector = ShadowSectors[SectorNum.X, SectorNum.Y]; //remove graphics from sector Sectors[SectorNum.X, SectorNum.Y].DeleteLists(); //perform the undo Undo_Sector_Rejoin(UndoSector); //update the backup ShadowSector_Create(SectorNum); //add old state to the redo step (that was this undo step) NewSectorsForThisUndo.Add(CurrentSector); //prepare to update graphics on this sector SectorGraphicsChanges.Changed(SectorNum); } ThisUndo.ChangedSectors = NewSectorsForThisUndo; UInt32 ID = 0; clsUnitAdd UnitAdd = new clsUnitAdd(); UnitAdd.Map = this; clsUnit Unit = default(clsUnit); for ( int A = ThisUndo.UnitChanges.Count - 1; A >= 0; A-- ) //must do in reverse order, otherwise may try to delete units that havent been added yet { Unit = ThisUndo.UnitChanges[A].Unit; if ( ThisUndo.UnitChanges[A].Type == clsUnitChange.enumType.Added ) { //remove the unit from the map UnitRemove(Unit.MapLink.ArrayPosition); } else if ( ThisUndo.UnitChanges[A].Type == clsUnitChange.enumType.Deleted ) { //add the unit back on to the map ID = Unit.ID; UnitAdd.ID = ID; UnitAdd.NewUnit = Unit; UnitAdd.Perform(); App.ErrorIDChange(ID, Unit, "Undo_Perform"); } else { Debugger.Break(); } } clsGatewayChange GatewayChange = default(clsGatewayChange); for ( int A = ThisUndo.GatewayChanges.Count - 1; A >= 0; A-- ) { GatewayChange = ThisUndo.GatewayChanges[A]; switch ( GatewayChange.Type ) { case clsGatewayChange.enumType.Added: //remove the unit from the map GatewayChange.Gateway.MapLink.Disconnect(); break; case clsGatewayChange.enumType.Deleted: //add the unit back on to the map GatewayChange.Gateway.MapLink.Connect(Gateways); break; default: Debugger.Break(); break; } } SectorsUpdateGraphics(); MinimapMakeLater(); Program.frmMainInstance.SelectedObject_Changed(); }
/// <summary> /// Finds the list of locations that will be captured if a token was placed at the current location by the given player /// </summary> /// <param name="player">The player placing the token</param> /// <returns>The list of captured token locations</returns> private static SimpleList<int> FindCapturedTokens() { int player = Battle.CurrentTurn; SimpleList<int> spots = new SimpleList<int>(); // Checks in all 8 directions, starting with North for (int d = 0; d < 8; ++d) { int searchX = Battle.X + xChanges[d]; int searchY = Battle.Y + yChanges[d]; // Gets the list of possible moves SimpleList<int> possibleSpots = new SimpleList<int>(); // Allow it to search only within the grid's range while (searchX >= 0 && searchX < 10 && searchY >= 0 && searchY < 10) { int spot = Battle.Field[10 * searchY + searchX]; // If it's an enemy piece, remember the location if (spot == 3 - player) possibleSpots.Add(10 * searchY + searchX); // Stop when it's an owned piece else if (possibleSpots.Size > 0 && spot == player) { break; } // Stop and clear the list if it's an empty piece else { possibleSpots.Clear(); break; } searchX += xChanges[d]; searchY += yChanges[d]; } // If the loop ended because of going out of range, clear the list if (searchX < 0 || searchX > 9 || searchY < 0 || searchY > 9) possibleSpots.Clear(); // Add all the valid spots found that weren't cleared foreach (int i in possibleSpots) spots.Add(i); } return spots; }
public static SimpleList<string> BytesToLinesRemoveComments(BinaryReader reader) { char CurrentChar = (char)0; bool CurrentCharExists = default(bool); bool InLineComment = default(bool); bool InCommentBlock = default(bool); char PrevChar = (char)0; bool PrevCharExists = default(bool); string Line = ""; SimpleList<string> Result = new SimpleList<string>(); do { MonoContinueDo: PrevChar = CurrentChar; PrevCharExists = CurrentCharExists; try { CurrentChar = reader.ReadChar(); CurrentCharExists = true; } catch ( Exception ) { CurrentCharExists = false; } if ( CurrentCharExists ) { switch ( CurrentChar ) { case ControlChars.Cr: case ControlChars.Lf: InLineComment = false; if ( PrevCharExists ) { Line += PrevChar.ToString(); } CurrentCharExists = false; if ( Line.Length > 0 ) { Result.Add(Line); Line = ""; } goto MonoContinueDo; case '*': if ( PrevCharExists && PrevChar == '/' ) { InCommentBlock = true; CurrentCharExists = false; goto MonoContinueDo; } break; case '/': if ( PrevCharExists ) { if ( PrevChar == '/' ) { InLineComment = true; CurrentCharExists = false; goto MonoContinueDo; } else if ( PrevChar == '*' ) { InCommentBlock = false; CurrentCharExists = false; goto MonoContinueDo; } } break; } } else { InLineComment = false; if ( PrevCharExists ) { Line += PrevChar.ToString(); } if ( Line.Length > 0 ) { Result.Add(Line); Line = ""; } break; } if ( PrevCharExists ) { if ( !(InCommentBlock || InLineComment) ) { Line += PrevChar.ToString(); } } } while ( true ); return Result; }
public void PerformTileWall(clsWallType WallType, sXY_int TileNum, bool Expand) { sXY_int SectorNum = new sXY_int(); clsUnit Unit = default(clsUnit); sXY_int UnitTile = new sXY_int(); sXY_int Difference = new sXY_int(); App.enumTileWalls TileWalls = App.enumTileWalls.None; SimpleList<clsUnit> Walls = new SimpleList<clsUnit>(); SimpleList<clsUnit> Removals = new SimpleList<clsUnit>(); clsUnitType UnitType = default(clsUnitType); clsStructureType StructureType = default(clsStructureType); int X = 0; int Y = 0; sXY_int MinTile = new sXY_int(); sXY_int MaxTile = new sXY_int(); clsUnitSectorConnection Connection = default(clsUnitSectorConnection); MinTile.X = TileNum.X - 1; MinTile.Y = TileNum.Y - 1; MaxTile.X = TileNum.X + 1; MaxTile.Y = TileNum.Y + 1; sXY_int SectorStart = GetSectorNumClamped(GetTileSectorNum(MinTile)); sXY_int SectorFinish = GetSectorNumClamped(GetTileSectorNum(MaxTile)); for ( Y = SectorStart.Y; Y <= SectorFinish.Y; Y++ ) { for ( X = SectorStart.X; X <= SectorFinish.X; X++ ) { SectorNum.X = X; SectorNum.Y = Y; foreach ( clsUnitSectorConnection tempLoopVar_Connection in Sectors[SectorNum.X, SectorNum.Y].Units ) { Connection = tempLoopVar_Connection; Unit = Connection.Unit; UnitType = Unit.Type; if ( UnitType.Type == clsUnitType.enumType.PlayerStructure ) { StructureType = (clsStructureType)UnitType; if ( StructureType.WallLink.Source == WallType ) { UnitTile = GetPosTileNum(Unit.Pos.Horizontal); Difference.X = UnitTile.X - TileNum.X; Difference.Y = UnitTile.Y - TileNum.Y; if ( Difference.Y == 1 ) { if ( Difference.X == 0 ) { TileWalls = (App.enumTileWalls)(TileWalls | App.enumTileWalls.Bottom); Walls.Add(Unit); } } else if ( Difference.Y == 0 ) { if ( Difference.X == 0 ) { Removals.Add(Unit); } else if ( Difference.X == -1 ) { TileWalls = (App.enumTileWalls)(TileWalls | App.enumTileWalls.Left); Walls.Add(Unit); } else if ( Difference.X == 1 ) { TileWalls = (App.enumTileWalls)(TileWalls | App.enumTileWalls.Right); Walls.Add(Unit); } } else if ( Difference.Y == -1 ) { if ( Difference.X == 0 ) { TileWalls = (App.enumTileWalls)(TileWalls | App.enumTileWalls.Top); Walls.Add(Unit); } } } } } } } foreach ( clsUnit tempLoopVar_Unit in Removals ) { Unit = tempLoopVar_Unit; UnitRemoveStoreChange(Unit.MapLink.ArrayPosition); } clsUnit NewUnit = new clsUnit(); clsUnitType NewUnitType = WallType.Segments[WallType.TileWalls_Segment[(int)TileWalls]]; NewUnit.Rotation = WallType.TileWalls_Direction[(int)TileWalls]; if ( Expand ) { NewUnit.UnitGroup = SelectedUnitGroup.Item; } else { if ( Removals.Count == 0 ) { Debugger.Break(); return; } NewUnit.UnitGroup = Removals[0].UnitGroup; } NewUnit.Pos = TileAlignedPos(TileNum, new sXY_int(1, 1)); NewUnit.Type = NewUnitType; clsUnitAdd UnitAdd = new clsUnitAdd(); UnitAdd.Map = this; UnitAdd.NewUnit = NewUnit; UnitAdd.StoreChange = true; UnitAdd.Perform(); if ( Expand ) { clsUnit Wall = default(clsUnit); foreach ( clsUnit tempLoopVar_Wall in Walls ) { Wall = tempLoopVar_Wall; PerformTileWall(WallType, GetPosTileNum(Wall.Pos.Horizontal), false); } } }
public void ListSupportShouldGetAndSetItems() { var list = new SimpleList<int>(); var test = new SimpleList<int>(); for (var i = 0; i < 30; i++) list.Add(i); var listSupport = new ListSupport(); var items = listSupport.GetItems(list); listSupport.SetItems(test, items); var matches = true; for (var i = 0; i < list.Count; i++) { if (list[i].Equals(test[i])) continue; matches = false; break; } Assert.IsTrue(matches); }
private static void ForInfoExample() { var forInfo = RecursiveFor.Prepare(new SimpleList<int> { 2, 3, 4 }); var allCombinations = new SimpleList<SimpleList<int>>(); forInfo.Begin(info => allCombinations.Add(info.GetIndexes())); foreach (var allCombination in allCombinations) { foreach (var i in allCombination) { Console.Write(i); Console.Write("-"); } Console.WriteLine(); } }
public DefContext Define(object value) { if (value == null) return null; var type = value.GetTypeOfObj(); if (_simpleTypeHelper.HasSupport(type)) return new SimpleDefContext { SimpleTypeDef = new SimpleTypeDef { Value = value } }; var objectEnumerator = new ObjectEnumerator(value); var typeEnumerator = new TypeEnumerator(); var complexTypeDefs = new SimpleList<ComplexTypeDef>(); while (objectEnumerator.Continue) { var current = objectEnumerator.GetNext(); var currentType = current.GetType(); var currentId = objectEnumerator.Get(current); var typeInfo = typeEnumerator.GetTypeInfo(currentType); if (currentType.IsImplOf<Array>()) { #region Array var array = current.CastObj<Array>(); var arrayItems = _complexTypeHelper .GetItems(array).CastObj<ArrayItems>(); var items = new SimpleList<object>(); foreach (var item in arrayItems.Items) items.Add(CheckReference(item, objectEnumerator)); complexTypeDefs.Add(new ArrayDef { Id = currentId, TypeInfoId = typeInfo.Id, Items = items, Indicies = array.GetIndicies() }); #endregion } else if (currentType.IsImplOf<IList>()) { #region List var list = current.CastObj<IList>(); var listItems = _complexTypeHelper .GetItems(list).CastObj<ListItems>(); var items = new SimpleList<object>(); foreach (var item in listItems.Items) items.Add(CheckReference(item, objectEnumerator)); complexTypeDefs.Add(new ListDef { Id = currentId, TypeInfoId = typeInfo.Id, Items = items }); #endregion } else if (currentType.IsImplOf<IDictionary>()) { #region Dictionary var dictionary = current.CastObj<IDictionary>(); var dictionaryItems = _complexTypeHelper .GetItems(dictionary).CastObj<DictionaryItems>(); var keys = new SimpleList<object>(); foreach (var key in dictionaryItems.Keys) keys.Add(CheckReference(key, objectEnumerator)); var values = new SimpleList<object>(); foreach (var val in dictionaryItems.Values) values.Add(CheckReference(val, objectEnumerator)); complexTypeDefs.Add(new DictionaryDef { Id = currentId, TypeInfoId = typeInfo.Id, Keys = keys, Values = values }); #endregion } else // user defined tpye at last { #region UserDefined var userDefinedItems = _complexTypeHelper .GetItems(current).CastObj<UserDefinedItems>(); var names = new SimpleList<byte>(); foreach (var name in userDefinedItems.Names) names.Add(typeInfo.PropertyNameIndex[name]); var values = new SimpleList<object>(); foreach (var val in userDefinedItems.Values) values.Add(CheckReference(val, objectEnumerator)); complexTypeDefs.Add(new UserDefinedDef { Id = currentId, TypeInfoId = typeInfo.Id, Names = names, Values = values }); #endregion } objectEnumerator.DefinedANewOne(); } return new ComplexDefContext { ComplexTypeDefs = complexTypeDefs, TypeInfos = typeEnumerator.GetTypeInfos() }; }
public void btnSave_Click(Object sender, EventArgs e) { clsSettings NewSettings = (clsSettings)(SettingsManager.Settings.GetCopy(new SettingsCreator())); double dblTemp = 0; int intTemp = 0; if ( IOUtil.InvariantParse(txtAutosaveChanges.Text, ref dblTemp) ) { NewSettings.set_Changes(SettingsManager.Setting_AutoSaveMinChanges, new Change<UInt32>((uint)(MathUtil.Clamp_dbl(dblTemp, 1.0D, (Convert.ToDouble(UInt32.MaxValue)) - 1.0D)))); } if ( IOUtil.InvariantParse(txtAutosaveInterval.Text, ref dblTemp) ) { NewSettings.set_Changes(SettingsManager.Setting_AutoSaveMinInterval_s, new Change<UInt32>((uint)(MathUtil.Clamp_dbl(dblTemp, 1.0D, (Convert.ToDouble(UInt32.MaxValue)) - 1.0D)))); } NewSettings.set_Changes(SettingsManager.Setting_AutoSaveCompress, new Change<bool>(cbxAutosaveCompression.Checked)); NewSettings.set_Changes(SettingsManager.Setting_AutoSaveEnabled, new Change<bool>(cbxAutosaveEnabled.Checked)); NewSettings.set_Changes(SettingsManager.Setting_DirectoriesPrompt, new Change<bool>(cbxAskDirectories.Checked)); NewSettings.set_Changes(SettingsManager.Setting_DirectPointer, new Change<bool>(cbxPointerDirect.Checked)); NewSettings.set_Changes(SettingsManager.Setting_FontFamily, new Change<FontFamily>(DisplayFont.FontFamily)); if ( IOUtil.InvariantParse(txtFOV.Text, ref dblTemp) ) { NewSettings.set_Changes(SettingsManager.Setting_FOVDefault, new Change<double>(dblTemp)); } NewSettings.set_Changes(SettingsManager.Setting_MinimapCliffColour, new Change<clsRGBA_sng>(MinimapCliffColour)); NewSettings.set_Changes(SettingsManager.Setting_MinimapSelectedObjectsColour, new Change<clsRGBA_sng>(MinimapSelectedObjectColour)); if ( IOUtil.InvariantParse(txtMinimapSize.Text, ref intTemp) ) { NewSettings.set_Changes(SettingsManager.Setting_MinimapSize, new Change<int>(intTemp)); } NewSettings.set_Changes(SettingsManager.Setting_MinimapTeamColours, new Change<bool>(cbxMinimapObjectColours.Checked)); NewSettings.set_Changes(SettingsManager.Setting_MinimapTeamColoursExceptFeatures, new Change<bool>(cbxMinimapTeamColourFeatures.Checked)); NewSettings.set_Changes(SettingsManager.Setting_Mipmaps, new Change<bool>(cbxMipmaps.Checked)); NewSettings.set_Changes(SettingsManager.Setting_MipmapsHardware, new Change<bool>(cbxMipmapsHardware.Checked)); if ( IOUtil.InvariantParse(txtUndoSteps.Text, ref intTemp) ) { NewSettings.set_Changes(SettingsManager.Setting_UndoLimit, new Change<int>(intTemp)); } SimpleList<string> tilesetPaths = new SimpleList<string>(); SimpleList<string> objectsPaths = new SimpleList<string>(); string[] controlTilesetPaths = tilesetsPathSetControl.GetPaths; string[] controlobjectsPaths = objectDataPathSetControl.GetPaths; for ( int i = 0; i <= controlTilesetPaths.GetUpperBound(0); i++ ) { tilesetPaths.Add(controlTilesetPaths[i]); } for ( int i = 0; i <= controlobjectsPaths.GetUpperBound(0); i++ ) { objectsPaths.Add(controlobjectsPaths[i]); } NewSettings.set_Changes(SettingsManager.Setting_TilesetDirectories, new Change<SimpleList<string>>(tilesetPaths)); NewSettings.set_Changes(SettingsManager.Setting_ObjectDataDirectories, new Change<SimpleList<string>>(objectsPaths)); NewSettings.set_Changes(SettingsManager.Setting_DefaultTilesetsPathNum, new Change<int>(tilesetsPathSetControl.SelectedNum)); NewSettings.set_Changes(SettingsManager.Setting_DefaultObjectDataPathNum, new Change<int>(objectDataPathSetControl.SelectedNum)); if ( IOUtil.InvariantParse(txtMapBPP.Text, ref intTemp) ) { NewSettings.set_Changes(SettingsManager.Setting_MapViewBPP, new Change<int>(intTemp)); } if ( IOUtil.InvariantParse(txtMapDepth.Text, ref intTemp) ) { NewSettings.set_Changes(SettingsManager.Setting_MapViewDepth, new Change<int>(intTemp)); } if ( IOUtil.InvariantParse(txtTexturesBPP.Text, ref intTemp) ) { NewSettings.set_Changes(SettingsManager.Setting_TextureViewBPP, new Change<int>(intTemp)); } if ( IOUtil.InvariantParse(txtTexturesDepth.Text, ref intTemp) ) { NewSettings.set_Changes(SettingsManager.Setting_TextureViewDepth, new Change<int>(intTemp)); } NewSettings.set_Changes(SettingsManager.Setting_PickOrientation, new Change<bool>(cbxPickerOrientation.Checked)); SettingsManager.UpdateSettings(NewSettings); clsMap Map = Program.frmMainInstance.MainMap; if ( Map != null ) { Map.MinimapMakeLater(); } Program.frmMainInstance.View_DrawViewLater(); KeyboardManager.KeyboardProfile = ChangedKeyControls; Finish(DialogResult.OK); }
public object GetInstance(DefContext defContext) { if (defContext == null) return null; var type = defContext.GetTypeOfObj(); if (type.IsTypeOf<SimpleDefContext>()) return defContext.CastObj<SimpleDefContext>() .SimpleTypeDef.Value; if (type.IsTypeOf<ComplexDefContext>()) { var context = defContext.CastObj<ComplexDefContext>(); var complexTypeDefs = context.ComplexTypeDefs; var typeInfos = context.TypeInfos; var typeInfosWithId = new Dictionary<int, TypeInfo>(); foreach (var typeInfo in typeInfos) typeInfosWithId.Add(typeInfo.Id, typeInfo); var instances = new Dictionary<int, object>(); short indexesAsIds = 0; #region Get Instances foreach (var complexTypeDef in complexTypeDefs) { var typeInfo = typeInfosWithId[complexTypeDef.TypeInfoId]; var currentType = Type.GetType(typeInfo.TypeName); if (currentType == null) throw new Exception(string.Format("Unknown type : {0}", typeInfo.TypeName)); if (currentType.IsImplOf<Array>()) { var arrayDef = complexTypeDef.CastObj<ArrayDef>(); instances.Add(indexesAsIds, _complexTypeHelper.CreateInstance(currentType, arrayDef.Indicies)); } else instances.Add(indexesAsIds, _complexTypeHelper.CreateInstance(currentType)); indexesAsIds++; } #endregion #region Relate Instances foreach (var complexTypeDef in complexTypeDefs) { var instance = instances[complexTypeDef.Id]; var instanceType = instance.GetTypeOfObj(); if (instanceType.IsImplOf<Array>()) { #region Array var arrayDef = complexTypeDef.CastObj<ArrayDef>(); var items = new SimpleList<object>(); foreach (var defValue in arrayDef.Items) items.Add(CheckInstance(defValue, instances)); var arrayItems = new ArrayItems { Items = items }; _complexTypeHelper.SetItems(instance, arrayItems); #endregion } else if (instanceType.IsImplOf<IList>()) { #region List var listDef = complexTypeDef.CastObj<ListDef>(); var items = new SimpleList<object>(); foreach (var defValue in listDef.Items) items.Add(CheckInstance(defValue, instances)); var listItems = new ListItems { Items = items }; _complexTypeHelper.SetItems(instance, listItems); #endregion } else if (instanceType.IsImplOf<IDictionary>()) { #region Dictionary var dictionaryDef = complexTypeDef.CastObj<DictionaryDef>(); var keys = new SimpleList<object>(); foreach (var defValue in dictionaryDef.Keys) keys.Add(CheckInstance(defValue, instances)); var values = new SimpleList<object>(); foreach (var defValue in dictionaryDef.Values) values.Add(CheckInstance(defValue, instances)); var dictionaryItems = new DictionaryItems { Keys = keys, Values = values }; _complexTypeHelper.SetItems(instance, dictionaryItems); #endregion } else // user defined tpye at last { #region UserDefined var userDefinedDef = complexTypeDef.CastObj<UserDefinedDef>(); var typeInfo = typeInfosWithId[userDefinedDef.TypeInfoId]; var names = new SimpleList<string>(); foreach (var index in userDefinedDef.Names) names.Add(typeInfo.PropertyIndexName[index]); var values = new SimpleList<object>(); foreach (var defValue in userDefinedDef.Values) values.Add(CheckInstance(defValue, instances)); var userDefinedItems = new UserDefinedItems { Names = names, Values = values }; _complexTypeHelper.SetItems(instance, userDefinedItems); #endregion } } #endregion return instances[complexTypeDefs.SelectFirst().Id]; } throw new UnknownImplementationException(typeof(DefContext), type); }
/// <summary> /// Loads an array from the given data /// </summary> /// <returns>array</returns> private SimpleList<object> LoadArray() { SimpleList<object> array = new SimpleList<object>(); // Empty array if (data[0] == ']') { data = data.Substring(1); return array; } string current = ""; while (data.Length > 0) { char c = data[0]; data = data.Substring(1); // End of element if (c == ',') { array.Add(current); current = ""; } // End of array else if (c == ']') { array.Add(current); return array; } // Array inside the array else if (c == '[') { array.Add(LoadArray()); if (data[0] != ',' && data[0] != ']') throw new InvalidJSONDataException("Illegal character after ']': '" + data[0] + "'."); if (data[0] == ',') data = data.Substring(1); if (data[0] == ']') { data = data.Substring(1); return array; } } // Object inside the array else if (c == '{') { array.Add(LoadObject()); if (data[0] != ',' && data[0] != ']') throw new InvalidJSONDataException("Illegal character after '}' in array: '" + data[0] + "'."); if (data[0] == ',') data = data.Substring(1); if (data[0] == ']') { data = data.Substring(1); return array; } } else { current += c; } } return array; }
public clsResult Load_WZ(string Path) { clsResult ReturnResult = new clsResult("Loading WZ from " + Convert.ToString(ControlChars.Quote) + Path + Convert.ToString(ControlChars.Quote)); App.sResult SubResult = new App.sResult(); string Quote = ControlChars.Quote.ToString(); ZipEntry ZipEntry = default(ZipEntry); bool GameFound = default(bool); bool DatasetFound = default(bool); SimpleList<clsWZMapEntry> Maps = new SimpleList<clsWZMapEntry>(); clsTileset GameTileset = null; string GameName = ""; string strTemp = ""; ZipSplitPath SplitPath; int A = 0; int B = 0; int C = 0; int D = 0; FileStream File = default(FileStream); try { File = System.IO.File.OpenRead(Path); } catch ( Exception ex ) { ReturnResult.ProblemAdd(ex.Message); return ReturnResult; } ZipInputStream ZipStream = new ZipInputStream(File); //get all usable lev entries do { ZipEntry = ZipStream.GetNextEntry(); if ( ZipEntry == null ) { break; } SplitPath = new ZipSplitPath(ZipEntry.Name); if ( SplitPath.FileExtension == "lev" && SplitPath.PartCount == 1 ) { if ( ZipEntry.Size > 10 * 1024 * 1024 ) { ReturnResult.ProblemAdd("lev file is too large."); ZipStream.Close(); return ReturnResult; } BinaryReader Reader = new BinaryReader(ZipStream); SimpleList<string> LineData = IOUtil.BytesToLinesRemoveComments(Reader); //find each level block for ( A = 0; A <= LineData.Count - 1; A++ ) { if ( Strings.LCase(Strings.Left(LineData[A], 5)) == "level" ) { //find each levels game file GameFound = false; B = 1; while ( A + B < LineData.Count ) { if ( Strings.LCase(Strings.Left(Convert.ToString(LineData[A + B]), 4)) == "game" ) { C = Strings.InStr(Convert.ToString(LineData[A + B]), Quote, (CompareMethod)0); D = Strings.InStrRev(Convert.ToString(LineData[A + B]), Quote, -1, (CompareMethod)0); if ( C > 0 & D > 0 & D - C > 1 ) { GameName = Strings.LCase(Strings.Mid(Convert.ToString(LineData[A + B]), C + 1, D - C - 1)); //see if map is already counted for ( C = 0; C <= Maps.Count - 1; C++ ) { if ( GameName == Maps[C].Name ) { break; } } if ( C == Maps.Count ) { GameFound = true; } } break; } else if ( Strings.LCase(Strings.Left(Convert.ToString(LineData[A + B]), 5)) == "level" ) { break; } B++; } if ( GameFound ) { //find the dataset (determines tileset) DatasetFound = false; B = 1; while ( A + B < LineData.Count ) { if ( Strings.LCase(Strings.Left(Convert.ToString(LineData[A + B]), 7)) == "dataset" ) { strTemp = Strings.LCase(Strings.Right(Convert.ToString(LineData[A + B]), 1)); if ( strTemp == "1" ) { GameTileset = App.Tileset_Arizona; DatasetFound = true; } else if ( strTemp == "2" ) { GameTileset = App.Tileset_Urban; DatasetFound = true; } else if ( strTemp == "3" ) { GameTileset = App.Tileset_Rockies; DatasetFound = true; } break; } else if ( Strings.LCase(Strings.Left(Convert.ToString(LineData[A + B]), 5)) == "level" ) { break; } B++; } if ( DatasetFound ) { clsWZMapEntry NewMap = new clsWZMapEntry(); NewMap.Name = GameName; NewMap.Tileset = GameTileset; Maps.Add(NewMap); } } } } } } while ( true ); ZipStream.Close(); string MapLoadName = ""; //prompt user for which of the entries to load if ( Maps.Count < 1 ) { ReturnResult.ProblemAdd("No maps found in file."); return ReturnResult; } else if ( Maps.Count == 1 ) { MapLoadName = Convert.ToString(Maps[0].Name); Tileset = Maps[0].Tileset; } else { frmWZLoad.clsOutput SelectToLoadResult = new frmWZLoad.clsOutput(); string[] Names = new string[Maps.Count]; for ( A = 0; A <= Maps.Count - 1; A++ ) { Names[A] = Convert.ToString(Maps[A].Name); } frmWZLoad SelectToLoadForm = new frmWZLoad(Names, SelectToLoadResult, "Select a map from " + Convert.ToString(new App.sSplitPath(Path).FileTitle)); SelectToLoadForm.ShowDialog(); if ( SelectToLoadResult.Result < 0 ) { ReturnResult.ProblemAdd("No map selected."); return ReturnResult; } MapLoadName = Convert.ToString(Maps[SelectToLoadResult.Result].Name); Tileset = Maps[SelectToLoadResult.Result].Tileset; } TileType_Reset(); SetPainterToDefaults(); ZipSplitPath GameSplitPath = new ZipSplitPath(MapLoadName); string GameFilesPath = GameSplitPath.FilePath + GameSplitPath.FileTitleWithoutExtension + "/"; ZipStreamEntry ZipSearchResult = default(ZipStreamEntry); ZipSearchResult = IOUtil.FindZipEntryFromPath(Path, MapLoadName); if ( ZipSearchResult == null ) { ReturnResult.ProblemAdd("Game file not found."); return ReturnResult; } else { BinaryReader Map_Reader = new BinaryReader(ZipSearchResult.Stream); SubResult = Read_WZ_gam(Map_Reader); Map_Reader.Close(); if ( !SubResult.Success ) { ReturnResult.ProblemAdd(SubResult.Problem); return ReturnResult; } } ZipSearchResult = IOUtil.FindZipEntryFromPath(Path, GameFilesPath + "game.map"); if ( ZipSearchResult == null ) { ReturnResult.ProblemAdd("game.map file not found"); return ReturnResult; } else { BinaryReader Map_Reader = new BinaryReader(ZipSearchResult.Stream); SubResult = Read_WZ_map(Map_Reader); Map_Reader.Close(); if ( !SubResult.Success ) { ReturnResult.ProblemAdd(SubResult.Problem); return ReturnResult; } } SimpleClassList<clsWZBJOUnit> BJOUnits = new SimpleClassList<clsWZBJOUnit>(); IniFeatures INIFeatures = null; ZipSearchResult = IOUtil.FindZipEntryFromPath(Path, GameFilesPath + "feature.ini"); if ( ZipSearchResult == null ) { } else { clsResult Result = new clsResult("feature.ini"); IniReader FeaturesINI = new IniReader(); StreamReader FeaturesINI_Reader = new StreamReader(ZipSearchResult.Stream); Result.Take(FeaturesINI.ReadFile(FeaturesINI_Reader)); FeaturesINI_Reader.Close(); INIFeatures = new IniFeatures(FeaturesINI.Sections.Count); Result.Take(FeaturesINI.Translate(INIFeatures)); ReturnResult.Add(Result); } if ( INIFeatures == null ) { clsResult Result = new clsResult("feat.bjo"); ZipSearchResult = IOUtil.FindZipEntryFromPath(Path, GameFilesPath + "feat.bjo"); if ( ZipSearchResult == null ) { Result.WarningAdd("file not found"); } else { BinaryReader Features_Reader = new BinaryReader(ZipSearchResult.Stream); SubResult = Read_WZ_Features(Features_Reader, BJOUnits); Features_Reader.Close(); if ( !SubResult.Success ) { Result.WarningAdd(SubResult.Problem); } } ReturnResult.Add(Result); } if ( true ) { clsResult Result = new clsResult("ttypes.ttp"); ZipSearchResult = IOUtil.FindZipEntryFromPath(Path, GameFilesPath + "ttypes.ttp"); if ( ZipSearchResult == null ) { Result.WarningAdd("file not found"); } else { BinaryReader TileTypes_Reader = new BinaryReader(ZipSearchResult.Stream); SubResult = Read_WZ_TileTypes(TileTypes_Reader); TileTypes_Reader.Close(); if ( !SubResult.Success ) { Result.WarningAdd(SubResult.Problem); } } ReturnResult.Add(Result); } IniStructures INIStructures = null; ZipSearchResult = IOUtil.FindZipEntryFromPath(Path, GameFilesPath + "struct.ini"); if ( ZipSearchResult == null ) { } else { clsResult Result = new clsResult("struct.ini"); IniReader StructuresINI = new IniReader(); StreamReader StructuresINI_Reader = new StreamReader(ZipSearchResult.Stream); Result.Take(StructuresINI.ReadFile(StructuresINI_Reader)); StructuresINI_Reader.Close(); INIStructures = new IniStructures(StructuresINI.Sections.Count, this); Result.Take(StructuresINI.Translate(INIStructures)); ReturnResult.Add(Result); } if ( INIStructures == null ) { clsResult Result = new clsResult("struct.bjo"); ZipSearchResult = IOUtil.FindZipEntryFromPath(Path, GameFilesPath + "struct.bjo"); if ( ZipSearchResult == null ) { Result.WarningAdd("file not found"); } else { BinaryReader Structures_Reader = new BinaryReader(ZipSearchResult.Stream); SubResult = Read_WZ_Structures(Structures_Reader, BJOUnits); Structures_Reader.Close(); if ( !SubResult.Success ) { Result.WarningAdd(SubResult.Problem); } } ReturnResult.Add(Result); } IniDroids INIDroids = null; ZipSearchResult = IOUtil.FindZipEntryFromPath(Path, GameFilesPath + "droid.ini"); if ( ZipSearchResult == null ) { } else { clsResult Result = new clsResult("droid.ini"); IniReader DroidsINI = new IniReader(); StreamReader DroidsINI_Reader = new StreamReader(ZipSearchResult.Stream); Result.Take(DroidsINI.ReadFile(DroidsINI_Reader)); DroidsINI_Reader.Close(); INIDroids = new IniDroids(DroidsINI.Sections.Count, this); Result.Take(DroidsINI.Translate(INIDroids)); ReturnResult.Add(Result); } if ( INIDroids == null ) { clsResult Result = new clsResult("dinit.bjo"); ZipSearchResult = IOUtil.FindZipEntryFromPath(Path, GameFilesPath + "dinit.bjo"); if ( ZipSearchResult == null ) { Result.WarningAdd("file not found"); } else { BinaryReader Droids_Reader = new BinaryReader(ZipSearchResult.Stream); SubResult = Read_WZ_Droids(Droids_Reader, BJOUnits); Droids_Reader.Close(); if ( !SubResult.Success ) { Result.WarningAdd(SubResult.Problem); } } ReturnResult.Add(Result); } sCreateWZObjectsArgs CreateObjectsArgs = new sCreateWZObjectsArgs(); CreateObjectsArgs.BJOUnits = BJOUnits; CreateObjectsArgs.INIStructures = INIStructures; CreateObjectsArgs.INIDroids = INIDroids; CreateObjectsArgs.INIFeatures = INIFeatures; ReturnResult.Add(CreateWZObjects(CreateObjectsArgs)); //objects are modified by this and must already exist ZipSearchResult = IOUtil.FindZipEntryFromPath(Path, GameFilesPath + "labels.ini"); if ( ZipSearchResult == null ) { } else { clsResult Result = new clsResult("labels.ini"); IniReader LabelsINI = new IniReader(); StreamReader LabelsINI_Reader = new StreamReader(ZipSearchResult.Stream); Result.Take(LabelsINI.ReadFile(LabelsINI_Reader)); LabelsINI_Reader.Close(); Result.Take(Read_WZ_Labels(LabelsINI, false)); ReturnResult.Add(Result); } return ReturnResult; }
/// <summary> /// The computer's playing algorithm /// Determines where to play for the AI /// Possibly can be expanded upon to make a better AI /// (prioritizing corners or further considerations) /// /// Current Process: /// - Finds all possible moves /// - Give each move a rating depending on what skill it is /// - Counts how many tokens that can be lost next round for each move /// - Weighs the options using (rating - loss), higher being better /// - Keeps a list of the best option(s) /// - Picks a move from the list of best options and uses it /// </summary> /// <param name="filter">The list of accepted actions</param> /// <returns>the location of the "best" move</returns> public static Move Run(params int[] filter) { // Records the best option when measured by ( captured pieces - vulnerable pieces ) int best = 0; // Saves the board to refresh after checking int[] boardBackup = new int[100]; Battle.Field.Board.CopyTo(boardBackup, 0); Boolean couldMove = false; // Finds where the computer can move SimpleList<Move> moves = FindPossibleMoves(2); // Records the locations of the best choices SimpleList<Move> bestMoves = new SimpleList<Move>(); int hp = Battle.Player.Health; int hp2 = Battle.Foe.Health; Battle.ApEnabled(false); // Weigh each move according to the ( captured pieces - vulnerable pieces ) idea foreach (Move a in moves) { if (a.Action == 0) couldMove = true; // Apply the filter if (filter.Length != 0) { Boolean good = false; foreach (int i in filter) if (a.Action == i) good = true; if (!good) continue; } Battle.X = a.Location % 10; Battle.Y = a.Location / 10; // Get the rating of the skill Type type = Type.GetType(actionPrefix + actionNames[a.Action]); int c = (int)type.InvokeMember("Rate", BindingFlags.InvokeMethod, null, null, null); // Get how many tokens can be lost to the human type.InvokeMember("Perform", BindingFlags.InvokeMethod, null, null, null); int l = FindPotentialLoss(); Battle.ExtraTurns = 0; // Keep moves within 2 of the "best" and clear all old moves if the new move is much better if (c - l > best + 2 || bestMoves.Size == 0) { best = c - l; bestMoves.Clear(); bestMoves.Add(a); } else if (c - 1 >= best - 2) bestMoves.Add(a); // Refresh the board after checking the spot boardBackup.CopyTo(Battle.Field.Board, 0); } // Restore the hps back to what it was before the tests Battle.Player.Damage(Battle.Player.Health - hp); Battle.Foe.Damage(Battle.Foe.Health - hp2); Battle.ApEnabled(true); // If the computer found a best option, return it if (bestMoves.Size > 0 && couldMove) { Move bestMove = bestMoves[new Random().Next(0, bestMoves.Size)]; return bestMove; } return null; }
/// <summary> /// Shared Constructor /// </summary> /// <param name="s">default skill state</param> /// <param name="l">level</param> /// <param name="h">health</param> public Human(Boolean s, int l, int h) { level = l; health = h; maxHP = h; skills = new SimpleList<Boolean>(); for (int x = 0; x < 9; ++x) skills.Add(s); questItems = new SimpleList<QuestItem>(); }
public clsResult Load(string path) { var returnResult = new clsResult("Loading LND from \"{0}\"".Format2(path), false); logger.Info("Loading LND from \"{0}\"".Format2(path)); try { var strTemp = ""; var strTemp2 = ""; var X = 0; var Y = 0; var A = 0; var B = 0; var Tile_Num = 0; // SimpleList<string> LineData = default(SimpleList<string>); var Line_Num = 0; LNDTile[] LNDTile = null; var LNDObjects = new SimpleList<LNDObject>(); var UnitAdd = new clsUnitAdd(); UnitAdd.Map = map; var Reader = default(BinaryReader); try { Reader = new BinaryReader(new FileStream(path, FileMode.Open), App.UTF8Encoding); } catch ( Exception ex ) { returnResult.ProblemAdd(ex.Message); return returnResult; } var LineData = IOUtil.BytesToLinesRemoveComments(Reader); Reader.Close(); Array.Resize(ref LNDTile, LineData.Count); var strTemp3 = ""; var GotTiles = default(bool); var GotObjects = default(bool); var GotGates = default(bool); var GotTileTypes = default(bool); var LNDTileType = new byte[0]; var ObjectText = new string[11]; var GateText = new string[4]; var TileTypeText = new string[256]; var LNDTileTypeCount = 0; var LNDGates = new SimpleList<clsGateway>(); var Gateway = default(clsGateway); var C = 0; var D = 0; var GotText = default(bool); var FlipX = default(bool); var FlipZ = default(bool); byte Rotation = 0; var NewTileSize = new XYInt(); double dblTemp = 0; Line_Num = 0; while ( Line_Num < LineData.Count ) { strTemp = LineData[Line_Num]; A = strTemp.IndexOf("TileWidth ") + 1; if ( A == 0 ) { } A = strTemp.IndexOf("TileHeight ") + 1; if ( A == 0 ) { } A = strTemp.IndexOf("MapWidth ") + 1; if ( A == 0 ) { } else { IOUtil.InvariantParse(strTemp.Substring(strTemp.Length - (strTemp.Length - (A + 8)), strTemp.Length - (A + 8)), ref NewTileSize.X); goto LineDone; } A = strTemp.IndexOf("MapHeight ") + 1; if ( A == 0 ) { } else { IOUtil.InvariantParse(strTemp.Substring(strTemp.Length - (strTemp.Length - (A + 9)), strTemp.Length - (A + 9)), ref NewTileSize.Y); goto LineDone; } A = strTemp.IndexOf("Textures {") + 1; if ( A == 0 ) { } else { Line_Num++; strTemp = LineData[Line_Num]; strTemp2 = strTemp.ToLower(); if ( strTemp2.IndexOf("tertilesc1") + 1 > 0 ) { map.Tileset = App.Tileset_Arizona; } if ( strTemp2.IndexOf("tertilesc2") + 1 > 0 ) { map.Tileset = App.Tileset_Urban; } if ( strTemp2.IndexOf("tertilesc3") + 1 > 0 ) { map.Tileset = App.Tileset_Rockies; } goto LineDone; } A = strTemp.IndexOf("Tiles {") + 1; if ( A == 0 || GotTiles ) { } else { Line_Num++; while ( Line_Num < LineData.Count ) { strTemp = LineData[Line_Num]; A = strTemp.IndexOf("}") + 1; if ( A == 0 ) { A = strTemp.IndexOf("TID ") + 1; if ( A == 0 ) { returnResult.ProblemAdd("Tile ID missing"); return returnResult; } strTemp2 = strTemp.Substring(strTemp.Length - (strTemp.Length - A - 3), strTemp.Length - A - 3); A = strTemp2.IndexOf(" ") + 1; if ( A > 0 ) { strTemp2 = strTemp2.Substring(0, A - 1); } var temp_Result = LNDTile[Tile_Num].TID; IOUtil.InvariantParse(strTemp2, ref temp_Result); A = strTemp.IndexOf("VF ") + 1; if ( A == 0 ) { returnResult.ProblemAdd("Tile VF missing"); return returnResult; } strTemp2 = strTemp.Substring(strTemp.Length - (strTemp.Length - A - 2), strTemp.Length - A - 2); A = strTemp2.IndexOf(" ") + 1; if ( A > 0 ) { strTemp2 = strTemp2.Substring(0, A - 1); } var temp_Result2 = LNDTile[Tile_Num].VF; IOUtil.InvariantParse(strTemp2, ref temp_Result2); A = strTemp.IndexOf("TF ") + 1; if ( A == 0 ) { returnResult.ProblemAdd("Tile TF missing"); return returnResult; } strTemp2 = strTemp.Substring(strTemp.Length - (strTemp.Length - A - 2), strTemp.Length - A - 2); A = strTemp2.IndexOf(" ") + 1; if ( A > 0 ) { strTemp2 = strTemp2.Substring(0, A - 1); } var temp_Result3 = LNDTile[Tile_Num].TF; IOUtil.InvariantParse(strTemp2, ref temp_Result3); A = strTemp.IndexOf(" F ") + 1; if ( A == 0 ) { returnResult.ProblemAdd("Tile flip missing"); return returnResult; } strTemp2 = strTemp.Substring(strTemp.Length - A - 2, strTemp.Length - A - 2); A = strTemp2.IndexOf(" "); if ( A > 0 ) { strTemp2 = strTemp2.Substring(0, A); } var temp_Result4 = LNDTile[Tile_Num].F; IOUtil.InvariantParse(strTemp2, ref temp_Result4); A = strTemp.IndexOf(" VH ") + 1; if ( A == 0 ) { returnResult.ProblemAdd("Tile height is missing"); return returnResult; } strTemp3 = strTemp.Substring(strTemp.Length - (strTemp.Length - A - 3), strTemp.Length - A - 3); for ( A = 0; A <= 2; A++ ) { B = strTemp3.IndexOf(" ") + 1; if ( B == 0 ) { returnResult.ProblemAdd("A tile height value is missing"); return returnResult; } strTemp2 = strTemp3.Substring(0, B - 1); strTemp3 = strTemp3.Substring(strTemp3.Length - (strTemp3.Length - B), strTemp3.Length - B); if ( A == 0 ) { var temp_Result5 = LNDTile[Tile_Num].Vertex0Height; IOUtil.InvariantParse(strTemp2, ref temp_Result5); } else if ( A == 1 ) { var temp_Result6 = LNDTile[Tile_Num].Vertex1Height; IOUtil.InvariantParse(strTemp2, ref temp_Result6); } else if ( A == 2 ) { var temp_Result7 = LNDTile[Tile_Num].Vertex2Height; IOUtil.InvariantParse(strTemp2, ref temp_Result7); } } var temp_Result8 = LNDTile[Tile_Num].Vertex3Height; IOUtil.InvariantParse(strTemp3, ref temp_Result8); Tile_Num++; } else { GotTiles = true; goto LineDone; } Line_Num++; } GotTiles = true; goto LineDone; } A = strTemp.IndexOf("Objects {") + 1; if ( A == 0 || GotObjects ) { } else { Line_Num++; while ( Line_Num < LineData.Count ) { strTemp = LineData[Line_Num]; A = strTemp.IndexOf("}") + 1; if ( A == 0 ) { C = 0; ObjectText[0] = ""; GotText = false; for ( B = 0; B <= strTemp.Length - 1; B++ ) { if ( strTemp[B] != ' ' && strTemp[B] != '\t' ) { GotText = true; ObjectText[C] += strTemp[B].ToString(); } else { if ( GotText ) { C++; if ( C == 11 ) { returnResult.ProblemAdd("Too many fields for an object, or a space at the end."); return returnResult; } ObjectText[C] = ""; GotText = false; } } } var NewObject = new LNDObject(); IOUtil.InvariantParse(ObjectText[0], ref NewObject.ID); IOUtil.InvariantParse(ObjectText[1], ref NewObject.TypeNum); NewObject.Code = ObjectText[2].Substring(1, ObjectText[2].Length - 2); //remove quotes IOUtil.InvariantParse(ObjectText[3], ref NewObject.PlayerNum); NewObject.Name = ObjectText[4].Substring(1, ObjectText[4].Length - 2); //remove quotes IOUtil.InvariantParse(ObjectText[5], ref NewObject.Pos.X); IOUtil.InvariantParse(ObjectText[6], ref NewObject.Pos.Y); IOUtil.InvariantParse(ObjectText[7], ref NewObject.Pos.Z); if ( IOUtil.InvariantParse(ObjectText[8], ref dblTemp) ) { NewObject.Rotation.X = (int)(MathUtil.Clamp_dbl(dblTemp, 0.0D, 359.0D)); } if ( IOUtil.InvariantParse(ObjectText[9], ref dblTemp) ) { NewObject.Rotation.Y = (int)(MathUtil.Clamp_dbl(dblTemp, 0.0D, 359.0D)); } if ( IOUtil.InvariantParse(ObjectText[10], ref dblTemp) ) { NewObject.Rotation.Z = (int)(MathUtil.Clamp_dbl(dblTemp, 0.0D, 359.0D)); } LNDObjects.Add(NewObject); } else { GotObjects = true; goto LineDone; } Line_Num++; } GotObjects = true; goto LineDone; } A = strTemp.IndexOf("Gates {") + 1; if ( A == 0 || GotGates ) { } else { Line_Num++; while ( Line_Num < LineData.Count ) { strTemp = LineData[Line_Num]; A = strTemp.IndexOf("}") + 1; if ( A == 0 ) { C = 0; GateText[0] = ""; GotText = false; for ( B = 0; B <= strTemp.Length - 1; B++ ) { if ( strTemp[B] != ' ' && strTemp[B] != '\t' ) { GotText = true; GateText[C] += strTemp[B].ToString(); } else { if ( GotText ) { C++; if ( C == 4 ) { returnResult.ProblemAdd("Too many fields for a gateway, or a space at the end."); return returnResult; } GateText[C] = ""; GotText = false; } } } Gateway = new clsGateway(); IOUtil.InvariantParse(GateText[0], ref Gateway.PosA.X); Gateway.PosA.X = Math.Max(Gateway.PosA.X, 0); IOUtil.InvariantParse(GateText[1], ref Gateway.PosA.Y); Gateway.PosA.Y = Math.Max(Gateway.PosA.Y, 0); IOUtil.InvariantParse(GateText[2], ref Gateway.PosB.X); Gateway.PosB.X = Math.Max(Gateway.PosB.X, 0); IOUtil.InvariantParse(GateText[3], ref Gateway.PosB.Y); Gateway.PosB.Y = Math.Max(Gateway.PosB.Y, 0); LNDGates.Add(Gateway); } else { GotGates = true; goto LineDone; } Line_Num++; } GotGates = true; goto LineDone; } A = strTemp.IndexOf("Tiles {") + 1; if ( A == 0 || GotTileTypes || !GotTiles ) { } else { Line_Num++; while ( Line_Num < LineData.Count ) { strTemp = LineData[Line_Num]; A = strTemp.IndexOf("}") + 1; if ( A == 0 ) { C = 0; TileTypeText[0] = ""; GotText = false; for ( B = 0; B <= strTemp.Length - 1; B++ ) { if ( strTemp[B] != ' ' && strTemp[B] != '\t' ) { GotText = true; TileTypeText[C] += strTemp[B].ToString(); } else { if ( GotText ) { C++; if ( C == 256 ) { returnResult.ProblemAdd("Too many fields for tile types."); return returnResult; } TileTypeText[C] = ""; GotText = false; } } } if ( TileTypeText[C] == "" || TileTypeText[C] == " " ) { C--; } for ( D = 0; D <= C; D++ ) { Array.Resize(ref LNDTileType, LNDTileTypeCount + 1); LNDTileType[LNDTileTypeCount] = Math.Min(byte.Parse(TileTypeText[D]), (byte)11); LNDTileTypeCount++; } } else { GotTileTypes = true; goto LineDone; } Line_Num++; } GotTileTypes = true; } LineDone: Line_Num++; } Array.Resize(ref LNDTile, Tile_Num); map.SetPainterToDefaults(); if ( NewTileSize.X < 1 | NewTileSize.Y < 1 ) { returnResult.ProblemAdd("The LND\'s terrain dimensions are missing or invalid."); return returnResult; } map.TerrainBlank(NewTileSize); map.TileType_Reset(); for ( Y = 0; Y <= map.Terrain.TileSize.Y - 1; Y++ ) { for ( X = 0; X <= map.Terrain.TileSize.X - 1; X++ ) { Tile_Num = Y * map.Terrain.TileSize.X + X; //lnd uses different order! (3 = 2, 2 = 3), this program goes left to right, lnd goes clockwise around each tile map.Terrain.Vertices[X, Y].Height = (byte)(LNDTile[Tile_Num].Vertex0Height); } } for ( Y = 0; Y <= map.Terrain.TileSize.Y - 1; Y++ ) { for ( X = 0; X <= map.Terrain.TileSize.X - 1; X++ ) { Tile_Num = Y * map.Terrain.TileSize.X + X; map.Terrain.Tiles[X, Y].Texture.TextureNum = LNDTile[Tile_Num].TID - 1; //ignore higher values A = Convert.ToInt32((LNDTile[Tile_Num].F / 64.0D)); LNDTile[Tile_Num].F = (short)(LNDTile[Tile_Num].F - A * 64); A = (int)((LNDTile[Tile_Num].F / 16.0D)); LNDTile[Tile_Num].F = (short)(LNDTile[Tile_Num].F - A * 16); if ( A < 0 | A > 3 ) { returnResult.ProblemAdd("Invalid flip value."); return returnResult; } Rotation = (byte)A; A = (int)((LNDTile[Tile_Num].F / 8.0D)); LNDTile[Tile_Num].F -= (short)(A * 8); FlipZ = A == 1; A = (int)((LNDTile[Tile_Num].F / 4.0D)); LNDTile[Tile_Num].F -= (short)(A * 4); FlipX = A == 1; A = Convert.ToInt32((LNDTile[Tile_Num].F / 2.0D)); LNDTile[Tile_Num].F -= (short)(A * 2); map.Terrain.Tiles[X, Y].Tri = A == 1; //vf, tf, ignore TileUtil.OldOrientation_To_TileOrientation(Rotation, FlipX, FlipZ, ref map.Terrain.Tiles[X, Y].Texture.Orientation); } } var newUnit = default(clsUnit); var xyzInt = new XYZInt(0, 0, 0); var newTypeBase = default(UnitTypeBase); UInt32 availableID = 0; availableID = 1U; foreach ( var currentObject in LNDObjects ) { if ( currentObject.ID >= availableID ) { availableID = currentObject.ID + 1U; } } foreach ( var currentObject in LNDObjects ) { switch ( currentObject.TypeNum ) { case 0: newTypeBase = App.ObjectData.FindOrCreateUnitType(currentObject.Code, UnitType.Feature, -1); break; case 1: newTypeBase = App.ObjectData.FindOrCreateUnitType(currentObject.Code, UnitType.PlayerStructure, -1); break; case 2: newTypeBase = App.ObjectData.FindOrCreateUnitType(currentObject.Code, UnitType.PlayerDroid, -1); break; default: newTypeBase = null; break; } if ( newTypeBase != null ) { newUnit = new clsUnit(); newUnit.TypeBase = newTypeBase; if ( currentObject.PlayerNum < 0 | currentObject.PlayerNum >= Constants.PlayerCountMax ) { newUnit.UnitGroup = map.ScavengerUnitGroup; } else { newUnit.UnitGroup = map.UnitGroups[currentObject.PlayerNum]; } xyzInt.X = (int)currentObject.Pos.X; xyzInt.Y = (int)currentObject.Pos.Y; xyzInt.Z = (int)currentObject.Pos.Z; newUnit.Pos = mapPos_From_LNDPos(xyzInt); newUnit.Rotation = currentObject.Rotation.Y; if ( currentObject.ID == 0U ) { currentObject.ID = availableID; App.ZeroIDWarning(newUnit, currentObject.ID, returnResult); } UnitAdd.NewUnit = newUnit; UnitAdd.ID = currentObject.ID; UnitAdd.Perform(); App.ErrorIDChange(currentObject.ID, newUnit, "Load_LND"); if ( availableID == currentObject.ID ) { availableID = newUnit.ID + 1U; } } } foreach ( var tempLoopVar_Gateway in LNDGates ) { Gateway = tempLoopVar_Gateway; map.GatewayCreate(Gateway.PosA, Gateway.PosB); } if ( map.Tileset != null ) { for ( A = 0; A <= Math.Min(LNDTileTypeCount - 1, map.Tileset.TileCount) - 1; A++ ) { map.Tile_TypeNum[A] = LNDTileType[A + 1]; //lnd value 0 is ignored } } } catch ( Exception ex ) { returnResult.ProblemAdd(ex.Message); return returnResult; } return returnResult; }
/// <summary> /// Constructor for a new player /// </summary> public Human(int file) : this(false, 1, Constants.IntValue("playerHealthBonus") + Constants.IntValue("playerHealthPerLevel")) { money = Constants.IntValue("playerStartMoney"); inventory = Consumable.EmptyInventory; seeds = new SimpleList<int>(); Random random = new Random(); seeds.Add(random.Next()); seeds.Add(random.Next()); area = 1; this.saveFile = file; }
public void RedoPerform() { clsUndo ThisUndo = default(clsUndo); ThisUndo = Undos[UndoPosition]; sXY_int SectorNum = new sXY_int(); clsShadowSector CurrentSector = default(clsShadowSector); clsShadowSector UndoSector = default(clsShadowSector); SimpleList<clsShadowSector> NewSectorsForThisUndo = new SimpleList<clsShadowSector>(); foreach ( clsShadowSector tempLoopVar_UndoSector in ThisUndo.ChangedSectors ) { UndoSector = tempLoopVar_UndoSector; SectorNum = UndoSector.Num; //store existing state for undo CurrentSector = ShadowSectors[SectorNum.X, SectorNum.Y]; //remove graphics from sector Sectors[SectorNum.X, SectorNum.Y].DeleteLists(); //perform the redo Undo_Sector_Rejoin(UndoSector); //update the backup ShadowSector_Create(SectorNum); //add old state to the undo step (that was this redo step) NewSectorsForThisUndo.Add(CurrentSector); //prepare to update graphics on this sector SectorGraphicsChanges.Changed(SectorNum); } ThisUndo.ChangedSectors = NewSectorsForThisUndo; UInt32 ID = 0; clsUnitAdd UnitAdd = new clsUnitAdd(); UnitAdd.Map = this; clsUnit Unit = default(clsUnit); for ( int A = 0; A <= ThisUndo.UnitChanges.Count - 1; A++ ) //forward order is important { Unit = ThisUndo.UnitChanges[A].Unit; if ( ThisUndo.UnitChanges[A].Type == clsUnitChange.enumType.Added ) { //add the unit back on to the map ID = Unit.ID; UnitAdd.ID = ID; UnitAdd.NewUnit = Unit; UnitAdd.Perform(); App.ErrorIDChange(ID, Unit, "Redo_Perform"); } else if ( ThisUndo.UnitChanges[A].Type == clsUnitChange.enumType.Deleted ) { //remove the unit from the map UnitRemove(Unit.MapLink.ArrayPosition); } else { Debugger.Break(); } } clsGatewayChange GatewayChange = default(clsGatewayChange); for ( int A = 0; A <= ThisUndo.GatewayChanges.Count - 1; A++ ) //forward order is important { GatewayChange = ThisUndo.GatewayChanges[A]; switch ( GatewayChange.Type ) { case clsGatewayChange.enumType.Added: //add the unit back on to the map GatewayChange.Gateway.MapLink.Connect(Gateways); break; case clsGatewayChange.enumType.Deleted: //remove the unit from the map GatewayChange.Gateway.MapLink.Disconnect(); break; default: Debugger.Break(); break; } } UndoPosition++; SectorsUpdateGraphics(); MinimapMakeLater(); Program.frmMainInstance.SelectedObject_Changed(); }
/// <summary> /// Generates the rooms using the seed /// </summary> public void Generate() { this.id = human.area; // Set the size (in rooms) for the world Console.WriteLine("Choosing sizes..."); Random generation = new Random(seed); length = generation.Next( id / Constants.IntValue("mapSizeDivisor") + Constants.IntValue("mapSizeBonusMin"), id / Constants.IntValue("mapSizeDivisor") + Constants.IntValue("mapSizeBonusMax")); width = generation.Next( id / Constants.IntValue("mapSizeDivisor") + Constants.IntValue("mapSizeBonusMin"), id / Constants.IntValue("mapSizeDivisor") + Constants.IntValue("mapSizeBonusMax")); rooms = new _2DRoomList(); int finishRoom = generation.Next(0, length); int[] roomLengths = new int[length]; for (int i = 0; i < length; ++i) roomLengths[i] = generation.Next(11, 33); Console.WriteLine("Generating Rooms..."); // Create all of the rooms with random templates for (int y = 0; y < width; ++y) { // Randomize the column width int roomWidth = generation.Next(7, 13); for (int x = 0; x < length; ++x) { // Randomize the type int type = generation.Next(); // Get the room layout with the new parameters char[,] tiles = Template.CreateRoom(type, roomLengths[x], roomWidth); int halfWidth = roomWidth / 2; int halfLength = roomLengths[x] / 2; // Set the paths between rooms if (x != 0) { tiles[0, halfWidth - 1] = Convert(tiles[0, halfWidth - 1], 4); tiles[0, halfWidth + 1] = Convert(tiles[0, halfWidth + 1], 5); tiles[0, halfWidth] = ' '; } if (y != 0) { tiles[halfLength - 1, 0] = Convert(tiles[halfLength - 1, 0], 0); tiles[halfLength + 1, 0] = Convert(tiles[halfLength + 1, 0], 1); tiles[halfLength, 0] = ' '; } if (x != length - 1) { tiles[roomLengths[x] - 1, halfWidth - 1] = Convert(tiles[roomLengths[x] - 1, halfWidth - 1], 6); tiles[roomLengths[x] - 1, halfWidth + 1] = Convert(tiles[roomLengths[x] - 1, halfWidth + 1], 7); tiles[roomLengths[x] - 1, halfWidth] = ' '; } if (y != width - 1 || x == finishRoom) { tiles[halfLength - 1, roomWidth - 1] = Convert(tiles[halfLength - 1, roomWidth - 1], 2); tiles[halfLength + 1, roomWidth - 1] = Convert(tiles[halfLength + 1, roomWidth - 1], 3); tiles[halfLength, roomWidth - 1] = ' '; } // Add the room to the array rooms.Add(new Room(roomLengths[x], roomWidth, tiles)); // Place the human within the first room if (x + y == 0) human.Position = new int[] { 1, roomWidth / 2 }; } } pathing.Map = this; Console.WriteLine("Arranging rooms..."); rooms.Arrange(length, width); Console.WriteLine("Adding enemies..."); // Add enemies to the map for (int x = 0; x < length; ++x) for (int y = 0; y < width; ++y) { if (x == 0 && y == 0) continue; currentRoom[0] = x; currentRoom[1] = y; int enemyCount = random.Next(Constants.IntValue("mapEnemyMin"), Constants.IntValue("mapEnemyMax") + 1); for (int i = 0; i < enemyCount; ++i) { Minion enemy = new Minion(id); do { enemy.Position = pathing.GetAvailablePosition(new int[] {1, CurrentRoom.VerticalSize / 2}); enemy.Room = new int[] { x, y }; } while (enemyList.Contains(enemy)); enemyList.Add(enemy); } Console.WriteLine(" Room " + (length * y + x)); } Console.WriteLine("Loading Quest Items..."); SimpleList<int[]> takenRooms = new SimpleList<int[]>(); // Place the associated quest items in the map foreach (QuestItem item in human.QuestItems) { if (item.Area == id) { Boolean taken; do { taken = false; currentRoom[0] = generation.Next(0, length); currentRoom[1] = generation.Next(0, width); foreach (int[] spot in takenRooms) if (currentRoom[0] == spot[0] && currentRoom[1] == spot[1]) taken = true; } while (currentRoom[0] + currentRoom[1] == 0 || taken); takenRooms.Add(new int[] { currentRoom[0], currentRoom[1] }); int[] tile = pathing.GetAvailablePosition(new int[] {1, rooms[currentRoom[0], currentRoom[1]].VerticalSize / 2}); item.Location = new int[] { currentRoom[0], currentRoom[1], tile[0], tile[1] }; } } currentRoom[0] = 0; currentRoom[1] = 0; }
public void MapInsert(clsMap MapToInsert, sXY_int Offset, sXY_int Area, bool InsertHeights, bool InsertTextures, bool InsertUnits, bool DeleteUnits, bool InsertGateways, bool DeleteGateways) { sXY_int Finish = new sXY_int(); int X = 0; int Y = 0; sXY_int SectorStart = new sXY_int(); sXY_int SectorFinish = new sXY_int(); sXY_int AreaAdjusted = new sXY_int(); sXY_int SectorNum = new sXY_int(); Finish.X = Math.Min(Offset.X + Math.Min(Area.X, MapToInsert.Terrain.TileSize.X), Terrain.TileSize.X); Finish.Y = Math.Min(Offset.Y + Math.Min(Area.Y, MapToInsert.Terrain.TileSize.Y), Terrain.TileSize.Y); AreaAdjusted.X = Finish.X - Offset.X; AreaAdjusted.Y = Finish.Y - Offset.Y; GetTileSectorRange(new sXY_int(Offset.X - 1, Offset.Y - 1), Finish, ref SectorStart, ref SectorFinish); for ( Y = SectorStart.Y; Y <= SectorFinish.Y; Y++ ) { SectorNum.Y = Y; for ( X = SectorStart.X; X <= SectorFinish.X; X++ ) { SectorNum.X = X; SectorGraphicsChanges.Changed(SectorNum); SectorUnitHeightsChanges.Changed(SectorNum); SectorTerrainUndoChanges.Changed(SectorNum); } } if ( InsertHeights ) { for ( Y = 0; Y <= AreaAdjusted.Y; Y++ ) { for ( X = 0; X <= AreaAdjusted.X; X++ ) { Terrain.Vertices[Offset.X + X, Offset.Y + Y].Height = MapToInsert.Terrain.Vertices[X, Y].Height; } } for ( Y = 0; Y <= AreaAdjusted.Y - 1; Y++ ) { for ( X = 0; X <= AreaAdjusted.X - 1; X++ ) { Terrain.Tiles[Offset.X + X, Offset.Y + Y].Tri = MapToInsert.Terrain.Tiles[X, Y].Tri; } } } if ( InsertTextures ) { for ( Y = 0; Y <= AreaAdjusted.Y; Y++ ) { for ( X = 0; X <= AreaAdjusted.X; X++ ) { Terrain.Vertices[Offset.X + X, Offset.Y + Y].Terrain = MapToInsert.Terrain.Vertices[X, Y].Terrain; } } bool TriDirection = default(bool); for ( Y = 0; Y <= AreaAdjusted.Y - 1; Y++ ) { for ( X = 0; X <= AreaAdjusted.X - 1; X++ ) { TriDirection = Terrain.Tiles[Offset.X + X, Offset.Y + Y].Tri; Terrain.Tiles[Offset.X + X, Offset.Y + Y].Copy(MapToInsert.Terrain.Tiles[X, Y]); Terrain.Tiles[Offset.X + X, Offset.Y + Y].Tri = TriDirection; } } for ( Y = 0; Y <= AreaAdjusted.Y; Y++ ) { for ( X = 0; X <= AreaAdjusted.X - 1; X++ ) { Terrain.SideH[Offset.X + X, Offset.Y + Y].Road = MapToInsert.Terrain.SideH[X, Y].Road; } } for ( Y = 0; Y <= AreaAdjusted.Y - 1; Y++ ) { for ( X = 0; X <= AreaAdjusted.X; X++ ) { Terrain.SideV[Offset.X + X, Offset.Y + Y].Road = MapToInsert.Terrain.SideV[X, Y].Road; } } } sXY_int LastTile = new sXY_int(); LastTile = Finish; LastTile.X--; LastTile.Y--; if ( DeleteGateways ) { int A = 0; A = 0; while ( A < Gateways.Count ) { if ( Gateways[A].PosA.IsInRange(Offset, LastTile) || Gateways[A].PosB.IsInRange(Offset, LastTile) ) { GatewayRemoveStoreChange(A); } else { A++; } } } if ( InsertGateways ) { sXY_int GateStart = new sXY_int(); sXY_int GateFinish = new sXY_int(); clsGateway Gateway = default(clsGateway); foreach ( clsGateway tempLoopVar_Gateway in MapToInsert.Gateways ) { Gateway = tempLoopVar_Gateway; GateStart.X = Offset.X + Gateway.PosA.X; GateStart.Y = Offset.Y + Gateway.PosA.Y; GateFinish.X = Offset.X + Gateway.PosB.X; GateFinish.Y = Offset.Y + Gateway.PosB.Y; if ( GateStart.IsInRange(Offset, LastTile) || GateFinish.IsInRange(Offset, LastTile) ) { GatewayCreateStoreChange(GateStart, GateFinish); } } } if ( DeleteUnits ) { SimpleList<clsUnit> UnitsToDelete = new SimpleList<clsUnit>(); int UnitToDeleteCount = 0; clsUnit Unit = default(clsUnit); for ( Y = SectorStart.Y; Y <= SectorFinish.Y; Y++ ) { for ( X = SectorStart.X; X <= SectorFinish.X; X++ ) { clsUnitSectorConnection Connection = default(clsUnitSectorConnection); foreach ( clsUnitSectorConnection tempLoopVar_Connection in Sectors[X, Y].Units ) { Connection = tempLoopVar_Connection; Unit = Connection.Unit; if ( App.PosIsWithinTileArea(Unit.Pos.Horizontal, Offset, Finish) ) { UnitsToDelete.Add(Unit); } } } } foreach ( clsUnit tempLoopVar_Unit in UnitsToDelete ) { Unit = tempLoopVar_Unit; if ( Unit.MapLink.IsConnected ) //units may be in the list multiple times and already be deleted { UnitRemoveStoreChange(Unit.MapLink.ArrayPosition); } } } if ( InsertUnits ) { sXY_int PosDif = new sXY_int(); clsUnit NewUnit = default(clsUnit); clsUnit Unit = default(clsUnit); sXY_int ZeroPos = new sXY_int(0, 0); clsUnitAdd UnitAdd = new clsUnitAdd(); UnitAdd.Map = this; UnitAdd.StoreChange = true; PosDif.X = Offset.X * App.TerrainGridSpacing; PosDif.Y = Offset.Y * App.TerrainGridSpacing; foreach ( clsUnit tempLoopVar_Unit in MapToInsert.Units ) { Unit = tempLoopVar_Unit; if ( App.PosIsWithinTileArea(Unit.Pos.Horizontal, ZeroPos, AreaAdjusted) ) { NewUnit = new clsUnit(Unit, this); NewUnit.Pos.Horizontal.X += PosDif.X; NewUnit.Pos.Horizontal.Y += PosDif.Y; UnitAdd.NewUnit = NewUnit; UnitAdd.Label = Unit.Label; UnitAdd.Perform(); } } } SectorsUpdateGraphics(); SectorsUpdateUnitHeights(); MinimapMakeLater(); }
/// <summary> /// Moves the enemy at each tick /// </summary> public void Tick() { // Do not move enemies if masking dew is active if (human.dewSteps > 0) return; SimpleList<int[]> occupiedPositions = new SimpleList<int[]>(); SimpleList<Minion> expired = new SimpleList<Minion>(); foreach (Minion minion in enemyList) { // If the enemy is in the same room, move it and check if it reached the player if (minion.Room[0] == currentRoom[0] && minion.Room[1] == currentRoom[1]) { int[] offset = Offset(minion.Room[0], minion.Room[1]); // If the minion doesn't have a list of moves already, give it one if (minion.Moves.Empty()) minion.Moves = pathing.GetMoves(new int[] { minion.Position[0] + offset[0], minion.Position[1] + offset[1] }, human.Position); // Get the next move int[] m = minion.Moves.Pop(); Boolean occupied = false; // If the spot is taken, backtrack to the original position foreach (int[] spot in occupiedPositions) if (spot[0] == m[0] && spot[1] == m[1]) { occupied = true; minion.Moves.Push(m); break; } if (occupied) { occupiedPositions.Add(minion.Position); continue; } // Else, take the position minion.Position = m; occupiedPositions.Add(minion.Position); // If that was the last move, the player has been reached so a battle begins if (minion.Moves.NearEmpty()) { expired.Add(minion); Encounter(minion); break; } } /* else { if (Math.Abs(minion.Room[0] - currentRoom[0]) > 1 || Math.Abs(minion.Room[1] - currentRoom[1]) > 1) continue; if (minion.Moves.empty()) { currentRoom.CopyTo(backup, 0); currentRoom[0] = minion.Room[0]; currentRoom[1] = minion.Room[1]; int[] target = pathing.GetAvailablePosition(minion.Position); minion.Moves = pathing.GetMoves(minion.Position, target); backup.CopyTo(currentRoom, 0); } minion.Position = minion.Moves.pop(); } */ } // Remove expired minions (ones that were battled) foreach (Minion minion in expired) enemyList.Remove(minion); // Update the display Refresh(); }