Merge pull request #27 from janavarro95/Development

Development
This commit is contained in:
janavarro95 2018-01-10 13:17:42 -08:00 committed by GitHub
commit 928df83457
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
51 changed files with 9157 additions and 291 deletions

View File

@ -8,5 +8,8 @@ namespace Omegasis.SaveAnywhere.Framework.Models
/// <summary>The saved character data.</summary> /// <summary>The saved character data.</summary>
public CharacterData[] Characters { get; set; } public CharacterData[] Characters { get; set; }
/// <summary>Checks if the character was swimming at save time.</summary>
public bool IsCharacterSwimming { get; set; }
} }
} }

View File

@ -3,5 +3,7 @@
namespace Omegasis.SaveAnywhere.Framework namespace Omegasis.SaveAnywhere.Framework
{ {
/// <summary>A marker subclass to detect when a custom save is in progress.</summary> /// <summary>A marker subclass to detect when a custom save is in progress.</summary>
internal class NewSaveGameMenu : SaveGameMenu { } internal class NewSaveGameMenu : SaveGameMenu {}
} }

View File

@ -13,7 +13,7 @@ namespace Omegasis.SaveAnywhere.Framework
** Properties ** Properties
*********/ *********/
/// <summary>The private field on the shipping menu which indicates the game has already been saved, which prevents it from saving.</summary> /// <summary>The private field on the shipping menu which indicates the game has already been saved, which prevents it from saving.</summary>
private readonly IPrivateField<bool> SavedYet; private readonly IReflectedField<bool> SavedYet;
/********* /*********
@ -25,7 +25,19 @@ namespace Omegasis.SaveAnywhere.Framework
public NewShippingMenu(List<Item> items, IReflectionHelper reflection) public NewShippingMenu(List<Item> items, IReflectionHelper reflection)
: base(items) : base(items)
{ {
this.SavedYet = reflection.GetPrivateField<bool>(this, "savedYet"); this.SavedYet = reflection.GetField<bool>(this, "savedYet");
}
/// <summary>
/// Overrides some base functionality of the shipping menu to enable proper closing.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="playSound"></param>
public override void receiveLeftClick(int x, int y, bool playSound = true)
{
if (this.okButton.containsPoint(x, y)) this.exitThisMenu(true);
base.receiveLeftClick(x, y, playSound);
} }
/// <summary>Updates the menu during the game's update loop.</summary> /// <summary>Updates the menu during the game's update loop.</summary>

View File

@ -84,7 +84,8 @@ namespace Omegasis.SaveAnywhere.Framework
PlayerData data = new PlayerData PlayerData data = new PlayerData
{ {
Time = Game1.timeOfDay, Time = Game1.timeOfDay,
Characters = this.GetPositions().ToArray() Characters = this.GetPositions().ToArray(),
IsCharacterSwimming = Game1.player.swimming
}; };
// save to disk // save to disk
@ -92,7 +93,7 @@ namespace Omegasis.SaveAnywhere.Framework
Directory.CreateDirectory(new FileInfo(this.SavePath).Directory.FullName); Directory.CreateDirectory(new FileInfo(this.SavePath).Directory.FullName);
this.Helper.WriteJsonFile(this.SavePath, data); this.Helper.WriteJsonFile(this.SavePath, data);
// clear any legacy data (no longer needed as backup) // clear any legacy data (no longer needed as backup)1
this.RemoveLegacyDataForThisPlayer(); this.RemoveLegacyDataForThisPlayer();
} }
@ -106,10 +107,31 @@ namespace Omegasis.SaveAnywhere.Framework
// apply // apply
Game1.timeOfDay = data.Time; Game1.timeOfDay = data.Time;
this.ResumeSwimming(data);
this.SetPositions(data.Characters); this.SetPositions(data.Characters);
this.OnLoaded?.Invoke(); this.OnLoaded?.Invoke();
} }
/// <summary>
/// Checks to see if the player was swimming when the game was saved and if so, resumes the swimming animation.
/// </summary>
/// <param name="data"></param>
public void ResumeSwimming(PlayerData data)
{
try
{
if (data.IsCharacterSwimming == true)
{
Game1.player.changeIntoSwimsuit();
Game1.player.swimming = true;
}
}
catch (Exception err)
{
//Here to allow compatability with old save files.
}
}
/********* /*********
** Private methods ** Private methods
@ -135,7 +157,7 @@ namespace Omegasis.SaveAnywhere.Framework
CharacterType? type = this.GetCharacterType(npc); CharacterType? type = this.GetCharacterType(npc);
if (type == null) if (type == null)
continue; continue;
if (npc == null || npc.currentLocation == null) continue;
string name = npc.name; string name = npc.name;
string map = npc.currentLocation.name; string map = npc.currentLocation.name;
Point tile = npc.getTileLocationPoint(); Point tile = npc.getTileLocationPoint();

View File

@ -31,6 +31,15 @@ namespace Omegasis.SaveAnywhere
private bool IsCustomSaving; private bool IsCustomSaving;
/// <summary>
/// Used to access the Mod's helper from other files associated with the mod.
/// </summary>
public static IModHelper ModHelper;
/// <summary>
/// Used to access the Mod's monitor to allow for debug logging in other files associated with the mod.
/// </summary>
public static IMonitor ModMonitor;
/********* /*********
** Public methods ** Public methods
*********/ *********/
@ -46,6 +55,8 @@ namespace Omegasis.SaveAnywhere
ControlEvents.KeyPressed += this.ControlEvents_KeyPressed; ControlEvents.KeyPressed += this.ControlEvents_KeyPressed;
GameEvents.UpdateTick += this.GameEvents_UpdateTick; GameEvents.UpdateTick += this.GameEvents_UpdateTick;
TimeEvents.AfterDayStarted += this.TimeEvents_AfterDayStarted; TimeEvents.AfterDayStarted += this.TimeEvents_AfterDayStarted;
ModHelper = helper;
ModMonitor = Monitor;
} }

View File

@ -61,7 +61,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RuneFactoryCropsMod", "Rune
{C5F88D48-EA20-40CD-91E2-C8725DC11795} = {C5F88D48-EA20-40CD-91E2-C8725DC11795} {C5F88D48-EA20-40CD-91E2-C8725DC11795} = {C5F88D48-EA20-40CD-91E2-C8725DC11795}
EndProjectSection EndProjectSection
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StarAI", "..\StarAI\StarAI\StarAI\StarAI.csproj", "{93632675-991D-425B-96F9-9C2B6BFC4EFE}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StarAI", "..\StarAI\StarAI\StarAI.csproj", "{93632675-991D-425B-96F9-9C2B6BFC4EFE}"
ProjectSection(ProjectDependencies) = postProject ProjectSection(ProjectDependencies) = postProject
{0756D36A-95C8-480D-8EA6-4584C03010C6} = {0756D36A-95C8-480D-8EA6-4584C03010C6} {0756D36A-95C8-480D-8EA6-4584C03010C6} = {0756D36A-95C8-480D-8EA6-4584C03010C6}
EndProjectSection EndProjectSection

View File

@ -1566,3 +1566,4 @@ namespace StardustCore
} }
} }

View File

@ -51,6 +51,7 @@
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Serialization\Serialization.cs" /> <Compile Include="Serialization\Serialization.cs" />
<Compile Include="Serialization\SerializerDataNode.cs" /> <Compile Include="Serialization\SerializerDataNode.cs" />
<Compile Include="StaticClass.cs" />
<Compile Include="Utilities.cs" /> <Compile Include="Utilities.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StardustCore
{
public static class StaticExtentions
{
/// <summary>
/// Thank you stack overflow. https://stackoverflow.com/questions/3907299/if-statements-matching-multiple-values
/// Ex:) if(1.In(1,2,3)) //This returns true since 1 is in the parameter list.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj">Object to pass in value.</param>
/// <param name="args">A list like (1,2,3) to see if it's contained.</param>
/// <returns></returns>
public static bool In<T>(this T obj, params T[] args)
{
return args.Contains(obj);
}
public static bool HasValue(this double value)
{
return !Double.IsNaN(value) && !Double.IsInfinity(value);
}
}
}

View File

@ -774,5 +774,149 @@ namespace StardustCore
} }
public static StardewValley.Object checkRadiusForObject(int radius, string name)
{
for (int x = -radius; x <= radius; x++)
{
for (int y = -radius; y <= radius; y++)
{
bool f = Game1.player.currentLocation.isObjectAt((Game1.player.getTileX() + x) * Game1.tileSize, (Game1.player.getTileY() + y) * Game1.tileSize);
if (f == false) continue;
StardewValley.Object obj = Game1.player.currentLocation.getObjectAt((Game1.player.getTileX() + x) * Game1.tileSize, (Game1.player.getTileY() + y) * Game1.tileSize);
if (obj == null) continue;
if (obj.name == name)
{
return obj;
}
}
}
return null;
}
public static StardewValley.Object checkCardinalForObject(string name)
{
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
if (x == -1 && y == -1) continue; //upper left
if (x == -1 && y == 1) continue; //bottom left
if (x == 1 && y == -1) continue; //upper right
if (x == 1 && y == 1) continue; //bottom right
bool f = Game1.player.currentLocation.isObjectAt((Game1.player.getTileX() + x) * Game1.tileSize, (Game1.player.getTileY() + y) * Game1.tileSize);
if (f == false) continue;
StardewValley.Object obj = Game1.player.currentLocation.getObjectAt((Game1.player.getTileX() + x) * Game1.tileSize, (Game1.player.getTileY() + y) * Game1.tileSize);
if (obj == null) continue;
if (obj.name == name)
{
return obj;
}
}
}
return null;
}
public static void faceDirectionTowardsSomething(Vector2 tileLocation)
{
if (tileLocation.X < Game1.player.getTileX())
{
Game1.player.faceDirection(3);
}
else if (tileLocation.X > Game1.player.getTileX())
{
Game1.player.faceDirection(1);
}
else if (tileLocation.Y < Game1.player.getTileY())
{
Game1.player.faceDirection(0);
}
else if (tileLocation.Y > Game1.player.getTileY())
{
Game1.player.faceDirection(2);
}
}
public static bool doesLocationContainObject(GameLocation location, string name)
{
foreach (var v in location.objects)
{
if (name == v.Value.name) return true;
}
return false;
}
public static KeyValuePair<Vector2,TerrainFeature> checkRadiusForTerrainFeature(int radius, Type terrainType)
{
for (int x = -radius; x <= radius; x++)
{
for (int y = -radius; y <= radius; y++)
{
Vector2 pos = new Vector2((Game1.player.getTileX() + x), (Game1.player.getTileY() + y));
bool f = Game1.player.currentLocation.isTerrainFeatureAt((int)pos.X,(int)pos.Y);
if (f == false) continue;
TerrainFeature t = Game1.player.currentLocation.terrainFeatures[pos]; //((Game1.player.getTileX() + x) * Game1.tileSize, (Game1.player.getTileY() + y) * Game1.tileSize);
if (t == null) continue;
if (t.GetType() == terrainType)
{
return new KeyValuePair<Vector2, TerrainFeature> (pos,t);
}
}
}
return new KeyValuePair<Vector2, TerrainFeature>(new Vector2(),null);
}
public static KeyValuePair<Vector2, TerrainFeature> checkCardinalForTerrainFeature(Type terrainType)
{
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
if (x == -1 && y == -1) continue; //upper left
if (x == -1 && y == 1) continue; //bottom left
if (x == 1 && y == -1) continue; //upper right
if (x == 1 && y == 1) continue; //bottom right
Vector2 pos = new Vector2((Game1.player.getTileX() + x), (Game1.player.getTileY() + y));
bool f = Game1.player.currentLocation.isTerrainFeatureAt((int)pos.X, (int)pos.Y);
if (f == false) continue;
TerrainFeature t = Game1.player.currentLocation.terrainFeatures[pos]; //((Game1.player.getTileX() + x) * Game1.tileSize, (Game1.player.getTileY() + y) * Game1.tileSize);
if (t == null) continue;
if (t.GetType() == terrainType)
{
return new KeyValuePair<Vector2, TerrainFeature>(pos, t);
}
}
}
return new KeyValuePair<Vector2, TerrainFeature>(new Vector2(), null);
}
public static bool doesLocationContainTerrainFeature(GameLocation location, Type terrain)
{
foreach (var v in location.terrainFeatures)
{
if (terrain == v.Value.GetType()) return true;
}
return false;
}
public static Item getItemFromInventory(int index)
{
foreach(var v in Game1.player.items)
{
if (v.parentSheetIndex == index) return v;
}
return null;
}
public static Item getItemFromInventory(string name)
{
foreach (var v in Game1.player.items)
{
if (v.Name == name) return v;
}
return null;
}
} }
} }

View File

@ -0,0 +1,38 @@
using Microsoft.Xna.Framework;
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.CheatCore
{
class DoorsToWarps
{
public static void makeAllDoorsWarps()
{
foreach(var v in Game1.locations)
{
foreach(var door in v.doors)
{
// ModCore.CoreMonitor.Log(v.name.ToString());
// ModCore.CoreMonitor.Log(door.Key.ToString());
// ModCore.CoreMonitor.Log(door.Value);
foreach(var warp in Game1.getLocationFromName(door.Value).warps)
{
if (warp.TargetName == v.name && warp.TargetX==door.Key.X&& warp.TargetY==door.Key.Y+1)
{
Warp w = new Warp(door.Key.X, door.Key.Y, door.Value, warp.X, warp.Y - 1,false);
v.warps.Add(w);
ModCore.CoreMonitor.Log("Star AI: Cheat Core: Adding warp on door at:" + door.Value + " " + new Vector2(door.Key.X, door.Key.Y));
}
}
}
}
}
}
}

View File

@ -10,6 +10,11 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using StarAI; using StarAI;
using StarAI.PathFindingCore.WaterLogic;
using StarAI.TaskCore.MapTransitionLogic;
using StarAI.TaskCore;
using StarAI.TaskCore.CropLogic;
using StarAI.TaskCore.DebrisLogic;
namespace StarAI namespace StarAI
{ {
@ -21,83 +26,315 @@ namespace StarAI
ModCore.CoreHelper.ConsoleCommands.Add("hello", "Ok?", new Action<string, string[]>(hello)); ModCore.CoreHelper.ConsoleCommands.Add("hello", "Ok?", new Action<string, string[]>(hello));
ModCore.CoreHelper.ConsoleCommands.Add("pathfind", "pathy?", new Action<string, string[]>(Commands.pathfind)); ModCore.CoreHelper.ConsoleCommands.Add("pathfind", "pathy?", new Action<string, string[]>(Commands.pathfind));
ModCore.CoreHelper.ConsoleCommands.Add("pathfinding", "pathy?", new Action<string, string[]>(Commands.pathfind)); ModCore.CoreHelper.ConsoleCommands.Add("pathfinding", "pathy?", new Action<string, string[]>(Commands.pathfind));
ModCore.CoreHelper.ConsoleCommands.Add("Execute", "Run tasks", new Action<string,string[]>(Commands.runTasks)); ModCore.CoreHelper.ConsoleCommands.Add("Execute", "Run tasks", new Action<string, string[]>(Commands.runTasks));
//ModCore.CoreHelper.ConsoleCommands.Add("execute", "Run tasks", new Action<string, string[]>(Commands.runTasks)); //ModCore.CoreHelper.ConsoleCommands.Add("execute", "Run tasks", new Action<string, string[]>(Commands.runTasks));
ModCore.CoreHelper.ConsoleCommands.Add("runTasks", "Run tasks", new Action<string, string[]>(Commands.runTasks)); ModCore.CoreHelper.ConsoleCommands.Add("runTasks", "Run tasks", new Action<string, string[]>(Commands.runTasks));
ModCore.CoreHelper.ConsoleCommands.Add("Water", "Water the crops", new Action<string, string[]>(Commands.waterCrops)); ModCore.CoreHelper.ConsoleCommands.Add("Water", "Water the crops", new Action<string, string[]>(Commands.waterCrops));
ModCore.CoreHelper.ConsoleCommands.Add("Harvest", "Harvest the crops", new Action<string, string[]>(Commands.harvestCrops)); ModCore.CoreHelper.ConsoleCommands.Add("Harvest", "Harvest the crops", new Action<string, string[]>(Commands.harvestCrops));
ModCore.CoreHelper.ConsoleCommands.Add("getseeds", "Get Seeds From chests.", new Action<string, string[]>(Commands.getSeedsFromChests)); ModCore.CoreHelper.ConsoleCommands.Add("getseeds", "Get Seeds From chests.", new Action<string, string[]>(Commands.getSeedsFromChests));
ModCore.CoreHelper.ConsoleCommands.Add("choptwigs", "Chop twigs.", new Action<string, string[]>(Commands.chopAllTwigs));
ModCore.CoreHelper.ConsoleCommands.Add("chopsticks", "Chop twigs.", new Action<string, string[]>(Commands.chopAllTwigs));
ModCore.CoreHelper.ConsoleCommands.Add("choptrees", "Chop trees down.", new Action<string, string[]>(Commands.chopAllTrees));
ModCore.CoreHelper.ConsoleCommands.Add("cuttrees", "Chop trees down.", new Action<string, string[]>(Commands.chopAllTrees));
ModCore.CoreHelper.ConsoleCommands.Add("breakstones", "Break small stones with pickaxe.", new Action<string, string[]>(Commands.breakAllStones));
ModCore.CoreHelper.ConsoleCommands.Add("cutweed", "Cut weeds with a tool.", new Action<string, string[]>(Commands.cutAllWeeds));
ModCore.CoreHelper.ConsoleCommands.Add("cutweeds", "Cut weeds with a tool", new Action<string, string[]>(Commands.cutAllWeeds));
ModCore.CoreHelper.ConsoleCommands.Add("watercan", "Fill my watering can.", new Action<string, string[]>(Commands.fillWateringCan));
ModCore.CoreHelper.ConsoleCommands.Add("fillcan", "Fill my watering can.", new Action<string, string[]>(Commands.fillWateringCan));
ModCore.CoreHelper.ConsoleCommands.Add("digdirt", "Dig out dirt on the farm.", new Action<string, string[]>(Commands.hoeDirtAmount));
ModCore.CoreHelper.ConsoleCommands.Add("tillsoil", "Dig out dirt on the farm.", new Action<string, string[]>(Commands.hoeDirtAmount));
ModCore.CoreHelper.ConsoleCommands.Add("hoedirt", "Dig out dirt on the farm.", new Action<string, string[]>(Commands.hoeDirtAmount));
ModCore.CoreHelper.ConsoleCommands.Add("plant", "Plant Seeds", new Action<string, string[]>(Commands.plantSeeds));
ModCore.CoreHelper.ConsoleCommands.Add("plantseeds", "Plant Seeds", new Action<string, string[]>(Commands.plantSeeds));
ModCore.CoreHelper.ConsoleCommands.Add("shippingbin", "Goto shipping bin", new Action<string, string[]>(Commands.goToShippingBin));
ModCore.CoreHelper.ConsoleCommands.Add("shipItem", "Ship an Item", new Action<string, string[]>(Commands.shipItem));
ModCore.CoreHelper.ConsoleCommands.Add("pathto", "Path to the adjacent map", new Action<string, string[]>(Commands.pathToMap));
ModCore.CoreHelper.ConsoleCommands.Add("goto", "Path to a given waypoint", new Action<string, string[]>(Commands.wayPoints));
ModCore.CoreHelper.ConsoleCommands.Add("waypoints", "Utilities to deal with waypoints", new Action<string, string[]>(Commands.wayPoints));
ModCore.CoreHelper.ConsoleCommands.Add("placement", "Toggleplacement", new Action<string, string[]>(Commands.togglePlacement));
// ModCore.CoreHelper.ConsoleCommands.Add("chopsticks", "Chop twigs.", new Action<string, string[]>(Commands.chopAllTwigs));
pathfind("Initialize Delay 0", new string[] { pathfind("Initialize Delay 0", new string[] {
"setDelay", "setDelay",
"0" "0"
}); });
} }
public static void hoeDirtAmount(string s, string[] args)
{
if (args.Length != 3)
{
ModCore.CoreMonitor.Log("Error, need to specify 3 paramaters:<Game location name>, <Number of tiles to dig.>, <Radius to search around farmer>");
return;
}
GameLocation loc = Game1.getLocationFromName(args[0]);
if (loc == null)
{
ModCore.CoreMonitor.Log("Error location " + args[0] + "is not valid");
return;
}
SeedLogic.makeAsMuchDirtAsSpecifiedAroundFarmer(loc, Convert.ToInt32(args[1]), Convert.ToInt32(args[2]));
}
public static void plantSeeds(string s, string[] args)
{
SeedLogic.plantSeeds(Game1.player.currentLocation);
}
public static void taskListCommands(string s, string[] args)
{
if (args.Length == 0)
{
ModCore.CoreMonitor.Log("Error: Need more parameters. Possible command paramaters are...");
ModCore.CoreMonitor.Log("(Pop/pop): pop off the first task and remove it");
ModCore.CoreMonitor.Log("(Clear/clear/Flush/flush):Remove all tasks from the task list");
return;
}
if (args[0] == "Pop" || args[0] == "pop")
{
ExecutionCore.TaskList.taskList.Remove(ExecutionCore.TaskList.taskList.ElementAt(0));
ModCore.CoreMonitor.Log("Removed top task from tasklist.");
return;
}
if (args[0] == "Clear" || args[0] == "clear")
{
ExecutionCore.TaskList.taskList.Clear();
ModCore.CoreMonitor.Log("Cleared out the task list");
return;
}
if (args[0] == "Flush" || args[0] == "flush")
{
ExecutionCore.TaskList.taskList.Clear();
ModCore.CoreMonitor.Log("Cleared out the task list");
return;
}
}
public static void wayPoints(string s, string[] args)
{
if (args.Length == 0)
{
ModCore.CoreMonitor.Log("Invalid arguments. Possible arguments are:");
ModCore.CoreMonitor.Log("Print: Print all waypoints");
ModCore.CoreMonitor.Log("print: Print all waypoints");
ModCore.CoreMonitor.Log("goto <waypointName>: Go to a specified waypoint in the world.");
return;
}
if (s == "goto")
{
if (args.Length == 0)
{
ModCore.CoreMonitor.Log("Please specify a waypoint name. They can be fetched with the command line \"waypoints print\"");
return;
}
WayPoints.pathToWayPoint(args[0]);
return;
}
if (args[0] == "Print" || args[0] == "print")
{
WayPoints.printWayPoints();
}
if (args[0] == "goto" || args[0] == "GoTo" || args[0] == "goTo")
{
if (args.Length == 1)
{
ModCore.CoreMonitor.Log("Please specify a waypoint name. They can be fetched with the command line \"waypoints print\"");
return;
}
WayPoints.pathToWayPoint(args[1]);
return;
}
}
public static void pathToMap(string s, string[] args)
{
if (args.Length == 0)
{
ModCore.CoreMonitor.Log("Need 1 parameter. MapName");
ModCore.CoreMonitor.Log("OR need 3 parameters. MapName, xTile, yTile");
return;
}
else
{
if (args.Length == 1)
{
//path to the map location.
WarpGoal.getWarpChain(Game1.player.currentLocation, args[0]);
}
if (args.Length >= 3)
{
//path to the map location.
WarpGoal.pathToWorldTile(Game1.player.currentLocation, args[0], Convert.ToInt32(args[1]), Convert.ToInt32(args[2]));
}
}
}
public static void getSeedsFromChests(string s, string[] args) public static void getSeedsFromChests(string s, string[] args)
{ {
ChestLogic.getAllSeasonalSeedsFromAllChestsAtLocation(Game1.player.currentLocation); ChestLogic.getAllSeasonalSeedsFromAllChestsAtLocation(Game1.player.currentLocation);
} }
public static void shipItem(string s, string[] args)
{
if (args.Length < 2)
{
ModCore.CoreMonitor.Log("NOT ENOUGH PARAMETERS. NEED 2 ARGS. ItemIndex,Amount");
return;
}
StardewValley.Object ok = new StardewValley.Object(Convert.ToInt32(args[0]), Convert.ToInt32(args[1]));
if (ok == null) {
ModCore.CoreMonitor.Log("ITEM IS NULL????");
return;
}
ExecutionCore.TaskPrerequisites.ItemPrerequisite pre = new ExecutionCore.TaskPrerequisites.ItemPrerequisite(ok, ok.stack);
if (pre.doesPlayerHaveEnoughOfMe())
{
ShippingLogic.goToShippingBinShipItem(ok);
}
else
{
ModCore.CoreMonitor.Log("Player does not have: " + ok.name + ": amount: " + ok.stack.ToString());
}
}
public static void goToShippingBin(string s, string[] args)
{
ShippingLogic.goToShippingBinSetUp();
}
public static void fillWateringCan(string s, string[] args)
{
WaterLogic.getAllWaterTiles(Game1.player.currentLocation);
}
public static void chopAllTrees(string s, string[] args)
{
if (args.Length == 1)
{
if (args[0] == "All" || args[0] == "all")
{
ModCore.CoreMonitor.Log("CHOP ALL TREES");
DebrisLogic.getAllTreesToChop(Game1.player.currentLocation);
return;
}
}
DebrisLogic.getAllTreesToChop(Game1.player.currentLocation);
}
/*
public void goPickUpDebris()
{
public static void removeSquareDebrisFromTile(int tileX, int tileY)
{
for (int index = Game1.currentLocation.debris.Count - 1; index >= 0; --index)
{
if (Game1.currentLocation.debris[index].debrisType == Debris.DebrisType.SQUARES && (int)((double)Game1.currentLocation.debris[index].Chunks[0].position.X / (double)Game1.tileSize) == tileX && Game1.currentLocation.debris[index].chunkFinalYLevel / Game1.tileSize == tileY)
Game1.currentLocation.debris.RemoveAt(index);
}
}
*/
public static void chopAllTwigs(string s, string[] args)
{
if (args.Length == 1)
{
if (args[0] == "All" || args[0] == "all")
{
DebrisLogic.getAllSticksToChop(Game1.player.currentLocation);
return;
}
}
DebrisLogic.getAllSticksToChop(Game1.player.currentLocation);
}
public static void goToMap(string s, string[] args)
{
if (args.Length < 1)
{
ModCore.CoreMonitor.Log("Need args length of 1. Param: Name of location to go to.");
return;
}
TaskCore.MapTransitionLogic.TransitionLogic.transitionToAdjacentMap(Game1.player.currentLocation, args[0]);
}
public static void breakAllStones(string s, string[] args)
{
if (args.Length == 1)
{
if (args[0] == "All" || args[0] == "all")
{
DebrisLogic.getAllStonesToBreak(Game1.player.currentLocation);
return;
}
}
DebrisLogic.getAllStonesToBreak(Game1.player.currentLocation);
}
public static void cutAllWeeds(string s, string[] args)
{
if (args.Length == 1)
{
if (args[0] == "All" || args[0] == "all")
{
DebrisLogic.getAllWeedsToCut(Game1.player.currentLocation);
return;
}
}
DebrisLogic.getAllWeedsToCut(Game1.player.currentLocation);
}
public static void runTasks(string s, string[] args) public static void runTasks(string s, string[] args)
{ {
ExecutionCore.TaskList.runTaskList(); ExecutionCore.TaskList.runTaskList();
/*
ModCore.CoreMonitor.Log("EXECUTE TASKS");
PathFindingLogic.source = null;
PathFindingLogic.currentGoal = null;
if (ExecutionCore.TaskList.executioner.Status == TaskStatus.Running)
{
ModCore.CoreMonitor.Log("Tasklist is already executing. Just going to return.");
return;
}
if (ExecutionCore.TaskList.executioner.Status == TaskStatus.RanToCompletion)
{
ModCore.CoreMonitor.Log("Tasklist is finished. Going to restart");
List<Task> removalList = new List<Task>();
foreach(var v in ExecutionCore.TaskList.taskList)
{
if (v.IsCompleted) removalList.Add(v);
}
foreach(var v in removalList)
{
ExecutionCore.TaskList.taskList.Remove(v);
}
ExecutionCore.TaskList.executioner = new Task(new Action(ExecutionCore.TaskList.runTaskList));
ExecutionCore.TaskList.executioner.Start();
// ExecutionCore.TaskList.taskList.Clear();
return;
//ExecutionCore.TaskList.runTaskList();
}
if (ExecutionCore.TaskList.executioner.Status == TaskStatus.Faulted)
{
ModCore.CoreMonitor.Log(ExecutionCore.TaskList.executioner.Exception.ToString());
}
if (ExecutionCore.TaskList.executioner.Status == TaskStatus.Created)
{
//ExecutionCore.TaskList.runTaskList();
List<Task> removalList = new List<Task>();
ExecutionCore.TaskList.executioner.Start();
return;
}
*/
} }
public static void waterCrops(string s, string[] args) public static void waterCrops(string s, string[] args)
{ {
PathFindingCore.CropLogic.CropLogic.getAllCropsNeededToBeWatered(); CropLogic.getAllCropsNeededToBeWatered();
} }
public static void harvestCrops(string s,string[] args) public static void harvestCrops(string s, string[] args)
{ {
PathFindingCore.CropLogic.CropLogic.getAllCropsNeededToBeHarvested(); CropLogic.getAllCropsNeededToBeHarvested();
}
public static void togglePlacement(string s, string[] args)
{
if (PathFindingCore.Utilities.placement == true)
{
PathFindingLogic.delay = 0;
PathFindingCore.Utilities.placement = false;
ModCore.CoreMonitor.Log("Placement disabled");
return;
}
if (PathFindingCore.Utilities.placement == false)
{
PathFindingLogic.delay = 100;
PathFindingCore.Utilities.placement = true;
ModCore.CoreMonitor.Log("Placement enabled");
return;
}
} }
/// <summary> /// <summary>
@ -339,7 +576,7 @@ namespace StarAI
obj[1] = PathFindingLogic.currentGoal; obj[1] = PathFindingLogic.currentGoal;
PathFindingLogic.queue = new List<TileNode>(); PathFindingLogic.queue = new List<TileNode>();
obj[2] = PathFindingLogic.queue; obj[2] = PathFindingLogic.queue;
ExecutionCore.TaskList.taskList.Add(new ExecutionCore.CustomTask(PathFindingLogic.pathFindToSingleGoal, obj,new ExecutionCore.TaskMetaData("Pathfind Command",PathFindingCore.Utilities.calculatePathCost(PathFindingLogic.source)))); // ExecutionCore.TaskList.taskList.Add(new ExecutionCore.CustomTask(PathFindingLogic.pathFindToSingleGoal, obj,new ExecutionCore.TaskMetaData("Pathfind Command",PathFindingCore.Utilities.calculatePathCost(PathFindingLogic.source,false))));
//ExecutionCore.TaskList.taskList.Add(new Task(new Action<object>(PathFindingLogic.pathFindToSingleGoal),obj)); //ExecutionCore.TaskList.taskList.Add(new Task(new Action<object>(PathFindingLogic.pathFindToSingleGoal),obj));
} }
#endregion #endregion

View File

@ -0,0 +1,55 @@
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.DialogueCore
{
public class ReponseLogic
{
public static void answerDialogueResponses()
{
if (Game1.player.currentLocation.lastQuestionKey != null)
{
ModCore.CoreMonitor.Log(Game1.player.currentLocation.lastQuestionKey);
while (Game1.player.currentLocation.lastQuestionKey == "Sleep")
{
//WindowsInput.InputSimulator.SimulateKeyDown(WindowsInput.VirtualKeyCode.ESCAPE);
Game1.player.currentLocation.lastQuestionKey = null;
ModCore.CoreMonitor.Log("GO TO SLEEP");
answerDialogueSleep();
//Game1.player.currentLocation.answerDialogue(new Response(Game1.player.currentLocation.lastQuestionKey, "Yes"));
}
}
}
public static void answerDialogueSleep()
{
GameLocation location = Game1.player.currentLocation;
if ((double)location.LightLevel == 0.0 && Game1.timeOfDay < 2000)
{
location.LightLevel = 0.6f;
Game1.playSound("openBox");
Game1.NewDay(600f);
}
else if ((double)location.LightLevel > 0.0 && Game1.timeOfDay >= 2000)
{
location.LightLevel = 0.0f;
Game1.playSound("openBox");
Game1.NewDay(600f);
}
else
Game1.NewDay(0.0f);
Game1.player.mostRecentBed = Game1.player.position;
Game1.player.doEmote(24);
Game1.player.freezePause = 2000;
}
}
}

View File

@ -0,0 +1,78 @@
using StarAI.PathFindingCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.ExecutionCore
{
public class CustomTask
{
public delegate void ObjectTask(object obj);
public delegate void VoidTask();
public ObjectTask objectTask;
public object objectParameterDataArray;
public VoidTask voidTask;
public TaskMetaData taskMetaData;
/// <summary>
/// Create a custom task and calculate cost of the action automatically without having to pass cost to the meta data. Saves a lot of code space and memory.
/// </summary>
/// <param name="objTask"></param>
/// <param name="arrayData"></param>
/// <param name="TaskMetaData"></param>
public CustomTask(ObjectTask objTask,object[] arrayData, TaskMetaData TaskMetaData)
{
objectTask = objTask;
objectParameterDataArray = arrayData;
this.taskMetaData = TaskMetaData;
try
{
// ModCore.CoreMonitor.Log("ONE COST");
this.taskMetaData.calculateTaskCost((TileNode)arrayData[0], false); //Used for pathing to a single tile in a location
}
catch(Exception err)
{
// ModCore.CoreMonitor.Log(err.ToString());
}
try
{
// ModCore.CoreMonitor.Log("TWO COST");
this.taskMetaData.calculateTaskCost((List<TileNode>)arrayData[0], false); //used to calculate best path stuff
}
catch (Exception err)
{
// ModCore.CoreMonitor.Log(err.ToString());
}
try
{
// ModCore.CoreMonitor.Log("THREE COST");
this.taskMetaData.calculateTaskCost((List<List<TileNode>>)arrayData[0], false); //and this one is for multiple paths.
}
catch(Exception err)
{
//ModCore.CoreMonitor.Log(err.ToString());
}
}
public CustomTask(VoidTask vTask, TaskMetaData TaskMetaData)
{
voidTask = vTask;
this.taskMetaData = TaskMetaData;
}
public void runTask()
{
//Check Before running task if all prerequisites are working
if (objectTask != null) objectTask.Invoke(objectParameterDataArray);
if (voidTask != null) voidTask.Invoke();
}
}
}

View File

@ -0,0 +1,394 @@
using Microsoft.Xna.Framework;
using StarAI.PathFindingCore;
using StarAI.PathFindingCore.WaterLogic;
using StarAI.TaskCore.MapTransitionLogic;
using StardewModdingAPI;
using StardewValley;
using StardewValley.Tools;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.ExecutionCore
{
class TaskList
{
public static List<CustomTask> taskList = new List<CustomTask>();
public static Task executioner = new Task(new Action(runTaskList));
public static List<CustomTask> removalList = new List<CustomTask>();
public static bool pathafterLocationChange;
public static void runTaskList()
{
//myTask t = new myTask(StarAI.PathFindingCore.CropLogic.CropLogic.harvestSingleCrop);
bool assignNewTask = true;
if(TaskPrerequisites.BedTimePrerequisite.enoughTimeToDoTaskStatic() == false)
{
CustomTask task = WayPoints.pathToWayPointReturnTask("bed");
if (task == null) ModCore.CoreMonitor.Log("SOMETHING WENT WRONG WHEN TRYING TO GO TO BED", LogLevel.Error);
ModCore.CoreMonitor.Log("Not enough time remaining in day. Going home.", LogLevel.Alert);
task.runTask();
Utilities.tileExceptionList.Clear();
taskList.Clear();
removalList.Clear();
return;
}
while(ranAllTasks()==false||TaskPrerequisites.BedTimePrerequisite.enoughTimeToDoTaskStatic()==false)
{
Utilities.tileExceptionList.Clear();
foreach (var task2 in taskList)
{
if (removalList.Contains(task2)) continue;
var temp = task2;
recalculateTask(ref temp);
//task.taskMetaData = new TaskMetaData(task.taskMetaData.name, PathFindingCore.Utilities.calculatePathCost(task.objectParameterDataArray), task.taskMetaData.staminaPrerequisite, task.taskMetaData.toolPrerequisite);
}
// ModCore.CoreMonitor.Log("DONE CALCULATING JUNK NOW RUNNING TASK");
//Some really cool delegate magic that sorts in place by the cost of the action!!!!
taskList.Sort(delegate (CustomTask t1, CustomTask t2)
{
return t1.taskMetaData.cost.CompareTo(t2.taskMetaData.cost);
});
CustomTask v = taskList.ElementAt(0);
int i = 0;
while (removalList.Contains(v))
{
v = taskList.ElementAt(i);
i++;
}
// v.Start();
bool recalculate= interruptionTasks(v);
if (recalculate) {
recalculateTask(ref v);
}
if (v.taskMetaData.verifyAllPrerequisitesHit() == true)
{
v.runTask();
Utilities.clearExceptionListWithName("Child");
Utilities.clearExceptionListWithName("Navigation");
removalList.Add(v);
}
else
{
removalList.Add(v);
}
}
Utilities.tileExceptionList.Clear();
taskList.Clear();
removalList.Clear();
}
public static void recalculateTask(ref CustomTask v)
{
object[] oArray = (object[])v.objectParameterDataArray;
// ModCore.CoreMonitor.Log("RECALCULATING: "+ v.taskMetaData.name);
if (v.taskMetaData.name.Contains("Path to "))
{
Utilities.tileExceptionList.Clear();
// ModCore.CoreMonitor.Log("POKE DEW VALLEY: " + v.taskMetaData.name);
string[] s = v.taskMetaData.name.Split(' ');
ModCore.CoreMonitor.Log(s.ElementAt(s.Length-1));
List<List<TileNode>> newPaths = new List<List<TileNode>>();
newPaths = TaskCore.MapTransitionLogic.WarpGoal.getWarpChainReturn(Game1.player.currentLocation, s.ElementAt(s.Length-1));
v.taskMetaData.cost = 0;
int value = 0;
foreach (var path in newPaths)
{
value+= (path.Count * TaskMetaDataHeuristics.pathCostMultiplier);
}
object[] arr = (object[])v.objectParameterDataArray;
arr[3] = newPaths;
v.taskMetaData.cost = value;
v.taskMetaData.pathsToTake = newPaths;
//ModCore.CoreMonitor.Log("IDK ANY MORE: " + v.taskMetaData.cost);
return;
}
Utilities.tileExceptionList.Clear();
try
{
Utilities.tileExceptionList.Clear();
TileNode t = (TileNode)oArray[0];
Utilities.tileExceptionList.Clear();
//ModCore.CoreMonitor.Log("Premtive calculate 1");
//ModCore.CoreMonitor.Log("Valaue before???:" + v.taskMetaData.pathsToTake[0].Count);
v.taskMetaData.calculateTaskCost(t, false);
//v.taskMetaData.pathsToTake = new List<List<TileNode>>();
//v.taskMetaData.pathsToTake.Add(StarAI.PathFindingCore.Utilities.getIdealPath(v));
object[] objArr = new object[10];
objArr[0] = (object)t;
objArr[1] = (object)v.taskMetaData.pathsToTake[0];
//ModCore.CoreMonitor.Log("HMM SO WHAT'S HAPPENING???:" + v.taskMetaData.pathsToTake[0].Count);
int malcolm = 0;
objArr[2] = (object)v.taskMetaData.pathsToTake[0].ElementAt(malcolm); //source of whatever is hit.
try
{
objArr[3] = oArray[3];
}
catch (Exception err2)
{
}
try
{
objArr[4] = oArray[4];
}
catch (Exception err2)
{
}
try
{
objArr[5] = oArray[5];
}
catch (Exception err2)
{
}
v.objectParameterDataArray = objArr;
return;
}
catch (Exception err)
{
}
try
{
Utilities.tileExceptionList.Clear();
List<TileNode> t = (List<TileNode>)oArray[0];
// ModCore.CoreMonitor.Log("Premtive calculate 2");
foreach (var s in Utilities.tileExceptionList)
{
ModCore.CoreMonitor.Log(s.actionType);
}
v.taskMetaData.calculateTaskCost(t, false);
object[] objArr = new object[10];
objArr[0] = (object)t; //List of trees to use for path calculations
objArr[1] = (object)v.taskMetaData.pathsToTake[0]; //The path itself.
int malcolm = 0;
// ModCore.CoreMonitor.Log("THIS IS MALCOLM:" + malcolm);
objArr[2] = (object)v.taskMetaData.pathsToTake[0].ElementAt(malcolm); //source of whatever is hit.
try
{
objArr[3] = oArray[3];
}
catch (Exception err2)
{
}
try
{
objArr[4] = oArray[4];
}
catch (Exception err2)
{
}
try
{
objArr[5] = oArray[5];
}
catch (Exception err2)
{
}
v.objectParameterDataArray = objArr;
Utilities.tileExceptionList.Clear();
return;
}
catch(Exception err)
{
}
try
{
Utilities.tileExceptionList.Clear();
List<List<TileNode>> t = (List<List<TileNode>>)oArray[3];
// ModCore.CoreMonitor.Log("Premtive calculate 3");
foreach (var s in Utilities.tileExceptionList)
{
ModCore.CoreMonitor.Log(s.actionType);
}
v.taskMetaData.calculateTaskCost(t, false);
object[] objArr = new object[10];
objArr[0] = (object)t; //List of trees to use for path calculations
objArr[1] = (object)v.taskMetaData.pathsToTake; //The path itself.
int malcolm = 0;
// ModCore.CoreMonitor.Log("THIS IS MALCOLM:" + malcolm);
objArr[2] = (object)v.taskMetaData.pathsToTake[0].ElementAt(malcolm); //source of whatever is hit.
try
{
objArr[3] = oArray[3];
}
catch (Exception err2)
{
}
try
{
objArr[4] = oArray[4];
}
catch (Exception err2)
{
}
try
{
objArr[5] = oArray[5];
}
catch (Exception err2)
{
}
v.objectParameterDataArray = objArr;
Utilities.tileExceptionList.Clear();
return;
}
catch(Exception err)
{
}
}
public static bool interruptionTasks(CustomTask v)
{
if (v.taskMetaData.bedTimePrerequisite.enoughTimeToDoTask() == false)
{
CustomTask task = WayPoints.pathToWayPointReturnTask("bed");
if (task == null)
{
ModCore.CoreMonitor.Log("SOMETHING WENT WRONG WHEN TRYING TO GO TO BED", LogLevel.Error);
return false;
}
ModCore.CoreMonitor.Log("Not enough time remaining in day. Going home and removing tasks.", LogLevel.Alert);
task.runTask();
return true;
}
if (v.taskMetaData.locationPrerequisite.isPlayerAtLocation() == false)
{
//Force player to move to that location, but also need the cost again....
// ModCore.CoreMonitor.Log("PLAYERS LOCATION:"+Game1.player.currentLocation.name);
Utilities.tileExceptionList.Clear();
CustomTask task= WarpGoal.getWarpChainReturnTask(Game1.player.currentLocation, v.taskMetaData.locationPrerequisite.location.name);
if (task == null)
{
ModCore.CoreMonitor.Log("SOMETHING WENT WRONG WHEN TRYING TO GO TO" + v.taskMetaData.locationPrerequisite.location.name, LogLevel.Error);
return false;
}
task.runTask();
object[] arr = (object[])v.objectParameterDataArray;
List<TileNode> path;
try
{
List<List<TileNode>> okList = (arr[0] as List<List<TileNode>>);
List<TileNode> smallList = okList.ElementAt(okList.Count - 1);
TileNode tile = smallList.ElementAt(smallList.Count - 1);
//arr[0] = WarpGoal.pathToWorldTileReturnTask(Game1.player.currentLocation, v.taskMetaData.locationPrerequisite.location.name,(int) tile.tileLocation.X,(int) tile.tileLocation.Y);
TileNode s = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
s.fakePlacementAction(Game1.player.currentLocation, Game1.player.getTileX(), Game1.player.getTileY());
path = Utilities.getIdealPath(tile, s);
}
catch(Exception err)
{
Utilities.tileExceptionList.Clear();
List<TileNode> smallList = (arr[1] as List<TileNode>);
TileNode tile = smallList.ElementAt(smallList.Count-1);
//ModCore.CoreMonitor.Log("LOC:" + tile.thisLocation + tile.thisLocation);
Warp lastWarp = new Warp(-1, -1, "Grahm", -1, -1, false);
GameLocation fakeLocation = Game1.getLocationFromName(Game1.player.currentLocation.name);
foreach(var ok in fakeLocation.warps)
{
if (ok.X == Game1.player.getTileX() && ok.Y == Game1.player.getTileY() + 1) lastWarp = ok;
}
//ModCore.CoreMonitor.Log("MYLOC:" + lastWarp.TargetName + lastWarp.TargetX +" "+lastWarp.TargetY);
//arr[0] = WarpGoal.pathToWorldTileReturnTask(Game1.player.currentLocation, v.taskMetaData.locationPrerequisite.location.name,(int) tile.tileLocation.X,(int) tile.tileLocation.Y);
TileNode s = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
s.fakePlacementAction(Game1.getLocationFromName(lastWarp.TargetName), lastWarp.TargetX, lastWarp.TargetY);
path = Utilities.getIdealPath(tile, s);
//arr[0] = s;
}
// ModCore.CoreMonitor.Log("PATHCOUNT:"+path.Count);
//arr[1] = path;
//v.objectParameterDataArray = arr;
PathFindingLogic.calculateMovement(path);
return false;
}
if (v.taskMetaData.name == "Water Crop")
{
StardewValley.Tools.WateringCan w = new WateringCan();
bool found = false;
foreach (var item in Game1.player.items)
{
if (item == null) continue;
if (item.GetType() == typeof(StardewValley.Tools.WateringCan))
{
w = (WateringCan)item;
found = true;
}
}
if (found == false)
{
removalList.Add(v);
return false;
}
if (w.WaterLeft == 0)
{
CustomTask waterRefill = WaterLogic.getAllWaterTilesTask(Game1.player.currentLocation);
ModCore.CoreMonitor.Log("No water in can. Going to refil");
waterRefill.runTask();
return true;
}
//
}
return false;
}
public static bool ranAllTasks()
{
foreach(CustomTask task in taskList)
{
if (removalList.Contains(task)) continue;
else return false;
}
return true;
}
public static void printAllTaskMetaData()
{
ModCore.CoreMonitor.Log(taskList.Count.ToString());
foreach (var task in taskList)
{
task.taskMetaData.printMetaData();
}
}
}
}

View File

@ -0,0 +1,158 @@
using StarAI.ExecutionCore.TaskPrerequisites;
using StarAI.PathFindingCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.ExecutionCore
{
public class TaskMetaData
{
public string name;
public float priority;
public float cost;
public float utility;
public float frequency;
public StarAI.ExecutionCore.TaskPrerequisites.StaminaPrerequisite staminaPrerequisite;
public StarAI.ExecutionCore.TaskPrerequisites.ToolPrerequisite toolPrerequisite;
public TaskPrerequisites.InventoryFullPrerequisite inventoryPrerequisite;
public TaskPrerequisites.BedTimePrerequisite bedTimePrerequisite;
public TaskPrerequisites.ItemPrerequisite itemPrerequisite;
public LocationPrerequisite locationPrerequisite;
public List<TaskPrerequisites.GenericPrerequisite> prerequisitesList;
public List<List<TileNode>> pathsToTake = new List<List<TileNode>>();
public TaskMetaData(string Name, LocationPrerequisite LocationPrereque, StaminaPrerequisite StaminaPrerequisite = null, ToolPrerequisite ToolPrerequisite = null, InventoryFullPrerequisite InventoryFull=null,BedTimePrerequisite bedTimePrereq=null, ItemPrerequisite ItemPrereque = null)
{
this.name = Name;
this.staminaPrerequisite = StaminaPrerequisite;
this.toolPrerequisite = ToolPrerequisite;
this.inventoryPrerequisite = InventoryFull;
this.pathsToTake = new List<List<TileNode>>();
this.bedTimePrerequisite = bedTimePrereq;
this.itemPrerequisite = ItemPrereque;
this.locationPrerequisite = LocationPrereque;
//Make sure to set values correctly incase of null
setUpLocationPrerequsiteIfNull();
setUpStaminaPrerequisiteIfNull();
setUpToolPrerequisiteIfNull();
setUpInventoryPrerequisiteIfNull();
setUpBedTimeIfNull();
setUpItemPrerequisiteIfNull();
this.prerequisitesList = new List<TaskPrerequisites.GenericPrerequisite>();
this.prerequisitesList.Add(this.staminaPrerequisite);
this.prerequisitesList.Add(this.toolPrerequisite);
this.prerequisitesList.Add(this.inventoryPrerequisite);
this.prerequisitesList.Add(this.bedTimePrerequisite);
this.prerequisitesList.Add(this.itemPrerequisite);
}
public void calculateTaskCost(TileNode source,bool unknownPath)
{
var pair = TaskMetaDataHeuristics.calculateTaskCost(source, this.toolPrerequisite, unknownPath);
this.cost= pair.Key;
this.pathsToTake = new List<List<TileNode>>();
this.pathsToTake.Add(pair.Value);
//this.path = Utilities.calculatePath(source, false);
}
public void calculateTaskCost(List<TileNode> source, bool unknownPath)
{
var pair = TaskMetaDataHeuristics.calculateTaskCost(source, this.toolPrerequisite, unknownPath);
this.cost = pair.Key;
this.pathsToTake = new List<List<TileNode>>();
this.pathsToTake.Add(pair.Value);
//this.path = Utilities.calculatePath(source, false);
}
public void calculateTaskCost(List<List<TileNode>> source, bool unknownPath)
{
var pair = TaskMetaDataHeuristics.calculateTaskCost(source, this.toolPrerequisite, unknownPath);
this.cost = pair.Key;
this.pathsToTake = pair.Value;
//this.path = Utilities.calculatePath(source, false);
}
private void setUpLocationPrerequsiteIfNull()
{
if (this.locationPrerequisite == null) this.locationPrerequisite = new LocationPrerequisite(null);
}
private void setUpToolPrerequisiteIfNull()
{
if (this.toolPrerequisite == null)
{
this.toolPrerequisite = new TaskPrerequisites.ToolPrerequisite(false, null,0);
}
}
private void setUpItemPrerequisiteIfNull()
{
if (this.itemPrerequisite == null)
{
this.itemPrerequisite = new TaskPrerequisites.ItemPrerequisite(null, 0);
}
}
private void setUpStaminaPrerequisiteIfNull()
{
if (this.staminaPrerequisite == null)
{
this.staminaPrerequisite = new TaskPrerequisites.StaminaPrerequisite(false, 0);
}
}
private void setUpInventoryPrerequisiteIfNull()
{
if (this.inventoryPrerequisite == null) this.inventoryPrerequisite = new TaskPrerequisites.InventoryFullPrerequisite(false);
}
private void setUpBedTimeIfNull()
{
if (this.bedTimePrerequisite == null) this.bedTimePrerequisite = new TaskPrerequisites.BedTimePrerequisite(true);
}
public bool verifyAllPrerequisitesHit()
{
foreach(var prerequisite in this.prerequisitesList)
{
if (prerequisite.checkAllPrerequisites() == false) return false;
}
return true;
}
public void printMetaData()
{
string s = "";
s += "Queued Task:"+"\n";
s += " TaskName: " + this.name + "\n";
s += " TaskCost: " + this.cost + "\n";
if (this.locationPrerequisite.location != null)
{
s += " Task Location: " + this.locationPrerequisite.location.name + "\n";
}
TileNode t = pathsToTake.ElementAt(pathsToTake.Count - 1).ElementAt(pathsToTake.ElementAt(pathsToTake.Count - 1).Count-1);
s += " Goal Location: " + t.thisLocation.name + " " + t.tileLocation;
s += " Task Requires Stamina: " + this.staminaPrerequisite.requiresStamina + "\n";
if(this.staminaPrerequisite.requiresStamina==true) s += " Requires : " + this.staminaPrerequisite.staminaCost + "Stamina.\n";
s += " Task Requires Tool: " + this.toolPrerequisite.requiresTool + "\n";
if (this.toolPrerequisite.requiresTool == true) s += " Requires a : " + this.toolPrerequisite.requiredTool + "\n";
s += " Task Requires Tool: " + this.toolPrerequisite.requiresTool + "\n";
s += " Checks if inventory full: "+this.inventoryPrerequisite.doesTaskRequireInventorySpace.ToString() + "\n";
ModCore.CoreMonitor.Log(s);
}
}
}

View File

@ -0,0 +1,130 @@
using StarAI.ExecutionCore.TaskPrerequisites;
using StarAI.PathFindingCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.ExecutionCore
{
/// <summary>
/// This will be used to determine how much any given action, pathing distance, etc will have on the overall cost of a given task.
/// </summary>
public class TaskMetaDataHeuristics
{
/// <summary>
/// Multiplier to be used to multiply out pathCost on any given action. Higher numbers will mean more discrimination against actions with long manhattan distances.
/// </summary>
public static int pathCostMultiplier=1;
/// <summary>
/// This is a dictionary that holds the action cost for every tool when it is used.
/// </summary>
public static Dictionary<Type, int> toolCostDictionary = new Dictionary<Type, int>();
/// <summary>
/// Used to set the values at the beginning.
/// </summary>
public static void initializeToolCostDictionary()
{
toolCostDictionary.Add(typeof(StardewValley.Tools.WateringCan), 2);
toolCostDictionary.Add(typeof(StardewValley.Tools.Axe), 4);
toolCostDictionary.Add(typeof(StardewValley.Tools.Pickaxe), 3);
toolCostDictionary.Add(typeof(StardewValley.Tools.FishingRod), 5);
toolCostDictionary.Add(typeof(StardewValley.Tools.Hoe), 2);
toolCostDictionary.Add(typeof(StardewValley.Tools.MeleeWeapon), 1);
toolCostDictionary.Add(typeof(StardewValley.Tools.Sword), 1);
}
/// <summary>
/// Used to assign a weight to using a tool a single time.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static int parseToolCostMultiplier(TaskPrerequisites.ToolPrerequisite t)
{
Type tool = t.requiredTool;
int value=2;
bool f = toolCostDictionary.TryGetValue(tool,out value);
if (f == true) return value;
else return 2;
}
/// <summary>
/// Used to calculate the weight of using a tool to add to the overall cost of a TaskMetaData cost.
/// </summary>
/// <param name="t"></param>
/// <param name="numberOfTimesToolIsUsed"></param>
/// <returns></returns>
public static int calculateToolCostMultiplier(TaskPrerequisites.ToolPrerequisite t)
{
if (t.requiresTool == false || t.requiredTool==null) return 0; //Default tool not used.
return (parseToolCostMultiplier(t) * t.estimatedNumberOfUses);
}
public static KeyValuePair<int,List<TileNode>> calculateTaskCost(TileNode v,ToolPrerequisite t,bool unknownPath)
{
//if(unknownPath) PathFindingLogic.delay = 18;
// else PathFindingLogic.delay = 0;
List<TileNode> idealPath = StarAI.PathFindingCore.Utilities.getIdealPath(v);
int costCalculation;
if (idealPath.Count == 0) costCalculation = Int32.MaxValue;
else costCalculation = idealPath.Count;
if (costCalculation == Int32.MaxValue) return new KeyValuePair<int, List<TileNode>>(Int32.MaxValue,new List<TileNode>());
float pathCost= costCalculation* pathCostMultiplier;
float toolCost = calculateToolCostMultiplier(t);
return new KeyValuePair<int,List<TileNode>>(((int)pathCost + (int)toolCost),idealPath);
}
public static KeyValuePair<int, List<TileNode>> calculateTaskCost(List<TileNode> v, ToolPrerequisite t, bool unknownPath)
{
//if (unknownPath) PathFindingLogic.delay = 18;
//else PathFindingLogic.delay = 0;
List<TileNode> idealPath = StarAI.PathFindingCore.Utilities.getIdealPath(v);
int costCalculation;
if (idealPath.Count == 0) costCalculation = Int32.MaxValue;
else costCalculation = idealPath.Count;
if (costCalculation == Int32.MaxValue) return new KeyValuePair<int, List<TileNode>>(Int32.MaxValue, new List<TileNode>());
float pathCost = costCalculation * pathCostMultiplier;
float toolCost = calculateToolCostMultiplier(t);
return new KeyValuePair<int, List<TileNode>>(((int)pathCost + (int)toolCost), idealPath);
}
public static KeyValuePair<int, List<List<TileNode>>> calculateTaskCost(List<List<TileNode>> v, ToolPrerequisite t, bool unknownPath)
{
//if (unknownPath) PathFindingLogic.delay = 18;
//else PathFindingLogic.delay = 0;
float totalCalculation = 0;
List < List < TileNode >> idealPaths=new List<List<TileNode>>();
foreach (var path in v)
{
ModCore.CoreMonitor.Log("HMMM" + path.ElementAt(0).thisLocation.name.ToString());
ModCore.CoreMonitor.Log("HMMM" + path.ElementAt(0).tileLocation.ToString());
List<TileNode> idealPath = StarAI.PathFindingCore.Utilities.getIdealPath(path);
int costCalculation=0;
if (idealPath.Count == 0) costCalculation = Int32.MaxValue;
else costCalculation = idealPath.Count;
//There was an error somewhere and now this won't work!!!!
if (costCalculation == Int32.MaxValue) return new KeyValuePair<int, List<List<TileNode>>>(Int32.MaxValue, new List<List<TileNode>>());
float pathCost = costCalculation * pathCostMultiplier;
ModCore.CoreMonitor.Log("I THINK THIS IS MY PATH COST: " + costCalculation);
float toolCost = calculateToolCostMultiplier(t);
totalCalculation += toolCost + pathCost;
idealPaths.Add(idealPath);
}
return new KeyValuePair<int, List<List<TileNode>>>((int)totalCalculation, idealPaths);
}
}
}

View File

@ -0,0 +1,73 @@
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.ExecutionCore.TaskPrerequisites
{
public class BedTimePrerequisite : GenericPrerequisite
{
public bool checkIfEnoughTimeRemaining;
public BedTimePrerequisite(bool CheckForBedtime)
{
this.checkIfEnoughTimeRemaining = CheckForBedtime;
}
public int timeRemainingInDay()
{
int passOutTime = 2600;
return passOutTime - Game1.timeOfDay;
}
/// <summary>
/// The default here will give you 2 hrs which should be enough for bedTime.
/// </summary>
/// <returns></returns>
public bool enoughTimeToDoTask()
{
int timeRemaining = timeRemainingInDay();
if (timeRemaining > 200) return true;
else return false;
}
public static int timeRemainingInDayStatic()
{
int passOutTime = 2600;
return passOutTime - Game1.timeOfDay;
}
/// <summary>
/// The default here will give you 2 hrs which should be enough for bedTime.
/// </summary>
/// <returns></returns>
public static bool enoughTimeToDoTaskStatic()
{
int timeRemaining = timeRemainingInDayStatic();
if (timeRemaining > 200) return true;
else return false;
}
public bool enoughTimeToDoTask(int timeToDoTask)
{
int timeRemaining = timeRemainingInDay();
if (timeRemaining > timeToDoTask) return true;
else return false;
}
public override bool checkAllPrerequisites()
{
if (this.checkIfEnoughTimeRemaining == false) return true;
if (enoughTimeToDoTask()) return true;
else
{
ModCore.CoreMonitor.Log("Not enough time remaining in the day. You should go home.");
//Add functionality here to return home.
return false;
}
}
}
}

View File

@ -0,0 +1,39 @@
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.ExecutionCore.TaskPrerequisites
{
/// <summary>
/// Weirdly enough this will be empty because it's just a placeholder prerequisite. Doesn't need to hold any more data since the player will always have an updated inventory.
/// </summary>
public class InventoryFullPrerequisite:GenericPrerequisite
{
public bool doesTaskRequireInventorySpace;
public InventoryFullPrerequisite(bool RequiresInventorySpace)
{
this.doesTaskRequireInventorySpace = RequiresInventorySpace;
}
public bool isPlayerInventoryFull()
{
return Game1.player.isInventoryFull();
}
public override bool checkAllPrerequisites()
{
if (this.doesTaskRequireInventorySpace == false) return true;
if (isPlayerInventoryFull() == false) return true;
else//player inventory is full
{
ModCore.CoreMonitor.Log("Player inventory is full failed the task prerequisite");
return false;
}
}
}
}

View File

@ -0,0 +1,56 @@
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.ExecutionCore.TaskPrerequisites
{
public class ItemPrerequisite:GenericPrerequisite
{
public Item item;
public int amount;
public ItemPrerequisite(Item DesiredItem, int Amount)
{
this.item = DesiredItem;
this.amount = Amount;
}
public override bool checkAllPrerequisites()
{
if (this.item == null || this.amount == 0) return true;
if (doesPlayerInventoryContainMe() == false) return false;
if (doesPlayerHaveEnoughOfMe() == false) return false;
return true;
}
public bool doesPlayerInventoryContainMe()
{
foreach(var item in Game1.player.items)
{
if (item == null) continue;
if (isItemSameTypeAsMe(item)) return true;
}
return false;
}
public bool isItemSameTypeAsMe(Item I)
{
if (I.GetType() == this.item.GetType()) return true;
else return false;
}
public bool doesPlayerHaveEnoughOfMe()
{
foreach (var item in Game1.player.items)
{
if (item == null) continue;
if (isItemSameTypeAsMe(item)&&item.Stack>=amount) return true;
}
return false;
}
}
}

View File

@ -0,0 +1,43 @@
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.ExecutionCore.TaskPrerequisites
{
public class LocationPrerequisite:GenericPrerequisite
{
public GameLocation location;
public LocationPrerequisite(GameLocation Location)
{
this.location = Location;
}
public bool isPlayerAtLocation()
{
if (this.location == null)
{
ModCore.CoreMonitor.Log("Location calculation is null");
return true;
}
else
{
ModCore.CoreMonitor.Log("THIS IS THE LOCATION"+this.location);
}
if (Game1.player.currentLocation == this.location || Game1.player.currentLocation.name == this.location.name) return true;
else return false;
}
public override bool checkAllPrerequisites()
{
if (this.location == null) return true;
if (isPlayerAtLocation()) return true;
return false;
}
}
}

View File

@ -0,0 +1,55 @@
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.ExecutionCore.TaskPrerequisites
{
public class ToolPrerequisite:GenericPrerequisite
{
public bool requiresTool;
public Type requiredTool;
public int estimatedNumberOfUses;
public ToolPrerequisite(bool TaskNeedsTool, Type RequiredTool, int EstimatedNumberOfUses)
{
requiresTool = TaskNeedsTool;
requiredTool = RequiredTool;
this.estimatedNumberOfUses = EstimatedNumberOfUses;
verifyToolSetUp();
}
public void verifyToolSetUp()
{
if (requiresTool == false)
{
requiredTool = null;
estimatedNumberOfUses = 0;
}
}
public bool isToolInInventory()
{
if (requiresTool == false) return true;
foreach (var item in Game1.player.items) {
Type t = requiredTool.GetType();
if ( item.GetType()==requiredTool) return true;
}
return false;
}
public override bool checkAllPrerequisites()
{
if (isToolInInventory()) return true;
else
{
ModCore.CoreMonitor.Log("A task failed due to not having the required tool: "+this.requiredTool);
return false;
}
}
//istoolinanychests???? Needs function to be able to request an item from any given chest and go fetch it which can require moving across maps.
}
}

View File

@ -0,0 +1,40 @@
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.InterfaceCore
{
public class InterfaceLogic
{
public static void interactWithCurrentMenu()
{
if (Game1.activeClickableMenu == null)
{
return;
}
//WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.ESCAPE);
//ModCore.CoreMonitor.Log(Game1.activeClickableMenu.ToString());
if(Game1.activeClickableMenu is StardewValley.Menus.DialogueBox)
{
Game1.activeClickableMenu.exitThisMenu(true);
ModCore.CoreMonitor.Log("BYE");
}
if (Game1.activeClickableMenu is StardewValley.Menus.ShippingMenu)
{
//(Game1.activeClickableMenu as StardewValley.Menus.ShippingMenu).readyToClose
//Game1.activeClickableMenu.exitThisMenu(true);
ShippingMenuCore.closeMenu();
ModCore.CoreMonitor.Log("Hello");
}
}
}
}

View File

@ -0,0 +1,22 @@
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.InterfaceCore
{
class ShippingMenuCore
{
public static void closeMenu()
{
(Game1.activeClickableMenu as StardewValley.Menus.ShippingMenu).okButton.snapMouseCursorToCenter();
if (Game1.activeClickableMenu is StardewValley.Menus.ShippingMenu)
{
ModCore.CoreMonitor.Log("PRESS ALREADY!");
WindowsInput.InputSimulator.SimulateKeyDown(WindowsInput.VirtualKeyCode.ESCAPE);
}
}
}
}

View File

@ -0,0 +1,442 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewValley;
using StardewValley.Menus;
using System;
using System.Collections.Generic;
using System.Linq;
using StardustCore;
namespace StarAI.MenuCore
{
public class CropUtilityMenu : IClickableMenu
{
public static int widthToMoveActiveTab = Game1.tileSize / 8;
private string descriptionText = "";
private string hoverText = "";
public List<ClickableTextureComponent> sideTabs = new List<ClickableTextureComponent>();
public Dictionary<int, List<List<ClickableTextureComponent>>> collections = new Dictionary<int, List<List<ClickableTextureComponent>>>();
public const int region_sideTabShipped = 7001;
public const int region_sideTabFish = 7002;
public const int region_sideTabArtifacts = 7003;
public const int region_sideTabMinerals = 7004;
public const int region_sideTabCooking = 7005;
public const int region_sideTabAchivements = 7006;
public const int region_forwardButton = 707;
public const int region_backButton = 706;
public const int organicsTab = 0;
public const int fishTab = 1;
public const int archaeologyTab = 2;
public const int mineralsTab = 3;
public const int cookingTab = 4;
public const int achievementsTab = 5;
public const int distanceFromMenuBottomBeforeNewPage = 128;
public ClickableTextureComponent backButton;
public ClickableTextureComponent forwardButton;
private int currentTab;
private int currentPage;
private int value;
public CropUtilityMenu(int x, int y, int width, int height)
: base(x, y, width, height, false)
{
List<ClickableTextureComponent> sideTabs1 = this.sideTabs;
ClickableTextureComponent textureComponent1 = new ClickableTextureComponent("", new Rectangle(this.xPositionOnScreen - Game1.tileSize * 3 / 4 + CollectionsPage.widthToMoveActiveTab, this.yPositionOnScreen + Game1.tileSize * 2, Game1.tileSize, Game1.tileSize), "", Game1.content.LoadString("Strings\\UI:Collections_Shipped"), Game1.mouseCursors, new Rectangle(640, 80, 16, 16), (float)Game1.pixelZoom, false);
int num1 = 7001;
textureComponent1.myID = num1;
int num2 = 7002;
textureComponent1.downNeighborID = num2;
int num3 = 0;
textureComponent1.rightNeighborID = num3;
sideTabs1.Add(textureComponent1);
this.collections.Add(0, new List<List<ClickableTextureComponent>>());
List<ClickableTextureComponent> sideTabs2 = this.sideTabs;
ClickableTextureComponent textureComponent2 = new ClickableTextureComponent("", new Rectangle(this.xPositionOnScreen - Game1.tileSize * 3 / 4, this.yPositionOnScreen + Game1.tileSize * 3, Game1.tileSize, Game1.tileSize), "", Game1.content.LoadString("Strings\\UI:Collections_Fish"), Game1.mouseCursors, new Rectangle(640, 64, 16, 16), (float)Game1.pixelZoom, false);
int num4 = 7002;
textureComponent2.myID = num4;
int num5 = 7001;
textureComponent2.upNeighborID = num5;
int num6 = 7003;
textureComponent2.downNeighborID = num6;
int num7 = 0;
textureComponent2.rightNeighborID = num7;
sideTabs2.Add(textureComponent2);
this.collections.Add(1, new List<List<ClickableTextureComponent>>());
List<ClickableTextureComponent> sideTabs3 = this.sideTabs;
ClickableTextureComponent textureComponent3 = new ClickableTextureComponent("", new Rectangle(this.xPositionOnScreen - Game1.tileSize * 3 / 4, this.yPositionOnScreen + Game1.tileSize * 4, Game1.tileSize, Game1.tileSize), "", Game1.content.LoadString("Strings\\UI:Collections_Artifacts"), Game1.mouseCursors, new Rectangle(656, 64, 16, 16), (float)Game1.pixelZoom, false);
int num8 = 7003;
textureComponent3.myID = num8;
int num9 = 7002;
textureComponent3.upNeighborID = num9;
int num10 = 7004;
textureComponent3.downNeighborID = num10;
int num11 = 0;
textureComponent3.rightNeighborID = num11;
sideTabs3.Add(textureComponent3);
this.collections.Add(2, new List<List<ClickableTextureComponent>>());
List<ClickableTextureComponent> sideTabs4 = this.sideTabs;
ClickableTextureComponent textureComponent4 = new ClickableTextureComponent("", new Rectangle(this.xPositionOnScreen - Game1.tileSize * 3 / 4, this.yPositionOnScreen + Game1.tileSize * 5, Game1.tileSize, Game1.tileSize), "", Game1.content.LoadString("Strings\\UI:Collections_Minerals"), Game1.mouseCursors, new Rectangle(672, 64, 16, 16), (float)Game1.pixelZoom, false);
int num12 = 7004;
textureComponent4.myID = num12;
int num13 = 7003;
textureComponent4.upNeighborID = num13;
int num14 = 7005;
textureComponent4.downNeighborID = num14;
int num15 = 0;
textureComponent4.rightNeighborID = num15;
sideTabs4.Add(textureComponent4);
this.collections.Add(3, new List<List<ClickableTextureComponent>>());
List<ClickableTextureComponent> sideTabs5 = this.sideTabs;
ClickableTextureComponent textureComponent5 = new ClickableTextureComponent("", new Rectangle(this.xPositionOnScreen - Game1.tileSize * 3 / 4, this.yPositionOnScreen + Game1.tileSize * 6, Game1.tileSize, Game1.tileSize), "", Game1.content.LoadString("Strings\\UI:Collections_Cooking"), Game1.mouseCursors, new Rectangle(688, 64, 16, 16), (float)Game1.pixelZoom, false);
int num16 = 7005;
textureComponent5.myID = num16;
int num17 = 7004;
textureComponent5.upNeighborID = num17;
int num18 = 7006;
textureComponent5.downNeighborID = num18;
int num19 = 0;
textureComponent5.rightNeighborID = num19;
sideTabs5.Add(textureComponent5);
this.collections.Add(4, new List<List<ClickableTextureComponent>>());
List<ClickableTextureComponent> sideTabs6 = this.sideTabs;
ClickableTextureComponent textureComponent6 = new ClickableTextureComponent("", new Rectangle(this.xPositionOnScreen - Game1.tileSize * 3 / 4, this.yPositionOnScreen + Game1.tileSize * 7, Game1.tileSize, Game1.tileSize), "", Game1.content.LoadString("Strings\\UI:Collections_Achievements"), Game1.mouseCursors, new Rectangle(656, 80, 16, 16), (float)Game1.pixelZoom, false);
int num20 = 7006;
textureComponent6.myID = num20;
int num21 = 7005;
textureComponent6.upNeighborID = num21;
int num22 = 0;
textureComponent6.rightNeighborID = num22;
sideTabs6.Add(textureComponent6);
this.collections.Add(5, new List<List<ClickableTextureComponent>>());
CollectionsPage.widthToMoveActiveTab = Game1.tileSize / 8;
ClickableTextureComponent textureComponent7 = new ClickableTextureComponent(new Rectangle(this.xPositionOnScreen + Game1.tileSize * 3 / 4, this.yPositionOnScreen + height - 20 * Game1.pixelZoom, 12 * Game1.pixelZoom, 11 * Game1.pixelZoom), Game1.mouseCursors, new Rectangle(352, 495, 12, 11), (float)Game1.pixelZoom, false);
int num23 = 706;
textureComponent7.myID = num23;
int num24 = -7777;
textureComponent7.rightNeighborID = num24;
this.backButton = textureComponent7;
ClickableTextureComponent textureComponent8 = new ClickableTextureComponent(new Rectangle(this.xPositionOnScreen + width - Game1.tileSize / 2 - 15 * Game1.pixelZoom, this.yPositionOnScreen + height - 20 * Game1.pixelZoom, 12 * Game1.pixelZoom, 11 * Game1.pixelZoom), Game1.mouseCursors, new Rectangle(365, 495, 12, 11), (float)Game1.pixelZoom, false);
int num25 = 707;
textureComponent8.myID = num25;
int num26 = -7777;
textureComponent8.leftNeighborID = num26;
this.forwardButton = textureComponent8;
int[] numArray = new int[this.sideTabs.Count];
int num27 = this.xPositionOnScreen + IClickableMenu.borderWidth + IClickableMenu.spaceToClearSideBorder;
int num28 = this.yPositionOnScreen + IClickableMenu.borderWidth + IClickableMenu.spaceToClearTopBorder - Game1.tileSize / 4;
int num29 = 10;
foreach (KeyValuePair<int, string> keyValuePair in Game1.objectInformation)
{
string str = keyValuePair.Value.Split('/')[3];
bool drawShadow = false;
int index;
if (str.Contains("Arch"))
{
index = 2;
if (Game1.player.archaeologyFound.ContainsKey(keyValuePair.Key))
drawShadow = true;
}
else if (str.Contains("Fish"))
{
if (keyValuePair.Key < 167 || keyValuePair.Key >= 173)
{
index = 1;
if (Game1.player.fishCaught.ContainsKey(keyValuePair.Key))
drawShadow = true;
}
else
continue;
}
else if (str.Contains("Mineral") || str.Substring(str.Length - 3).Equals("-2"))
{
index = 3;
if (Game1.player.mineralsFound.ContainsKey(keyValuePair.Key))
drawShadow = true;
}
else if (str.Contains("Cooking") || str.Substring(str.Length - 3).Equals("-7"))
{
index = 4;
if (Game1.player.recipesCooked.ContainsKey(keyValuePair.Key))
drawShadow = true;
if (keyValuePair.Key == 217 || keyValuePair.Key == 772 || keyValuePair.Key == 773)
continue;
}
else if(keyValuePair.Key>0)
{
index = 0;
StardewValley.Object obj = new StardewValley.Object(keyValuePair.Key, 1);
if (obj.getCategoryName()!="Seed") continue;
drawShadow = true;
}
else
continue;
int x1 = num27 + numArray[index] % num29 * (Game1.tileSize + 4);
int y1 = num28 + numArray[index] / num29 * (Game1.tileSize + 4);
if (y1 > this.yPositionOnScreen + height - 128)
{
this.collections[index].Add(new List<ClickableTextureComponent>());
numArray[index] = 0;
x1 = num27;
y1 = num28;
}
if (this.collections[index].Count == 0)
this.collections[index].Add(new List<ClickableTextureComponent>());
StardewValley.Object o = new StardewValley.Object(keyValuePair.Key, 1);
if (o.getCategoryName() != "Seed") continue;
List<ClickableTextureComponent> textureComponentList = this.collections[index].Last<List<ClickableTextureComponent>>();
float scale= Game1.pixelZoom * (1 + UtilityCore.SeedCropUtility.getUtilityScaleValue(o.parentSheetIndex));
if (UtilityCore.SeedCropUtility.getUtilityScaleValue(o.parentSheetIndex)==0) scale = 1.00f;
ClickableTextureComponent textureComponent9 = new ClickableTextureComponent(keyValuePair.Key.ToString() + " " + drawShadow.ToString(), new Rectangle(x1, y1, Game1.tileSize, Game1.tileSize), (string)null, "", Game1.objectSpriteSheet, Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, keyValuePair.Key, 16, 16),Game1.pixelZoom, drawShadow);
textureComponent9.scale = scale;
int count = this.collections[index].Last<List<ClickableTextureComponent>>().Count;
textureComponent9.myID = count;
int num30 = (this.collections[index].Last<List<ClickableTextureComponent>>().Count + 1) % num29 == 0 ? -1 : this.collections[index].Last<List<ClickableTextureComponent>>().Count + 1;
textureComponent9.rightNeighborID = num30;
int num31 = this.collections[index].Last<List<ClickableTextureComponent>>().Count % num29 == 0 ? 7001 : this.collections[index].Last<List<ClickableTextureComponent>>().Count - 1;
textureComponent9.leftNeighborID = num31;
int num32 = y1 + (Game1.tileSize + 4) > this.yPositionOnScreen + height - 128 ? -7777 : this.collections[index].Last<List<ClickableTextureComponent>>().Count + num29;
textureComponent9.downNeighborID = num32;
int num33 = this.collections[index].Last<List<ClickableTextureComponent>>().Count < num29 ? 12345 : this.collections[index].Last<List<ClickableTextureComponent>>().Count - num29;
textureComponent9.upNeighborID = num33;
int num34 = 1;
textureComponent9.fullyImmutable = num34 != 0;
textureComponentList.Add(textureComponent9);
++numArray[index];
}
if (this.collections[5].Count == 0)
this.collections[5].Add(new List<ClickableTextureComponent>());
}
protected override void customSnapBehavior(int direction, int oldRegion, int oldID)
{
base.customSnapBehavior(direction, oldRegion, oldID);
if (direction == 2)
{
if (this.currentPage > 0)
this.currentlySnappedComponent = this.getComponentWithID(706);
else if (this.currentPage == 0 && this.collections[this.currentTab].Count > 1)
this.currentlySnappedComponent = this.getComponentWithID(707);
this.backButton.upNeighborID = oldID;
this.forwardButton.upNeighborID = oldID;
}
else if (direction == 3)
{
if (oldID != 707 || this.currentPage <= 0)
return;
this.currentlySnappedComponent = this.getComponentWithID(706);
}
else
{
if (direction != 1 || oldID != 706 || this.collections[this.currentTab].Count <= this.currentPage + 1)
return;
this.currentlySnappedComponent = this.getComponentWithID(707);
}
}
public override void snapToDefaultClickableComponent()
{
base.snapToDefaultClickableComponent();
this.currentlySnappedComponent = this.getComponentWithID(0);
this.snapCursorToCurrentSnappedComponent();
}
public override void receiveLeftClick(int x, int y, bool playSound = true)
{
for (int index = 0; index < this.sideTabs.Count; ++index)
{
if (this.sideTabs[index].containsPoint(x, y) && this.currentTab != index)
{
Game1.playSound("smallSelect");
this.sideTabs[this.currentTab].bounds.X -= CollectionsPage.widthToMoveActiveTab;
this.currentTab = index;
this.currentPage = 0;
this.sideTabs[index].bounds.X += CollectionsPage.widthToMoveActiveTab;
}
}
if (this.currentPage > 0 && this.backButton.containsPoint(x, y))
{
this.currentPage = this.currentPage - 1;
Game1.playSound("shwip");
this.backButton.scale = this.backButton.baseScale;
if (Game1.options.snappyMenus && Game1.options.gamepadControls && this.currentPage == 0)
{
this.currentlySnappedComponent = (ClickableComponent)this.forwardButton;
Game1.setMousePosition(this.currentlySnappedComponent.bounds.Center);
}
}
ClickableTextureComponent texture;
foreach (ClickableTextureComponent textureComponent in this.collections[0][this.currentPage])
{
if (textureComponent.containsPoint(x, y))
{
string[] s = textureComponent.name.Split(' ');
ModCore.CoreMonitor.Log(s[0]);
ModCore.CoreMonitor.Log("CLICKED A THING!");
UtilityCore.SeedCropUtility.updateUserUtilities(Convert.ToInt32(s[0]), 0.05f);
textureComponent.scale = Game1.pixelZoom * (1 + UtilityCore.SeedCropUtility.getUtilityScaleValue(Convert.ToInt32(s[0])));
if (UtilityCore.SeedCropUtility.getUtilityScaleValue(Convert.ToInt32(s[0]))==0) textureComponent.scale = 1.00f;
texture = textureComponent;
}
}
if (this.currentPage >= this.collections[this.currentTab].Count - 1 || !this.forwardButton.containsPoint(x, y))
return;
this.currentPage = this.currentPage + 1;
Game1.playSound("shwip");
this.forwardButton.scale = this.forwardButton.baseScale;
if (!Game1.options.snappyMenus || !Game1.options.gamepadControls || this.currentPage != this.collections[this.currentTab].Count - 1)
return;
this.currentlySnappedComponent = (ClickableComponent)this.backButton;
Game1.setMousePosition(this.currentlySnappedComponent.bounds.Center);
}
public override void receiveRightClick(int x, int y, bool playSound = true)
{
foreach (ClickableTextureComponent textureComponent in this.collections[0][this.currentPage])
{
if (textureComponent.containsPoint(x, y))
{
string[] s = textureComponent.name.Split(' ');
ModCore.CoreMonitor.Log(s[0]);
ModCore.CoreMonitor.Log("CLICKED A THING!");
UtilityCore.SeedCropUtility.updateUserUtilities(Convert.ToInt32(s[0]), -0.05f);
//ModCore.CoreMonitor.Log(textureComponent.scale.ToString());
textureComponent.scale = Game1.pixelZoom * (1 + UtilityCore.SeedCropUtility.getUtilityScaleValue(Convert.ToInt32(s[0])));
if (UtilityCore.SeedCropUtility.getUtilityScaleValue(Convert.ToInt32(s[0])) == 0) textureComponent.scale = 1.00f;
}
}
}
public override void performHoverAction(int x, int y)
{
this.descriptionText = "";
this.hoverText = "";
this.value = -1;
int i = 0;
foreach (ClickableTextureComponent sideTab in this.sideTabs)
{
if (i != 0) break;
if (sideTab.containsPoint(x, y))
{
this.hoverText = sideTab.hoverText;
return;
}
i++;
}
foreach (ClickableTextureComponent textureComponent in this.collections[this.currentTab][this.currentPage])
{
if (textureComponent.containsPoint(x, y))
{
string[] s = textureComponent.name.Split(' ');
textureComponent.scale = Game1.pixelZoom * (1+ UtilityCore.SeedCropUtility.getUtilityScaleValue(Convert.ToInt32(s[0])));
if (UtilityCore.SeedCropUtility.getUtilityScaleValue(Convert.ToInt32(s[0])) == 0) textureComponent.scale = 1.00f;
if (Convert.ToBoolean(textureComponent.name.Split(' ')[1]) || this.currentTab == 5) {
this.hoverText = this.createDescription(Convert.ToInt32(textureComponent.name.Split(' ')[0]));
this.hoverText += "\n\nAI Utility Value: " +Math.Round(UtilityCore.SeedCropUtility.CropSeedUtilityDictionary[(Convert.ToInt32(s[0]))],3);
this.hoverText += "\n\nUser Utility Value: " +Math.Round(UtilityCore.SeedCropUtility.UserCropSeedUtilityDictionary[(Convert.ToInt32(s[0]))],3);
this.hoverText += "\n\nTotal Utility Value: " +Math.Round(UtilityCore.SeedCropUtility.getUtilityScaleValue(Convert.ToInt32(s[0])),3);
}
else
this.hoverText = "???";
}
else
{
string[] s = textureComponent.name.Split(' ');
textureComponent.scale = Game1.pixelZoom * (1 + UtilityCore.SeedCropUtility.getUtilityScaleValue(Convert.ToInt32(s[0])));
if (UtilityCore.SeedCropUtility.getUtilityScaleValue(Convert.ToInt32(s[0])) == 0) textureComponent.scale = 1.00f;
}
}
this.forwardButton.tryHover(x, y, 0.5f);
this.backButton.tryHover(x, y, 0.5f);
}
public string createDescription(int index)
{
string str1 = "";
string str2;
if (this.currentTab == 5)
{
string[] strArray = Game1.achievements[index].Split('^');
str2 = str1 + strArray[0] + Environment.NewLine + Environment.NewLine + strArray[1];
}
else
{
string[] strArray = Game1.objectInformation[index].Split('/');
string str3 = strArray[4];
string str4 = str1 + str3 + Environment.NewLine + Environment.NewLine + Game1.parseText(strArray[5], Game1.smallFont, Game1.tileSize * 4) + Environment.NewLine + Environment.NewLine;
if (strArray[3].Contains("Arch"))
{
string str5 = str4;
string str6;
if (!Game1.player.archaeologyFound.ContainsKey(index))
str6 = "";
else
str6 = Game1.content.LoadString("Strings\\UI:Collections_Description_ArtifactsFound", (object)Game1.player.archaeologyFound[index][0]);
str2 = str5 + str6;
}
else if (strArray[3].Contains("Cooking"))
{
string str5 = str4;
string str6;
if (!Game1.player.recipesCooked.ContainsKey(index))
str6 = "";
else
str6 = Game1.content.LoadString("Strings\\UI:Collections_Description_RecipesCooked", (object)Game1.player.recipesCooked[index]);
str2 = str5 + str6;
}
else if (strArray[3].Contains("Fish"))
{
str2 = str4 + Game1.content.LoadString("Strings\\UI:Collections_Description_FishCaught", (object)(Game1.player.fishCaught.ContainsKey(index) ? Game1.player.fishCaught[index][0] : 0));
if (Game1.player.fishCaught.ContainsKey(index) && Game1.player.fishCaught[index][1] > 0)
str2 = str2 + Environment.NewLine + Game1.content.LoadString("Strings\\UI:Collections_Description_BiggestCatch", (object)(LocalizedContentManager.CurrentLanguageCode != LocalizedContentManager.LanguageCode.en ? Math.Round((double)Game1.player.fishCaught[index][1] * 2.54) : (double)Game1.player.fishCaught[index][1]));
}
else if (strArray[3].Contains("Minerals") || strArray[3].Substring(strArray[3].Length - 3).Equals("-2"))
str2 = str4 + Game1.content.LoadString("Strings\\UI:Collections_Description_MineralsFound", (object)(Game1.player.mineralsFound.ContainsKey(index) ? Game1.player.mineralsFound[index] : 0));
else
str2 = str4 + Game1.content.LoadString("Strings\\UI:Collections_Description_NumberShipped", (object)(Game1.player.basicShipped.ContainsKey(index) ? Game1.player.basicShipped[index] : 0));
this.value = Convert.ToInt32(strArray[1]);
}
return str2;
}
public override void draw(SpriteBatch b)
{
Game1.drawDialogueBox(this.xPositionOnScreen, this.yPositionOnScreen, this.width, this.height, false, true);
int i = 0;
foreach (ClickableTextureComponent sideTab in this.sideTabs)
{
sideTab.draw(b);
i++;
if (i != 0) break;
}
if (this.currentPage > 0)
this.backButton.draw(b);
if (this.currentPage < this.collections[this.currentTab].Count - 1)
this.forwardButton.draw(b);
b.End();
b.Begin(SpriteSortMode.FrontToBack, BlendState.NonPremultiplied, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null);
foreach (ClickableTextureComponent textureComponent in this.collections[0][this.currentPage])
{
bool boolean = textureComponent.scale.Equals(1.00f);
textureComponent.draw(b, boolean ? Color.White * 0.6f : Color.White, 0.86f);
if (this.currentTab == 5 & boolean)
{
int num = new Random(Convert.ToInt32(textureComponent.name.Split(' ')[0])).Next(12);
b.Draw(Game1.mouseCursors, new Vector2((float)(textureComponent.bounds.X + 16 + Game1.tileSize / 4), (float)(textureComponent.bounds.Y + 20 + Game1.tileSize / 4)), new Rectangle?(new Rectangle(256 + num % 6 * Game1.tileSize / 2, 128 + num / 6 * Game1.tileSize / 2, Game1.tileSize / 2, Game1.tileSize / 2)), Color.White, 0.0f, new Vector2((float)(Game1.tileSize / 4), (float)(Game1.tileSize / 4)), textureComponent.scale, SpriteEffects.None, 0.88f);
}
}
b.End();
b.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, (DepthStencilState)null, (RasterizerState)null);
if (this.hoverText.Equals(""))
{
this.drawMouse(b);
return;
}
IClickableMenu.drawHoverText(b, this.hoverText, Game1.smallFont, 0, 0, this.value, (string)null, -1, (string[])null, (Item)null, 0, -1, -1, -1, -1, 1f, (CraftingRecipe)null);
this.drawMouse(b);
}
}
}

278
StarAI/StarAI/ModCore.cs Normal file
View File

@ -0,0 +1,278 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StardewValley;
using StardewModdingAPI;
using WindowsInput;
using Microsoft.Xna.Framework;
using StarAI.PathFindingCore;
using System.IO;
using StardustCore;
using StardewValley.Menus;
using StarAI.TaskCore.MapTransitionLogic;
namespace StarAI
{
//TODO: Clean up initial code
//Make sure pathos doesn't update this once since it's a homework assignment. Sorry Pathos!
//Work on dijakstra's algorithm for path finding on this one? Make sure obstacles are included.
//Question how this is all going to work.
public class ModCore : Mod
{
public static StardewModdingAPI.IMonitor CoreMonitor;
public static StardewModdingAPI.IModHelper CoreHelper;
public static List<Warp> warpGoals = new List<Warp>();
public static object[] obj = new object[3];
public static bool throwUpShippingMenu;
private bool playerHasLoadedGame;
public override void Entry(IModHelper helper)
{
obj[0] = PathFindingLogic.source;
obj[1] = PathFindingLogic.currentGoal;
obj[2] = PathFindingLogic.queue;
CoreHelper = helper;
throwUpShippingMenu = false;
CoreMonitor = this.Monitor;
CoreMonitor.Log("Hello AI WORLD!", LogLevel.Info);
initializeEverything();
StardewModdingAPI.Events.ControlEvents.KeyPressed += ControlEvents_KeyPressed;
StardewModdingAPI.Events.SaveEvents.AfterLoad += SaveEvents_AfterLoad;
StardewModdingAPI.Events.SaveEvents.BeforeSave += SaveEvents_BeforeSave;
StardewModdingAPI.Events.SaveEvents.AfterSave += SaveEvents_AfterSave;
StardewModdingAPI.Events.GameEvents.UpdateTick += GameEvents_UpdateTick;
playerHasLoadedGame = false;
StardustCore.ModCore.SerializationManager.acceptedTypes.Add("StarAI.PathFindingCore.TileNode", new StardustCore.Serialization.SerializerDataNode(new StardustCore.Serialization.SerializerDataNode.SerializingFunction(StarAI.PathFindingCore.TileNode.Serialize), new StardustCore.Serialization.SerializerDataNode.ParsingFunction(StarAI.PathFindingCore.TileNode.ParseIntoInventory), new StardustCore.Serialization.SerializerDataNode.WorldParsingFunction(StarAI.PathFindingCore.TileNode.SerializeFromWorld), new StardustCore.Serialization.SerializerDataNode.SerializingToContainerFunction(StarAI.PathFindingCore.TileNode.Serialize)));
PathFindingCore.Utilities.placement = false;
}
private void GameEvents_UpdateTick(object sender, EventArgs e)
{
if (playerHasLoadedGame == false) return;
DialogueCore.ReponseLogic.answerDialogueResponses();
InterfaceCore.InterfaceLogic.interactWithCurrentMenu();
}
private void SaveEvents_AfterSave(object sender, EventArgs e)
{
WayPoints.setUpBedWaypoint();
UtilityCore.SeedCropUtility.setUpCropUtilityDictionaryDaily();
WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.ESCAPE);
}
public void initializeEverything()
{
Commands.initializeCommands();
PathFindingCore.Utilities.initializeTileExceptionList();
ExecutionCore.TaskMetaDataHeuristics.initializeToolCostDictionary();
WayPoints.initializeWaypoints();
}
private void SaveEvents_BeforeSave(object sender, EventArgs e)
{
List<TileNode> removalList = new List<TileNode>();
foreach(var v in StardustCore.ModCore.SerializationManager.trackedObjectList)
{
if(v.getCategoryName()=="Tile Node")
{
//StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
removalList.Add((v as TileNode));
}
}
foreach(var v in removalList)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
}
Stack<IClickableMenu> menus = new Stack<IClickableMenu>();
if (throwUpShippingMenu == true)
{
List<Item> itemList = new List<Item>();
foreach (var item in Game1.shippingBin)
{
itemList.Add(item);
}
menus.Push(new StardewValley.Menus.ShippingMenu(itemList));
foreach (var q in Game1.shippingBin)
{
ModCore.CoreMonitor.Log(q.name);
}
throwUpShippingMenu = false;
}
foreach(var v in Game1.endOfNightMenus)
{
menus.Push(v);
}
Game1.endOfNightMenus = menus;
}
private void SaveEvents_AfterLoad(object sender, EventArgs e)
{
// loadExceptionTiles();
CheatCore.DoorsToWarps.makeAllDoorsWarps();
WayPoints.setUpBedWaypoint();
WayPoints.verifyWayPoints();
UtilityCore.SeedCropUtility.setUpUserCropUtilityDictionary(); //Runs once
UtilityCore.SeedCropUtility.setUpCropUtilityDictionaryDaily(); //Runs daily
playerHasLoadedGame = true;
}
private void ControlEvents_KeyPressed(object sender, StardewModdingAPI.Events.EventArgsKeyPressed e)
{
//J key for shop
#region
if (e.KeyPressed == Microsoft.Xna.Framework.Input.Keys.J)
{
CoreMonitor.Log("OK THE J KEY WAS PRESSED!");
List<Item> shoppingList = new List<Item>();
StarAI.PathFindingCore.TileNode t = new StarAI.PathFindingCore.TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Aqua));
if (t == null)
{
CoreMonitor.Log("WTF?????");
}
try
{
if (t == null)
{
return;
}
shoppingList.Add((Item)t);
Game1.activeClickableMenu = new StardewValley.Menus.ShopMenu(shoppingList);
}
catch (Exception err)
{
CoreMonitor.Log(Convert.ToString(err));
}
}
#endregion
//K key for placing a tile.
#region
if (e.KeyPressed == Microsoft.Xna.Framework.Input.Keys.K)
{
CoreMonitor.Log("OK THE K KEY WAS PRESSED!");
StarAI.PathFindingCore.TileNode t = new StarAI.PathFindingCore.TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.randomColor());
if (t == null)
{
CoreMonitor.Log("WTF?????");
}
try
{
if (t == null)
{
return;
}
CoreMonitor.Log(new Vector2(Game1.player.getTileX() * Game1.tileSize, Game1.player.getTileY() * Game1.tileSize).ToString());
int xPos = (int)(Game1.player.getTileX()) * Game1.tileSize;
int yPos = (int)(Game1.player.getTileY()) * Game1.tileSize;
Rectangle r = new Rectangle(xPos, yPos, Game1.tileSize, Game1.tileSize);
Vector2 pos = new Vector2(r.X, r.Y);
bool ok = StarAI.PathFindingCore.TileNode.checkIfICanPlaceHere(t, pos, Game1.player.currentLocation);
if (ok == false) return;
t.placementAction(Game1.currentLocation, Game1.player.getTileX() * Game1.tileSize, Game1.player.getTileY() * Game1.tileSize);
//t.setAdjacentTiles(true);
}
catch (Exception err)
{
CoreMonitor.Log(Convert.ToString(err));
}
}
#endregion
if (e.KeyPressed == Microsoft.Xna.Framework.Input.Keys.Y)
{
ShopCore.ShopLogic.openSeedShopMenu();
}
if (e.KeyPressed == Microsoft.Xna.Framework.Input.Keys.T)
{
Game1.activeClickableMenu = new MenuCore.CropUtilityMenu((int)(Game1.viewport.Width * .1f), (int)(Game1.viewport.Height * .05f), (int)(Game1.viewport.Width*.7f),(int)(Game1.viewport.Height*.75f));
}
if (e.KeyPressed == Microsoft.Xna.Framework.Input.Keys.U)
{
ExecutionCore.TaskList.printAllTaskMetaData();
foreach(var v in PathFindingCore.Utilities.tileExceptionList)
{
ModCore.CoreMonitor.Log(v.actionType);
}
}
if (e.KeyPressed == Microsoft.Xna.Framework.Input.Keys.O)
{
foreach (var v in Game1.player.currentLocation.map.TileSheets)
{
foreach (var q in Game1.player.currentLocation.map.Layers)
{
string[] s = q.ToString().Split(':');
string layer = s[1].Trim();
if (Game1.player.currentLocation.map.GetLayer(layer) == null)
{
ModCore.CoreMonitor.Log("SHITTTTTT: " + layer, LogLevel.Error);
}
int tileIndex = Game1.player.currentLocation.getTileIndexAt((int)Game1.player.getTileX(), (int)Game1.player.getTileY(), layer);
if (tileIndex == -1) continue;
ModCore.CoreMonitor.Log("Position: " + (Game1.player.getTileLocation()).ToString(), LogLevel.Warn);
ModCore.CoreMonitor.Log("Layer: " + layer, LogLevel.Warn);
ModCore.CoreMonitor.Log("Index: " + tileIndex.ToString(), LogLevel.Warn);
ModCore.CoreMonitor.Log("Image Source: " + v.ImageSource, LogLevel.Warn);
if (layer == "Buildings")
{
TileExceptionNode tileException = new TileExceptionNode(v.ImageSource, tileIndex);
foreach(var tile in PathFindingCore.Utilities.ignoreCheckTiles)
{
if (tile.imageSource == tileException.imageSource && tile.index == tileException.index)
{
ModCore.CoreMonitor.Log("Tile exception already initialized!");
return; //tile is already initialized.
}
}
//PathFindingCore.Utilities.ignoreCheckTiles.Add(tileException);
// tileException.serializeJson(Path.Combine(ModCore.CoreHelper.DirectoryPath, PathFindingCore.Utilities.folderForExceptionTiles));
//StardustCore.ModCore.SerializationManager.
}
}
}
}
}
private void LocationEvents_CurrentLocationChanged(object sender, StardewModdingAPI.Events.EventArgsCurrentLocationChanged e)
{
CoreMonitor.Log("LOCATION CHANGED!");
CoreMonitor.Log(Game1.player.currentLocation.name);
foreach (var v in Game1.player.currentLocation.warps)
{
string s = "X: " + Convert.ToString(v.X) + " Y: " + Convert.ToString(v.Y) + " TargetX: " + Convert.ToString(v.TargetX) + " TargetY: " + Convert.ToString(v.TargetY) + " TargetLocationName: " + Convert.ToString(v.TargetName);
CoreMonitor.Log(s);
//warpGoals.Add(v); Disabled for now
}
//GameLocation loc=Game1.getLocationFromName("location name")
//
}
}
}

View File

@ -21,7 +21,7 @@ namespace StarAI.PathFindingCore
public static int delay; public static int delay;
public static int index = 0; // public static int index = 0;
public static void pathFindToAllGoals() public static void pathFindToAllGoals()
@ -71,9 +71,10 @@ namespace StarAI.PathFindingCore
public static void pathFindToSingleGoal(object data) public static void pathFindToSingleGoal(object data)
{ {
int index = 0;
List<TileNode> path = new List<TileNode>(); List<TileNode> path = new List<TileNode>();
//path.Clear(); //path.Clear();
ModCore.CoreMonitor.Log("LET'S GO!!!!", LogLevel.Error); //ModCore.CoreMonitor.Log("LET'S GO!!!!", LogLevel.Error);
object[] obj = (object[])data; object[] obj = (object[])data;
TileNode Source =(TileNode) obj[0]; TileNode Source =(TileNode) obj[0];
@ -116,7 +117,7 @@ namespace StarAI.PathFindingCore
if (x == 1 && y == 1) continue; //bottom right if (x == 1 && y == 1) continue; //bottom right
//TileNode t = new TileNode(1, Vector2.Zero, Souce.texturePath,source.dataPath, source.drawColor); //TileNode t = new TileNode(1, Vector2.Zero, Souce.texturePath,source.dataPath, source.drawColor);
TileNode.setSingleTileAsChild(currentNode, (int)currentNode.tileLocation.X + x, (int)currentNode.tileLocation.Y + y); TileNode.setSingleTileAsChild(currentNode, (int)currentNode.tileLocation.X + x, (int)currentNode.tileLocation.Y + y,false);
Vector2 check = new Vector2((int)currentNode.tileLocation.X + x, (int)currentNode.tileLocation.Y + y); Vector2 check = new Vector2((int)currentNode.tileLocation.X + x, (int)currentNode.tileLocation.Y + y);
if(check.X==Goal.tileLocation.X && check.Y == Goal.tileLocation.Y) if(check.X==Goal.tileLocation.X && check.Y == Goal.tileLocation.Y)
{ {
@ -189,13 +190,13 @@ namespace StarAI.PathFindingCore
if (currentNode.tileLocation != Goal.tileLocation) if (currentNode.tileLocation != Goal.tileLocation)
{ {
ModCore.CoreMonitor.Log("NO PATH FOUND", LogLevel.Error); // ModCore.CoreMonitor.Log("NO PATH FOUND", LogLevel.Error);
return; return;
} }
if (currentNode.tileLocation == Goal.tileLocation) if (currentNode.tileLocation == Goal.tileLocation)
{ {
ModCore.CoreMonitor.Log("SWEET BEANS!!!!!!", LogLevel.Error); // ModCore.CoreMonitor.Log("SWEET BEANS!!!!!!", LogLevel.Error);
queue.Clear(); queue.Clear();
index = 0; index = 0;
//ModCore.CoreMonitor.Log(currentNode.parent.ToString(), LogLevel.Error); //ModCore.CoreMonitor.Log(currentNode.parent.ToString(), LogLevel.Error);
@ -275,21 +276,34 @@ namespace StarAI.PathFindingCore
/// <param name="Queue">Depreciated for further builds.</param> /// <param name="Queue">Depreciated for further builds.</param>
/// <param name="Placement">Whether or not tiles are actually going to be placed</param> /// <param name="Placement">Whether or not tiles are actually going to be placed</param>
/// <returns></returns> /// <returns></returns>
public static List<TileNode> pathFindToSingleGoalReturnPath(TileNode Source, TileNode Goal, List<TileNode> Queue,bool Placement) public static List<TileNode> pathFindToSingleGoalReturnPath(TileNode Source, TileNode Goal, List<TileNode> Queue,bool Placement,bool CheckForUtility)
{ {
object[] obj = new object[4]; object[] obj = new object[5];
obj[0] = Source; obj[0] = Source;
obj[1] = Goal; obj[1] = Goal;
obj[2] = Queue; obj[2] = Queue;
obj[3] = Placement; obj[3] = Placement;
obj[4] = CheckForUtility;
return pathFindToSingleGoalReturnPath(obj); return pathFindToSingleGoalReturnPath(obj);
} }
public static List<TileNode> pathFindToSingleGoalReturnPath(TileNode Source, List<TileNode> Goal, List<TileNode> Queue, bool Placement, bool CheckForUtility)
{
object[] obj = new object[5];
obj[0] = Source;
obj[1] = Goal;
obj[2] = Queue;
obj[3] = Placement;
obj[4] = CheckForUtility;
return pathFindToSingleGoalReturnPathList(obj);
}
public static List<TileNode> pathFindToSingleGoalReturnPath(object data) public static List<TileNode> pathFindToSingleGoalReturnPath(object data)
{ {
int index = 0;
List<TileNode> path = new List<TileNode>(); List<TileNode> path = new List<TileNode>();
//path.Clear(); //path.Clear();
ModCore.CoreMonitor.Log("LET'S GO!!!!", LogLevel.Error); //ModCore.CoreMonitor.Log("LET'S GO!!!!", LogLevel.Error);
object[] obj = (object[])data; object[] obj = (object[])data;
TileNode Source = (TileNode)obj[0]; TileNode Source = (TileNode)obj[0];
@ -308,14 +322,17 @@ namespace StarAI.PathFindingCore
TileNode currentNode = Source; TileNode currentNode = Source;
bool placement = (bool)obj[3]; bool placement = (bool)obj[3];
bool checkForUtility = (bool)obj[4];
queue.Add(currentNode); queue.Add(currentNode);
index++; index++;
bool goalFound = false; bool goalFound = false;
Utilities.clearExceptionListWithName("Child");
Utilities.clearExceptionListWithName("Navigation");
while (currentNode.tileLocation != Goal.tileLocation && queue.Count != 0) while (currentNode.tileLocation != Goal.tileLocation && queue.Count != 0)
{ {
// ModCore.CoreMonitor.Log("LET'S GO PATH!!!!", LogLevel.Error); // ModCore.CoreMonitor.Log("LET'S GO PATH!!!!", LogLevel.Error);
// ModCore.CoreMonitor.Log("PATH FROM SOURCE: " + currentNode.tileLocation, LogLevel.Error); //ModCore.CoreMonitor.Log("PATH FROM SOURCE: " + currentNode.tileLocation, LogLevel.Error);
// ModCore.CoreMonitor.Log("PATH To GOAL: " + Goal.tileLocation, LogLevel.Error); //ModCore.CoreMonitor.Log("PATH To GOAL: " + Goal.tileLocation, LogLevel.Error);
//Console.WriteLine("OK WTF IS GOING ON????"); //Console.WriteLine("OK WTF IS GOING ON????");
//Add children to current node //Add children to current node
int xMin = -1; int xMin = -1;
@ -337,8 +354,8 @@ namespace StarAI.PathFindingCore
if (x == 1 && y == 1) continue; //bottom right if (x == 1 && y == 1) continue; //bottom right
//TileNode t = new TileNode(1, Vector2.Zero, Souce.texturePath,source.dataPath, source.drawColor); //TileNode t = new TileNode(1, Vector2.Zero, Souce.texturePath,source.dataPath, source.drawColor);
//ModCore.CoreMonitor.Log("HERE1", LogLevel.Error); //ModCore.CoreMonitor.Log("HERE1", LogLevel.Error);
TileNode.setSingleTileAsChild(currentNode, (int)currentNode.tileLocation.X + x, (int)currentNode.tileLocation.Y + y,placement); TileNode.setSingleTileAsChild(currentNode, (int)currentNode.tileLocation.X + x, (int)currentNode.tileLocation.Y + y, checkForUtility,placement);
//ModCore.CoreMonitor.Log("OR NO?", LogLevel.Error); //ModCore.CoreMonitor.Log("OR NO?", LogLevel.Error);
Vector2 check = new Vector2((int)currentNode.tileLocation.X + x, (int)currentNode.tileLocation.Y + y); Vector2 check = new Vector2((int)currentNode.tileLocation.X + x, (int)currentNode.tileLocation.Y + y);
if (check.X == Goal.tileLocation.X && check.Y == Goal.tileLocation.Y) if (check.X == Goal.tileLocation.X && check.Y == Goal.tileLocation.Y)
@ -414,7 +431,7 @@ namespace StarAI.PathFindingCore
if (currentNode.tileLocation != Goal.tileLocation) if (currentNode.tileLocation != Goal.tileLocation)
{ {
ModCore.CoreMonitor.Log("NO PATH FOUND", LogLevel.Error); // ModCore.CoreMonitor.Log("NO PATH FOUND", LogLevel.Error);
return new List<TileNode>(); return new List<TileNode>();
} }
@ -462,32 +479,33 @@ namespace StarAI.PathFindingCore
} }
} }
List<TileNode> removalList = new List<TileNode>(); List<TileNode> removalList = new List<TileNode>();
List<TileNode> ignoreList = new List<TileNode>();
foreach (var v in StardustCore.ModCore.SerializationManager.trackedObjectList) foreach (var v in StardustCore.ModCore.SerializationManager.trackedObjectList)
{ {
if (v is TileNode) if (v is TileNode)
{ {
removalList.Add((TileNode)v);
foreach (var exc in Utilities.tileExceptionList)
{
if (exc.tile == (v as TileNode)) continue;
}
if (path.Contains(v) || goals.Contains(v) || v.drawColor == StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Red))
{
continue;
}
else
{
removalList.Add((TileNode)v);
}
} }
} }
foreach (var v in removalList) foreach (var v in removalList)
{ {
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v); StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
//v.performRemoveAction(v.tileLocation, v.thisLocation); //v.performRemoveAction(v.tileLocation, v.thisLocation);
if(placement)v.thisLocation.removeObject(v.tileLocation, false); try
{
StardewValley.Object ob = v.thisLocation.objects[v.tileLocation];
//ModCore.CoreMonitor.Log(ob.name);
if (v.name != "Generic Colored Tile") continue;// ModCore.CoreMonitor.Log("Culperate 3");
if (placement) v.thisLocation.removeObject(v.tileLocation, false);
}
catch(Exception err)
{
}
//StardustCore.Utilities.masterRemovalList.Add(v); //StardustCore.Utilities.masterRemovalList.Add(v);
} }
return path; return path;
@ -497,12 +515,262 @@ namespace StarAI.PathFindingCore
} }
public static KeyValuePair<bool, TileNode> doesNodeEqualGoal(TileNode currentNode, List<TileNode> goal)
{
foreach(var v in goal)
{
if (v.tileLocation == currentNode.tileLocation) return new KeyValuePair<bool, TileNode>(true, v);
}
return new KeyValuePair<bool, TileNode>(false, null);
}
public static KeyValuePair<bool,TileNode> doesNodeEqualGoal(Vector2 currentNode, List<TileNode> goal)
{
foreach (var v in goal)
{
if (v.tileLocation.X == currentNode.X && v.tileLocation.Y == currentNode.Y) return new KeyValuePair<bool, TileNode> (true,v);
}
return new KeyValuePair<bool, TileNode>(false,null);
}
public static List<TileNode> pathFindToSingleGoalReturnPathList(object data)
{
int index = 0;
List<TileNode> path = new List<TileNode>();
//path.Clear();
//ModCore.CoreMonitor.Log("LET'S GO 2222!!!!", LogLevel.Error);
object[] obj = (object[])data;
TileNode Source = (TileNode)obj[0];
if (Source.parent != null)
{
Source.parent = null;
}
//
List<TileNode> Goals = (List<TileNode>)obj[1];
List<TileNode> Queue = (List<TileNode>)obj[2];
totalPathCost = 0;
TileNode currentNode = Source;
bool placement = (bool)obj[3];
bool checkForUtility = (bool)obj[4];
queue.Add(currentNode);
// index++;
bool goalFound = false;
while (doesNodeEqualGoal(currentNode,Goals).Key==false && queue.Count != 0)
{
// ModCore.CoreMonitor.Log("LET'S GO PATH!!!!", LogLevel.Error);
// ModCore.CoreMonitor.Log("PATH FROM Node: " + currentNode.tileLocation, LogLevel.Error);
// ModCore.CoreMonitor.Log("PATH FROM Source: " + Source.tileLocation, LogLevel.Error);
// ModCore.CoreMonitor.Log("GOALS COUNT " + Goals.Count, LogLevel.Error);
// ModCore.CoreMonitor.Log("THIS IS MY MISTAKE!!!!!!! " + Goals.Count, LogLevel.Error);
//Console.WriteLine("OK WTF IS GOING ON????");
//Add children to current node
int xMin = -1;
int yMin = -1;
int xMax = 1;
int yMax = 1;
//try to set children to tiles where children haven't been before
for (int x = xMin; x <= xMax; x++)
{
for (int y = yMin; y <= yMax; y++)
{
if (x == 0 && y == 0) continue;
//Include these 4 checks for just left right up down movement. Remove them to enable 8 direction path finding
if (x == -1 && y == -1) continue; //upper left
if (x == -1 && y == 1) continue; //bottom left
if (x == 1 && y == -1) continue; //upper right
if (x == 1 && y == 1) continue; //bottom right
//TileNode t = new TileNode(1, Vector2.Zero, Souce.texturePath,source.dataPath, source.drawColor);
//ModCore.CoreMonitor.Log("HERE1", LogLevel.Error);
TileNode.setSingleTileAsChild(currentNode, (int)currentNode.tileLocation.X + x, (int)currentNode.tileLocation.Y + y, checkForUtility, placement);
// ModCore.CoreMonitor.Log("OR NO?", LogLevel.Error);
Vector2 check = new Vector2((int)currentNode.tileLocation.X + x, (int)currentNode.tileLocation.Y + y);
if (doesNodeEqualGoal(check,Goals).Key==true)
{
doesNodeEqualGoal(check, Goals).Value.parent = currentNode;
// Goal = doesNodeEqualGoal(check, Goals).Value;
currentNode.drawColor = StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.LightGreen);
currentNode = doesNodeEqualGoal(check, Goals).Value;
// ModCore.CoreMonitor.Log("SNAGED THE GOAL!!!!!!");
//System.Threading.Thread.Sleep(2000);
goalFound = true;
}
}
}
if (goalFound == true)
{
currentNode = doesNodeEqualGoal(currentNode, Goals).Value;
// ModCore.CoreMonitor.Log("FOUND YOU!!!");
// path.Add(currentNode);
//System.Threading.Thread.Sleep(2000);
break;
}
List<TileNode> adjList = new List<TileNode>();
foreach (var node in currentNode.children)
{
// ModCore.CoreMonitor.Log("MAYBE HERE",LogLevel.Warn);
//TileNode t = new TileNode(1, Vector2.Zero, Souce.texturePath,source.dataPath, source.drawColor);
//TileNode.setSingleTileAsChild(source, (int)source.tileLocation.X + x, (int)source.tileLocation.Y + y);
if (node.parent == null)
{
//ModCore.CoreMonitor.Log("I DONT UNDERSTAND!");
System.Threading.Thread.Sleep(delay);
}
//ModCore.CoreMonitor.Log("ok checking adj:" + node.tileLocation.ToString());
if (node.seenState == 0)
{
node.drawColor = StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.LightPink); //Seen
}
if (node.seenState == 1)
{
node.drawColor = StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Blue);
}
if (node.seenState == 2)
{
node.drawColor = StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.DarkOrange);
}
adjList.Add(node);
}
foreach (var v in adjList)
{
if (queue.Contains(v)) continue;
else queue.Add(v);
}
currentNode.seenState = 2;
currentNode.drawColor = StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.DarkOrange); //Finished
try
{
currentNode = queue.ElementAt(index);
}
catch (Exception err)
{
//ModCore.CoreMonitor.Log("INDEX ERROR:"+index, LogLevel.Error);
break;
}
currentNode.drawColor = StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Blue); //Working
index++;
}
if (doesNodeEqualGoal(currentNode,Goals).Key==false)
{
// ModCore.CoreMonitor.Log("NO PATH FOUND", LogLevel.Error);
return new List<TileNode>();
}
if (doesNodeEqualGoal(currentNode, Goals).Key == true)
{
// ModCore.CoreMonitor.Log("SWEET BEANS!!!!!!", LogLevel.Error);
queue.Clear();
index = 0;
//ModCore.CoreMonitor.Log(currentNode.parent.ToString(), LogLevel.Error);
currentNode.drawColor = StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.LightGreen);
//currentGoal.drawColor=
}
while (currentNode.parent != null)
{
currentNode.drawColor = StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Red); //Working
path.Add(currentNode);
if (currentNode.parent.tileLocation.X < currentNode.tileLocation.X)
{
currentNode.parent.animationManager.setAnimation("Right", 0);
}
if (currentNode.parent.tileLocation.X > currentNode.tileLocation.X)
{
currentNode.parent.animationManager.setAnimation("Left", 0);
}
if (currentNode.parent.tileLocation.Y < currentNode.tileLocation.Y)
{
currentNode.parent.animationManager.setAnimation("Down", 0);
}
if (currentNode.parent.tileLocation.Y > currentNode.tileLocation.Y)
{
currentNode.parent.animationManager.setAnimation("Up", 0);
}
if (currentNode.parent.tileLocation == currentNode.tileLocation)
{
currentNode.drawColor = StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Black); //Working
}
currentNode.parent.animationManager.enableAnimation();
currentNode = currentNode.parent;
System.Threading.Thread.Sleep(delay);
if (currentNode.parent == null)
{
currentNode.drawColor = StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Red); //Working
path.Add(currentNode);
}
// ModCore.CoreMonitor.Log("??????");
}
List<TileNode> removalList = new List<TileNode>();
List<TileNode> ignoreList = new List<TileNode>();
foreach (var v in StardustCore.ModCore.SerializationManager.trackedObjectList)
{
if (v is TileNode)
{
// ModCore.CoreMonitor.Log("Removing item: " + why + " / " + StardustCore.ModCore.SerializationManager.trackedObjectList.Count);
removalList.Add((TileNode)v);
}
}
foreach (var v in removalList)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
//v.performRemoveAction(v.tileLocation, v.thisLocation);
try
{
StardewValley.Object ob = v.thisLocation.objects[v.tileLocation];
//ModCore.CoreMonitor.Log(ob.name);
if (v.name != "Generic Colored Tile") continue;// ModCore.CoreMonitor.Log("Culperate 3");
if (placement) v.thisLocation.removeObject(v.tileLocation, false);
}
catch (Exception err)
{
}
//StardustCore.Utilities.masterRemovalList.Add(v);
}
if (path.Count==0&& goalFound==true)
{
path.Add(Source);
}
return path;
//calculateMovement(path);
// goals.Remove(Goal);
}
public static void calculateMovement(List<TileNode> path) public static void calculateMovement(List<TileNode> path)
{ {
path.Reverse(); path.Reverse();
ModCore.CoreMonitor.Log("PATH COUNT TIME!!!!: " + path.Count); // ModCore.CoreMonitor.Log("PATH COUNT TIME!!!!: " + path.Count);
bool xTargetReached = false; bool xTargetReached = false;
bool yTargetReached = false; bool yTargetReached = false;
List<TileNode> removalList = new List<TileNode>(); List<TileNode> removalList = new List<TileNode>();
@ -510,9 +778,14 @@ namespace StarAI.PathFindingCore
while (path.Count > 0) while (path.Count > 0)
{ {
TileNode w = path[0]; TileNode w = path[0];
//ModCore.CoreMonitor.Log("Goto: " + w.tileLocation.ToString());
// ModCore.CoreMonitor.Log("Here: " +Game1.player.position.ToString());
// ModCore.CoreMonitor.Log("LOC: " + Game1.player.currentLocation);
Vector2 center2 = Utilities.parseCenterFromTile((int)w.tileLocation.X, (int)w.tileLocation.Y);
// ModCore.CoreMonitor.Log("Goto: " + center2);
//ModCore.CoreMonitor.Log("My position now: " + Game1.player.getTileLocation()); //ModCore.CoreMonitor.Log("My position now: " + Game1.player.getTileLocation());
//ModCore.CoreMonitor.Log("My Point position now: " + Game1.player.getTileLocationPoint()); //ModCore.CoreMonitor.Log("My Point position now: " + Game1.player.getTileLocationPoint());
if (Game1.player.getTileX() == w.tileLocation.X && Game1.player.getTileY() == w.tileLocation.Y) if (Game1.player.getTileX() == w.tileLocation.X && Game1.player.getTileY() == w.tileLocation.Y)
{ {
@ -617,15 +890,23 @@ namespace StarAI.PathFindingCore
ModCore.CoreMonitor.Log("UNCAUGHT EXCEPTION", LogLevel.Error); ModCore.CoreMonitor.Log("UNCAUGHT EXCEPTION", LogLevel.Error);
InputSimulator.SimulateKeyUp(VirtualKeyCode.VK_A);
InputSimulator.SimulateKeyUp(VirtualKeyCode.VK_D);
InputSimulator.SimulateKeyUp(VirtualKeyCode.VK_W);
InputSimulator.SimulateKeyUp(VirtualKeyCode.VK_S);
} }
} }
foreach(var v in removalList) foreach(var v in removalList)
{ {
//v.thisLocation.objects.Remove(v.tileLocation); //v.thisLocation.objects.Remove(v.tileLocation);
v.thisLocation.removeObject(v.tileLocation, false); //v.thisLocation.removeObject(v.tileLocation, false);
//v.performRemoveAction(v.tileLocation, v.thisLocation); //v.performRemoveAction(v.tileLocation, v.thisLocation);
//StardustCore.Utilities.masterRemovalList.Add(v); //StardustCore.Utilities.masterRemovalList.Add(v);
v.thisLocation.objects.Remove(v.tileLocation);
//ModCore.CoreMonitor.Log("WHUT???"+v.tileLocation);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v); StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
//var ok = v;
//ok = null;
} }
//goals.Clear(); //goals.Clear();
} }

View File

@ -25,19 +25,6 @@ namespace StarAI.PathFindingCore
index = TileIndex; index = TileIndex;
} }
public static TileExceptionNode parseJson(string s)
{
dynamic obj = JObject.Parse(s);
TileExceptionNode t = new TileExceptionNode();
t.imageSource = obj.imageSource;
t.index = obj.index;
return t;
}
public void serializeJson(string s)
{
StardustCore.ModCore.SerializationManager.WriteToJsonFile(Path.Combine(s, "tileExceptionData"+ this.index.ToString() + ".json"), (TileExceptionNode)this);
}
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,600 @@
using Microsoft.Xna.Framework;
using StardewModdingAPI;
using StardewValley;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WindowsInput;
namespace StarAI.PathFindingCore
{
public class Utilities
{
public static List<TileExceptionMetaData> tileExceptionList = new List<TileExceptionMetaData>();
public static List<TileExceptionNode> ignoreCheckTiles = new List<TileExceptionNode>();
public static string folderForExceptionTiles="ExceptionTilesData";
public static bool placement;
public static Vector2 parseCenterFromTile(int tileX, int tileY)
{
//int x = (tileX * Game1.tileSize) + Game1.tileSize / 2;
//int y = (tileY * Game1.tileSize) + Game1.tileSize / 2;
int x = (tileX * Game1.tileSize);
int y = (tileY * Game1.tileSize);
return new Vector2(x, y);
}
public static void initializeTileExceptionList()
{
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\spring_outdoorsTileSheet", 779));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\spring_outdoorsTileSheet", 780));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\spring_outdoorsTileSheet", 781));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\spring_outdoorsTileSheet", 782));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\summer_outdoorsTileSheet", 779));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\summer_outdoorsTileSheet", 780));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\summer_outdoorsTileSheet", 781));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\summer_outdoorsTileSheet", 782));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\fall_outdoorsTileSheet", 779));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\fall_outdoorsTileSheet", 780));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\fall_outdoorsTileSheet", 781));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\fall_outdoorsTileSheet", 782));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\winter_outdoorsTileSheet", 779));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\winter_outdoorsTileSheet", 780));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\winter_outdoorsTileSheet", 781));
ignoreCheckTiles.Add(new TileExceptionNode("Maps\\winter_outdoorsTileSheet", 782));
}
public static void cleanExceptionList(TileNode t)
{
TileExceptionMetaData err= new TileExceptionMetaData(null,"");
foreach (var v in tileExceptionList)
{
if (v.tile == t) err = v;
}
if(err.tile != null)
{
tileExceptionList.Remove(err);
}
}
public static TileExceptionMetaData getExceptionFromTile(TileNode t)
{
foreach(var v in tileExceptionList)
{
if (t.tileLocation == v.tile.tileLocation) return v;
}
return null;
}
public static void clearExceptionListWithNames(bool removeFromWorld)
{
List<TileNode> removalList = new List<TileNode>();
List<TileExceptionMetaData> removalList2 = new List<TileExceptionMetaData>();
foreach (var v in StardustCore.ModCore.SerializationManager.trackedObjectList)
{
TileExceptionMetaData exc = getExceptionFromTile((v as TileNode));
if (exc != null)
{
if (exc.actionType == "Navigation" || exc.actionType == "CostCalculation" || exc.actionType == "Child")
{
removalList.Add(exc.tile);
removalList2.Add(exc);
}
}
}
foreach(var v in removalList)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
if (removeFromWorld) v.thisLocation.objects.Remove(v.tileLocation);
}
foreach(var v in removalList2)
{
tileExceptionList.Remove(v);
}
}
public static void clearExceptionListWithName(string name)
{
List<TileExceptionMetaData> removalList = new List<TileExceptionMetaData>();
foreach(var v in tileExceptionList)
{
//ModCore.CoreMonitor.Log("DING");
if (v.actionType == name) removalList.Add(v);
}
foreach(var v in removalList)
{
Utilities.tileExceptionList.Remove(v);
}
}
public static void clearExceptionListWithName(bool removeFromWorld,string name)
{
List<TileNode> removalList = new List<TileNode>();
List<TileExceptionMetaData> removalList2 = new List<TileExceptionMetaData>();
foreach (var v in StardustCore.ModCore.SerializationManager.trackedObjectList)
{
TileExceptionMetaData exc = getExceptionFromTile((v as TileNode));
if (exc != null)
{
if (exc.actionType == name)
{
removalList.Add(exc.tile);
removalList2.Add(exc);
}
}
}
foreach (var v in removalList)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
if (removeFromWorld) v.thisLocation.objects.Remove(v.tileLocation);
}
foreach (var v in removalList2)
{
tileExceptionList.Remove(v);
}
}
/// <summary>
/// Used to calculate center of a tile with varience.
/// </summary>
/// <param name="position"></param>
/// <param name="goal"></param>
/// <param name="tolerance"></param>
/// <returns></returns>
public static bool isWithinRange(float position, float goal, int tolerance)
{
if (position >= goal - tolerance && position <= goal + tolerance) return true;
return false;
}
public static int calculatePathCost(TileNode v, bool Placement = true)
{
object[] obj = new object[2];
obj[0] = v;
obj[1] = Placement;
return calculatePathCost(obj);
}
public static int calculatePathCost(object obj)
{
object[] objArr = (object[])obj;
TileNode v = (TileNode)objArr[0];
bool placement;
try
{
placement = (bool)objArr[1];
}
catch(Exception err)
{
placement = true;
}
foreach (var q in objArr)
{
ModCore.CoreMonitor.Log("OK THIS IS THE RESULT !: " + q, LogLevel.Alert);
}
if (v == null) ModCore.CoreMonitor.Log("WTF MARK!!!!!!: ", LogLevel.Alert);
bool moveOn = false;
WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.VK_X);
int xMin = -1;
int yMin = -1;
int xMax = 1;
int yMax = 1;
List<TileNode> miniGoals = new List<TileNode>();
List<List<TileNode>> paths = new List<List<TileNode>>();
//try to set children to tiles where children haven't been before
for (int x = xMin; x <= xMax; x++)
{
for (int y = yMin; y <= yMax; y++)
{
if (x == 0 && y == 0) continue;
//Include these 4 checks for just left right up down movement. Remove them to enable 8 direction path finding
if (x == -1 && y == -1) continue; //upper left
if (x == -1 && y == 1) continue; //bottom left
if (x == 1 && y == -1) continue; //upper right
if (x == 1 && y == 1) continue; //bottom right
Vector2 pos = new Vector2(v.tileLocation.X + x, v.tileLocation.Y + y);
//ModCore.CoreMonitor.Log("AHHHHHHH POSITION: " + pos.ToString(), LogLevel.Alert);
bool f = PathFindingCore.TileNode.checkIfICanPlaceHere(v, pos * Game1.tileSize, v.thisLocation, true,true);
ModCore.CoreMonitor.Log("OK THIS IS THE RESULT F: " + f, LogLevel.Alert);
if (f == true)
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.RosyBrown));
if(placement)t.placementAction(v.thisLocation, (int)pos.X * Game1.tileSize, (int)pos.Y * Game1.tileSize);
else t.fakePlacementAction(v.thisLocation, (int)pos.X, (int)pos.Y);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(t, Game1.currentLocation, (int)pos.X * Game1.tileSize, (int)pos.Y * Game1.tileSize));
miniGoals.Add(t);
//Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "CostCalculation"));
}
}
}
List<TileNode> removalList = new List<TileNode>();
foreach (var nav in miniGoals)
{
TileNode tempSource = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.RosyBrown));
if(placement)tempSource.placementAction(Game1.player.currentLocation, Game1.player.getTileX() * Game1.tileSize, Game1.player.getTileY() * Game1.tileSize);
else tempSource.fakePlacementAction(v.thisLocation, (int)v.tileLocation.X, (int)v.tileLocation.Y);
List<TileNode> path = PathFindingCore.PathFindingLogic.pathFindToSingleGoalReturnPath(tempSource, nav, new List<TileNode>(),true,true);
Utilities.clearExceptionListWithName(placement, "Child");
ModCore.CoreMonitor.Log(tempSource.tileLocation.ToString()+tempSource.tileLocation.ToString());
ModCore.CoreMonitor.Log(nav.tileLocation.ToString() + nav.tileLocation.ToString());
if (path.Count != 0)
{
ModCore.CoreMonitor.Log("PATH WAS NOT NULL", LogLevel.Warn);
paths.Add(path);
foreach (var someTile in path)
{
if (someTile == nav) removalList.Add(someTile);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(someTile);
if (placement)
{
try
{
StardewValley.Object ob = someTile.thisLocation.objects[someTile.tileLocation];
ModCore.CoreMonitor.Log(ob.name);
if (ob.name == "Twig") ModCore.CoreMonitor.Log("Culperate 2");
someTile.thisLocation.objects.Remove(someTile.tileLocation);
}
catch(Exception err)
{
}
}
//someTile.performRemoveAction(someTile.tileLocation, someTile.thisLocation);
//StardustCore.Utilities.masterRemovalList.Add(v);
}
}
}
foreach (var q in removalList)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(q);
if (placement)
{
try
{
StardewValley.Object ob = q.thisLocation.objects[q.tileLocation];
ModCore.CoreMonitor.Log(ob.name);
if (ob.name == "Twig") ModCore.CoreMonitor.Log("Culperate 1");
q.thisLocation.objects.Remove(q.tileLocation);
}
catch(Exception err)
{
}
}
}
removalList.Clear();
int pathCost = 999999999;
List<TileNode> correctPath = new List<TileNode>();
foreach (var potentialPath in paths)
{
if (potentialPath.Count == 0) continue;
if (potentialPath.Count < pathCost)
{
pathCost = potentialPath.Count;
correctPath = potentialPath;
}
}
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
//goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(goodTile, Game1.currentLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize));
}
//END HERE FOR JUST CALCULATING PATH COST
if (paths.Count == 0) return Int32.MaxValue;
return correctPath.Count;
}
/// <summary>
/// This is used to pathfind to a single explicit target.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static List<TileNode> getIdealPath(TileNode target, TileNode Source=null)
{
object[] arr = new object[2];
arr[0] = target;
arr[1] = Source;
return getIdealPath(arr);
}
/// <summary>
/// This is used to pathfind to a single explicit target.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static List<TileNode> getIdealPath(object obj)
{
object[] objArr = (object[])obj;
TileNode v = (TileNode)objArr[0];
TileNode s;
try
{
s = (TileNode)objArr[1];
if (s == null)
{
s = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.RosyBrown));
s.fakePlacementAction(Game1.player.currentLocation, Game1.player.getTileX(), Game1.player.getTileY());
// ModCore.CoreMonitor.Log("WHUT???????");
}
}
catch(Exception err)
{
s = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.RosyBrown));
s.fakePlacementAction(Game1.player.currentLocation, Game1.player.getTileX(), Game1.player.getTileY());
ModCore.CoreMonitor.Log("ICECREAM!!!!!!???????");
}
bool utility = true;
int xMin = -1;
int yMin = -1;
int xMax = 1;
int yMax = 1;
List<TileNode> miniGoals = new List<TileNode>();
List<List<TileNode>> paths = new List<List<TileNode>>();
//try to set children to tiles where children haven't been before
for (int x = xMin; x <= xMax; x++)
{
for (int y = yMin; y <= yMax; y++)
{
if (x == 0 && y == 0) continue;
//Include these 4 checks for just left right up down movement. Remove them to enable 8 direction path finding
if (x == -1 && y == -1) continue; //upper left
if (x == -1 && y == 1) continue; //bottom left
if (x == 1 && y == -1) continue; //upper right
if (x == 1 && y == 1) continue; //bottom right
Vector2 pos = new Vector2(v.tileLocation.X + x, v.tileLocation.Y + y);
//ModCore.CoreMonitor.Log("AHHHHHHH POSITION: " + pos.ToString(), LogLevel.Alert);
bool f = PathFindingCore.TileNode.checkIfICanPlaceHere(v, pos * Game1.tileSize, v.thisLocation, true, utility);
if (f == false)
{
// ModCore.CoreMonitor.Log("FAILED TO PUT DOWN A GOAL????");
ModCore.CoreMonitor.Log(v.thisLocation.ToString()+pos.ToString());
}
// ModCore.CoreMonitor.Log("OK THIS IS THE RESULT F: " + f, LogLevel.Alert);
if (f == true)
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.RosyBrown));
if (placement) t.placementAction(v.thisLocation, (int)pos.X * Game1.tileSize, (int)pos.Y * Game1.tileSize);
else t.fakePlacementAction(v.thisLocation, (int)pos.X, (int)pos.Y);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode( t, Game1.currentLocation, (int)pos.X * Game1.tileSize, (int)pos.Y * Game1.tileSize));
miniGoals.Add(t);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "Navigation"));
}
}
}
List<TileNode> removalList = new List<TileNode>();
Utilities.clearExceptionListWithName("Child");
Utilities.clearExceptionListWithName("Navigation");
TileNode tempSource = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.RosyBrown));
if (placement) tempSource.placementAction(v.thisLocation, Game1.player.getTileX() * Game1.tileSize, Game1.player.getTileY() * Game1.tileSize);
else tempSource.fakePlacementAction(s.thisLocation, (int)s.tileLocation.X, (int)s.tileLocation.Y);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(tempSource, "Navigation"));
//StaardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(tempSource, Game1.currentLocation, Game1.player.getTileX() * Game1.tileSize, Game1.player.getTileY() * Game1.tileSize));
//have this take in a list of goals and see which goal it reaches first
List<TileNode> path = PathFindingCore.PathFindingLogic.pathFindToSingleGoalReturnPath(tempSource, miniGoals, new List<TileNode>(), placement, utility);
if (path.Count == 0)
{
ModCore.CoreMonitor.Log("NOPE, no path I guess.", LogLevel.Warn);
}
else
{
ModCore.CoreMonitor.Log("There is a path", LogLevel.Alert);
ModCore.CoreMonitor.Log("COST OF THE PATH IS: " + path.Count.ToString(), LogLevel.Alert);
}
if (path.Count != 0)
{
//ModCore.CoreMonitor.Log("PATH WAS NOT NULL", LogLevel.Warn);
paths.Add(path);
foreach (var someTile in path)
{
removalList.Add(someTile);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(someTile);
if (placement) someTile.thisLocation.objects.Remove(someTile.tileLocation);
//someTile.performRemoveAction(someTile.tileLocation, someTile.thisLocation);
//StardustCore.Utilities.masterRemovalList.Add(someTile);
//ModCore.CoreMonitor.Log("CAUGHT MY CULPERATE", LogLevel.Warn);
}
}
// Console.WriteLine("GOALS COUNT:" + miniGoals.Count);
foreach (var q in removalList)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(q);
if (placement) q.thisLocation.objects.Remove(q.tileLocation);
}
removalList.Clear();
int pathCost = 999999999;
List<TileNode> correctPath = new List<TileNode>();
foreach (var potentialPath in paths)
{
if (potentialPath.Count == 0) continue;
if (potentialPath.Count < pathCost)
{
pathCost = potentialPath.Count;
correctPath = potentialPath;
}
}
return correctPath;
}
/// <summary>
/// This is used to pathfind to any target that statisfies conditions. The first one hit becomes the new goal.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static List<TileNode> getIdealPath(List<TileNode> t)
{
object[] arr = new object[1];
arr[0] = t;
return getAnyIdealPath(arr);
}
/// <summary>
/// This is used to pathfind to any target that statisfies conditions. The first one hit becomes the new goal.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static List<TileNode> getAnyIdealPath(object obj)
{
object[] objArr = (object[])obj;
List<TileNode> vList = (List<TileNode>)objArr[0];
bool utility = true;
int xMin = -1;
int yMin = -1;
int xMax = 1;
int yMax = 1;
List<TileNode> miniGoals = new List<TileNode>();
List<List<TileNode>> paths = new List<List<TileNode>>();
//try to set children to tiles where children haven't been before
foreach (var v in vList)
{
for (int x = xMin; x <= xMax; x++)
{
for (int y = yMin; y <= yMax; y++)
{
if (x == 0 && y == 0) continue;
//Include these 4 checks for just left right up down movement. Remove them to enable 8 direction path finding
if (x == -1 && y == -1) continue; //upper left
if (x == -1 && y == 1) continue; //bottom left
if (x == 1 && y == -1) continue; //upper right
if (x == 1 && y == 1) continue; //bottom right
Vector2 pos = new Vector2(v.tileLocation.X + x, v.tileLocation.Y + y);
//ModCore.CoreMonitor.Log("AHHHHHHH POSITION: " + pos.ToString(), LogLevel.Alert);
bool f = PathFindingCore.TileNode.checkIfICanPlaceHere(v, pos * Game1.tileSize, v.thisLocation, true, utility);
// ModCore.CoreMonitor.Log("OK THIS IS THE RESULT F: " + f, LogLevel.Alert);
if (f == true)
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.RosyBrown));
if (placement) t.placementAction(v.thisLocation, (int)pos.X * Game1.tileSize, (int)pos.Y * Game1.tileSize);
else t.fakePlacementAction(v.thisLocation, (int)pos.X, (int)pos.Y);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode( t, Game1.currentLocation, (int)pos.X * Game1.tileSize, (int)pos.Y * Game1.tileSize));
miniGoals.Add(t);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "Navigation"));
}
}
}
}
List<TileNode> removalList = new List<TileNode>();
Utilities.clearExceptionListWithName("Child");
Utilities.clearExceptionListWithName("Navigation");
TileNode tempSource = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.RosyBrown));
if (placement) tempSource.placementAction(Game1.player.currentLocation, Game1.player.getTileX() * Game1.tileSize, Game1.player.getTileY() * Game1.tileSize);
else tempSource.fakePlacementAction(Game1.player.currentLocation, Game1.player.getTileX(), Game1.player.getTileY());
Utilities.tileExceptionList.Add(new TileExceptionMetaData(tempSource, "Navigation"));
//StaardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(tempSource, Game1.currentLocation, Game1.player.getTileX() * Game1.tileSize, Game1.player.getTileY() * Game1.tileSize));
//have this take in a list of goals and see which goal it reaches first
List<TileNode> path = PathFindingCore.PathFindingLogic.pathFindToSingleGoalReturnPath(tempSource, miniGoals, new List<TileNode>(), placement, utility);
ModCore.CoreMonitor.Log("OK MY PATH IS:" + path.Count);
Utilities.clearExceptionListWithName("Child");
Utilities.clearExceptionListWithName("Navigation");
if (path.Count == 0)
{
ModCore.CoreMonitor.Log("NOPE, no path I guess.", LogLevel.Warn);
}
else
{
ModCore.CoreMonitor.Log("There is a path", LogLevel.Alert);
ModCore.CoreMonitor.Log("COST OF THE PATH IS: " + path.Count.ToString(), LogLevel.Alert);
}
if (path.Count != 0)
{
//ModCore.CoreMonitor.Log("PATH WAS NOT NULL", LogLevel.Warn);
paths.Add(path);
foreach (var someTile in path)
{
removalList.Add(someTile);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(someTile);
if (placement) someTile.thisLocation.objects.Remove(someTile.tileLocation);
//someTile.performRemoveAction(someTile.tileLocation, someTile.thisLocation);
//StardustCore.Utilities.masterRemovalList.Add(someTile);
//ModCore.CoreMonitor.Log("CAUGHT MY CULPERATE", LogLevel.Warn);
}
}
Console.WriteLine("GOALS COUNT:" + miniGoals.Count);
foreach (var q in removalList)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(q);
if (placement) q.thisLocation.objects.Remove(q.tileLocation);
}
removalList.Clear();
int pathCost = 999999999;
List<TileNode> correctPath = new List<TileNode>();
foreach (var potentialPath in paths)
{
if (potentialPath.Count == 0) continue;
if (potentialPath.Count < pathCost)
{
pathCost = potentialPath.Count;
correctPath = potentialPath;
}
}
return correctPath;
}
}
}

View File

@ -0,0 +1,42 @@
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.ShopCore
{
class ShopLogic
{
public static void openSeedShopMenu()
{
Game1.activeClickableMenu = new StardewValley.Menus.ShopMenu(UtilityCore.SeedCropUtility.sortSeedListByUtility(getGeneralStoreSeedStock(true)));
}
public static List<Item> getGeneralStoreSeedStock(bool removeExpensiveItems){
List<Item> buyableSeeds = new List<Item>();
foreach (var location in Game1.locations)
{
if (location.name == "SeedShop")
{
List<Item> stock=(location as StardewValley.Locations.SeedShop).shopStock();
foreach(var item in stock)
{
if (item.getCategoryName() == "Seed")
{
if (removeExpensiveItems)
{
if (item.salePrice() > Game1.player.money) continue;
}
buyableSeeds.Add(item);
}
}
return buyableSeeds;
}
}
return buyableSeeds;
}
}
}

120
StarAI/StarAI/StarAI.csproj Normal file
View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{93632675-991D-425B-96F9-9C2B6BFC4EFE}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>StarAI</RootNamespace>
<AssemblyName>StarAI</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="ConsoleCommands">
<HintPath>..\..\..\..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Stardew Valley\Mods\ConsoleCommands\ConsoleCommands.dll</HintPath>
</Reference>
<Reference Include="InputSimulator">
<HintPath>..\..\..\..\..\..\..\Downloads\InputSimulator.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\GeneralMods\StardustCore\bin\Release\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="StardustCore">
<HintPath>..\..\GeneralMods\StardustCore\bin\Release\StardustCore.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CheatCore\DoorsToWarps.cs" />
<Compile Include="Commands.cs" />
<Compile Include="DialogueCore\ReponseLogic.cs" />
<Compile Include="ExecutionCore\CustomTask.cs" />
<Compile Include="ExecutionCore\TaskList.cs" />
<Compile Include="ExecutionCore\TaskMetaData.cs" />
<Compile Include="ExecutionCore\TaskMetaDataHeuristics.cs" />
<Compile Include="ExecutionCore\TaskPrerequisites\BedTimePrerequisite.cs" />
<Compile Include="ExecutionCore\TaskPrerequisites\GenericPrerequisite.cs" />
<Compile Include="ExecutionCore\TaskPrerequisites\InventoryFullPrerequisite.cs" />
<Compile Include="ExecutionCore\TaskPrerequisites\ItemPrerequisite.cs" />
<Compile Include="ExecutionCore\TaskPrerequisites\LocationPrerequisite.cs" />
<Compile Include="ExecutionCore\TaskPrerequisites\StaminaPrerequisite.cs" />
<Compile Include="ExecutionCore\TaskPrerequisites\ToolPrerequisite.cs" />
<Compile Include="InterfaceCore\InterfaceLogic.cs" />
<Compile Include="InterfaceCore\ShippingMenuCore.cs" />
<Compile Include="MenuCore\CropUtilityMenu.cs" />
<Compile Include="ModCore.cs" />
<Compile Include="ShopCore\ShopLogic.cs" />
<Compile Include="TaskCore\ChestLogic.cs" />
<Compile Include="TaskCore\CropLogic\CropLogic.cs" />
<Compile Include="TaskCore\CropLogic\SeedLogic.cs" />
<Compile Include="TaskCore\CropLogic\ShippingLogic.cs" />
<Compile Include="TaskCore\DebrisLogic\DebrisLogic.cs" />
<Compile Include="TaskCore\MapTransitionLogic\TransitionLogic.cs" />
<Compile Include="TaskCore\MapTransitionLogic\WarpGoal.cs" />
<Compile Include="PathFindingCore\PathFindingLogic.cs" />
<Compile Include="TaskCore\MapTransitionLogic\WayPoints.cs" />
<Compile Include="PathFindingCore\TileNodes\PlacementNode.cs" />
<Compile Include="PathFindingCore\TileNodes\TileExceptionMetaData.cs" />
<Compile Include="PathFindingCore\TileNodes\TileExceptionNode.cs" />
<Compile Include="PathFindingCore\TileNodes\TileNodeObject.cs" />
<Compile Include="PathFindingCore\Utilities.cs" />
<Compile Include="TaskCore\WaterLogic\WaterLogic.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UtilityCore\SeedCropUtility.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\Pathoschild.Stardew.ModBuildConfig.2.0.2\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.0.2\build\Pathoschild.Stardew.ModBuildConfig.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.0.2\build\Pathoschild.Stardew.ModBuildConfig.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Pathoschild.Stardew.ModBuildConfig.2.0.2\build\Pathoschild.Stardew.ModBuildConfig.targets'))" />
</Target>
<Import Project="..\..\GeneralMods\packages\Pathoschild.Stardew.ModBuildConfig.2.0.2\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\..\GeneralMods\packages\Pathoschild.Stardew.ModBuildConfig.2.0.2\build\Pathoschild.Stardew.ModBuildConfig.targets')" />
</Project>

View File

@ -1,188 +0,0 @@
using Microsoft.Xna.Framework;
using StardewModdingAPI;
using StardewValley;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WindowsInput;
namespace StarAI.PathFindingCore
{
public class Utilities
{
public static List<TileExceptionMetaData> tileExceptionList = new List<TileExceptionMetaData>();
public static List<TileExceptionNode> ignoreCheckTiles = new List<TileExceptionNode>();
public static string folderForExceptionTiles="ExceptionTilesData";
public static Vector2 parseCenterFromTile(int tileX, int tileY)
{
//int x = (tileX * Game1.tileSize) + Game1.tileSize / 2;
//int y = (tileY * Game1.tileSize) + Game1.tileSize / 2;
int x = (tileX * Game1.tileSize);
int y = (tileY * Game1.tileSize);
return new Vector2(x, y);
}
public static void initializeTileExceptionList()
{
}
public static void cleanExceptionList(TileNode t)
{
TileExceptionMetaData err= new TileExceptionMetaData(null,"");
foreach (var v in tileExceptionList)
{
if (v.tile == t) err = v;
}
if(err.tile != null)
{
tileExceptionList.Remove(err);
}
}
/// <summary>
/// Used to calculate center of a tile with varience.
/// </summary>
/// <param name="position"></param>
/// <param name="goal"></param>
/// <param name="tolerance"></param>
/// <returns></returns>
public static bool isWithinRange(float position, float goal, int tolerance)
{
if (position >= goal - tolerance && position <= goal + tolerance) return true;
return false;
}
public static int calculatePathCost(TileNode v, bool Placement = true)
{
object[] obj = new object[2];
obj[0] = v;
obj[1] = Placement;
return calculatePathCost(obj);
}
public static int calculatePathCost(object obj)
{
object[] objArr = (object[])obj;
TileNode v = (TileNode)objArr[0];
bool placement;
try
{
placement = (bool)objArr[1];
}
catch(Exception err)
{
placement = true;
}
foreach (var q in objArr)
{
ModCore.CoreMonitor.Log("OK THIS IS THE RESULT !: " + q, LogLevel.Alert);
}
if (v == null) ModCore.CoreMonitor.Log("WTF MARK!!!!!!: ", LogLevel.Alert);
bool moveOn = false;
WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.VK_X);
int xMin = -1;
int yMin = -1;
int xMax = 1;
int yMax = 1;
List<TileNode> miniGoals = new List<TileNode>();
List<List<TileNode>> paths = new List<List<TileNode>>();
//try to set children to tiles where children haven't been before
for (int x = xMin; x <= xMax; x++)
{
for (int y = yMin; y <= yMax; y++)
{
if (x == 0 && y == 0) continue;
//Include these 4 checks for just left right up down movement. Remove them to enable 8 direction path finding
if (x == -1 && y == -1) continue; //upper left
if (x == -1 && y == 1) continue; //bottom left
if (x == 1 && y == -1) continue; //upper right
if (x == 1 && y == 1) continue; //bottom right
Vector2 pos = new Vector2(v.tileLocation.X + x, v.tileLocation.Y + y);
//ModCore.CoreMonitor.Log("AHHHHHHH POSITION: " + pos.ToString(), LogLevel.Alert);
bool f = PathFindingCore.TileNode.checkIfICanPlaceHere(v, pos * Game1.tileSize, v.thisLocation, true);
ModCore.CoreMonitor.Log("OK THIS IS THE RESULT F: " + f, LogLevel.Alert);
if (f == true)
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.RosyBrown));
if(placement)t.placementAction(Game1.currentLocation, (int)pos.X * Game1.tileSize, (int)pos.Y * Game1.tileSize);
else t.fakePlacementAction(v.thisLocation, (int)pos.X, (int)pos.Y);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(t, Game1.currentLocation, (int)pos.X * Game1.tileSize, (int)pos.Y * Game1.tileSize));
miniGoals.Add(t);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "CropNavigation"));
}
}
}
List<TileNode> removalList = new List<TileNode>();
foreach (var nav in miniGoals)
{
TileNode tempSource = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.RosyBrown));
if(placement)tempSource.placementAction(Game1.player.currentLocation, Game1.player.getTileX() * Game1.tileSize, Game1.player.getTileY() * Game1.tileSize);
else tempSource.fakePlacementAction(Game1.player.currentLocation, Game1.player.getTileX(), Game1.player.getTileY());
List<TileNode> path = PathFindingCore.PathFindingLogic.pathFindToSingleGoalReturnPath(tempSource, nav, new List<TileNode>(), placement);
ModCore.CoreMonitor.Log(tempSource.tileLocation.ToString()+tempSource.tileLocation.ToString());
ModCore.CoreMonitor.Log(nav.tileLocation.ToString() + nav.tileLocation.ToString());
if (path.Count != 0)
{
ModCore.CoreMonitor.Log("PATH WAS NOT NULL", LogLevel.Warn);
paths.Add(path);
foreach (var someTile in path)
{
if (someTile == nav) removalList.Add(someTile);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(someTile);
if(placement)someTile.thisLocation.objects.Remove(someTile.tileLocation);
//someTile.performRemoveAction(someTile.tileLocation, someTile.thisLocation);
//StardustCore.Utilities.masterRemovalList.Add(v);
}
}
}
foreach (var q in removalList)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(q);
if(placement)q.thisLocation.objects.Remove(q.tileLocation);
}
removalList.Clear();
int pathCost = 999999999;
List<TileNode> correctPath = new List<TileNode>();
foreach (var potentialPath in paths)
{
if (potentialPath.Count == 0) continue;
if (potentialPath.Count < pathCost)
{
pathCost = potentialPath.Count;
correctPath = potentialPath;
}
}
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
//goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(goodTile, Game1.currentLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize));
}
//END HERE FOR JUST CALCULATING PATH COST
if (paths.Count == 0) return Int32.MaxValue;
return correctPath.Count;
}
}
}

View File

@ -0,0 +1,207 @@
using Microsoft.Xna.Framework;
using StarAI.PathFindingCore;
using StardewModdingAPI;
using StardewValley;
using StardewValley.Objects;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.TaskCore
{
class ChestLogic
{
public static List<TileNode> chestsAtThisLocation = new List<TileNode>();
public static void getAllSeasonalSeedsFromAllChestsAtLocation(GameLocation location)
{
object[] arr = new object[1];
arr[0] = location;
getAllSeasonalSeedsFromAllChestsAtLocation(arr);
}
public static void getAllSeasonalSeedsFromAllChestsAtLocation(object obj)
{
object[] objArr = (object[])obj;
GameLocation location = (GameLocation)objArr[0];
foreach (var v in location.objects)
{
ModCore.CoreMonitor.Log(v.Value.name);
if (v.Value is StardewValley.Objects.Chest)
{
//if contains seeds that can be planted this season.
foreach(var item in (v.Value as StardewValley.Objects.Chest).items)
{
if (item.getCategoryName() == "Seed")
{
StardewValley.Crop c = new Crop(item.parentSheetIndex, 0, 0);
if (c.seasonsToGrowIn.Contains(Game1.currentSeason))
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
//t.placementAction(Game1.currentLocation, (int)v.Key.X * Game1.tileSize, (int)v.Key.Y * Game1.tileSize);
t.tileLocation=new Vector2((int)v.Key.X, (int)v.Key.Y);
t.position = new Vector2(v.Key.X*Game1.tileSize, v.Key.Y*Game1.tileSize);
t.thisLocation = location;
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(t, Game1.currentLocation, (int)v.Key.X * Game1.tileSize, (int)v.Key.Y * Game1.tileSize));
Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "Chest"));
chestsAtThisLocation.Add(t);
}
}
}
}
}
foreach (var v in chestsAtThisLocation)
{
object[] objList = new object[2];
objList[0] = v;
// ExecutionCore.TaskList.taskList.Add(new Task(new Action<object>(waterSingleCrop), obj));
ExecutionCore.CustomTask task = new ExecutionCore.CustomTask(pathToSingleChest, objList, new ExecutionCore.TaskMetaData("GetSeasonalSeedsFromChest",new ExecutionCore.TaskPrerequisites.LocationPrerequisite(v.thisLocation), null, null, new ExecutionCore.TaskPrerequisites.InventoryFullPrerequisite(true)));
if (task.taskMetaData.cost == Int32.MaxValue)
{
Utilities.clearExceptionListWithNames(true);
continue;
}
ExecutionCore.TaskList.taskList.Add(task);
//Utilities.clearExceptionListWithName(true, "Child");
if (task.taskMetaData.pathsToTake == null)
{
ModCore.CoreMonitor.Log("WTF???");
}
ModCore.CoreMonitor.Log("COST:"+task.taskMetaData.cost);
objList[1] = task.taskMetaData.pathsToTake[0];
task.objectParameterDataArray = objList;
Utilities.clearExceptionListWithName("Child");
Utilities.clearExceptionListWithName("Navigation");
// waterSingleCrop(v);
}
chestsAtThisLocation.Clear();
}
public static void pathToSingleChest(object obj)
{
object[] objArray = (object[])obj;
TileNode v = (TileNode)objArray[0];
//List<TileNode> correctPath = Utilities.pathStuff(v);//(List<TileNode>)objArray[1];
List<TileNode> correctPath = (List<TileNode>)objArray[1];
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(goodTile, Game1.currentLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize));
goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
PathFindingLogic.calculateMovement(correctPath);
if (v.tileLocation.X < Game1.player.getTileX())
{
Game1.player.faceDirection(3);
}
else if (v.tileLocation.X > Game1.player.getTileX())
{
Game1.player.faceDirection(1);
}
else if (v.tileLocation.Y < Game1.player.getTileY())
{
Game1.player.faceDirection(0);
}
else if (v.tileLocation.Y > Game1.player.getTileY())
{
Game1.player.faceDirection(2);
}
bool move = false;
Chest chest =(Chest) v.thisLocation.objects[v.tileLocation];
List<Item> removalListSeeds = new List<Item>();
//Try to grab all the seeds I can from the chest.
while (Game1.player.isInventoryFull()==false&&chest.items.Count>0)
{
if (chest.giftbox)
{
ModCore.CoreMonitor.Log("GIFT BOX", LogLevel.Warn);
v.thisLocation.objects.Remove(v.tileLocation);
}
foreach (var item in chest.items)
{
if (item.getCategoryName() == "Seed")
{
int seedIndex = item.parentSheetIndex;
if (seedIndex == 770)
{
seedIndex = Crop.getRandomLowGradeCropForThisSeason(Game1.currentSeason);
if (seedIndex == 473)
--seedIndex;
}
StardewValley.Crop c = new Crop(seedIndex, 0, 0);
if (c.seasonsToGrowIn.Contains(Game1.currentSeason))
{
Game1.player.addItemByMenuIfNecessary(item);
removalListSeeds.Add(item);
break;
}
}
}
foreach(var remove in removalListSeeds)
{
chest.items.Remove(remove);
}
// if (WindowsInput.InputSimulator.IsKeyDown(WindowsInput.VirtualKeyCode.VK_C) == false) WindowsInput.InputSimulator.SimulateKeyDown(WindowsInput.VirtualKeyCode.VK_C);
Vector2 center = new Vector2();
if (Game1.player.facingDirection == 2)
{
center = Utilities.parseCenterFromTile((int)v.tileLocation.X + 1, (int)v.tileLocation.Y);
continue;
}
if (Game1.player.facingDirection == 1)
{
center = Utilities.parseCenterFromTile((int)v.tileLocation.X - 1, (int)v.tileLocation.Y);
continue;
}
if (Game1.player.facingDirection == 0)
{
center = Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y + 1);
continue;
}
if (Game1.player.facingDirection == 3)
{
center = Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y - 1);
continue;
}
Game1.player.position = center;
}
Utilities.cleanExceptionList(v);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
// StardustCore.Utilities.masterRemovalList.Add(v);
//v.performRemoveAction(v.tileLocation, v.thisLocation);
// v.thisLocation.objects.Remove(v.tileLocation);
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(goodTile);
//StardustCore.Utilities.masterRemovalList.Add(v);
goodTile.performRemoveAction(goodTile.tileLocation, goodTile.thisLocation);
//goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
//WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.VK_C);
}
}
}

View File

@ -0,0 +1,328 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StardewModdingAPI;
using StardustCore;
using StardewValley;
using Microsoft.Xna.Framework;
using System.IO;
using StarAI.ExecutionCore.TaskPrerequisites;
using StarAI.PathFindingCore;
namespace StarAI.TaskCore.CropLogic
{
class CropLogic
{
public static List<TileNode> cropsToWater = new List<TileNode>();
public static List<TileNode> cropsToHarvest = new List<TileNode>();
public static void getAllCropsNeededToBeWatered()
{
foreach (var v in Game1.player.currentLocation.terrainFeatures)
{
if (v.Value is StardewValley.TerrainFeatures.HoeDirt)
{
if ((v.Value as StardewValley.TerrainFeatures.HoeDirt).crop != null)
{
//cropsToWater.Add(v.Key);
//If my dirt needs to be watered and the crop isn't fully grown.
if ((v.Value as StardewValley.TerrainFeatures.HoeDirt).state==0 && isCropFullGrown((v.Value as StardewValley.TerrainFeatures.HoeDirt).crop) == false)
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.LightSkyBlue));
t.placementAction(Game1.currentLocation, (int)v.Key.X * Game1.tileSize, (int)v.Key.Y * Game1.tileSize);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(t, Game1.currentLocation, (int)v.Key.X * Game1.tileSize, (int)v.Key.Y * Game1.tileSize));
PathFindingCore.Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "Water"));
cropsToWater.Add(t);
}
}
}
}
//Instead of just running this function I should add it to my execution queue.
foreach(var v in cropsToWater)
{
object[] obj = new object[2];
obj[0] = v;
// ExecutionCore.TaskList.taskList.Add(new Task(new Action<object>(waterSingleCrop), obj));
StardewValley.Tools.WateringCan w = new StardewValley.Tools.WateringCan();
ExecutionCore.CustomTask task = new ExecutionCore.CustomTask(waterSingleCrop, obj, new ExecutionCore.TaskMetaData("Water Crop", new LocationPrerequisite(v.thisLocation),new StaminaPrerequisite(true, 3), new ToolPrerequisite(true, w.GetType(), 1)));
if (task.taskMetaData.cost == Int32.MaxValue)
{
StarAI.PathFindingCore.Utilities.clearExceptionListWithNames(true);
continue;
}
ExecutionCore.TaskList.taskList.Add(task);
obj[1] = task.taskMetaData.pathsToTake[0];
task.objectParameterDataArray = obj;
// waterSingleCrop(v);
StarAI.PathFindingCore.Utilities.clearExceptionListWithName("Child");
}
cropsToWater.Clear();
}
public static void waterSingleCrop(TileNode v,List<TileNode> path)
{
object[] obj = new object[2];
obj[0] = v;
obj[1] = path;
waterSingleCrop(obj);
}
public static void waterSingleCrop(object obj) {
object[] objArray = (object[])obj;
TileNode v = (TileNode)objArray[0];
//List<TileNode> correctPath = Utilities.pathStuff(v);//(List<TileNode>)objArray[1];
List<TileNode> correctPath = (List<TileNode>)objArray[1];
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(goodTile, Game1.currentLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize));
goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
PathFindingLogic.calculateMovement(correctPath);
if (v.tileLocation.X < Game1.player.getTileX())
{
Game1.player.faceDirection(3);
}
else if (v.tileLocation.X > Game1.player.getTileX())
{
Game1.player.faceDirection(1);
}
else if (v.tileLocation.Y < Game1.player.getTileY())
{
Game1.player.faceDirection(0);
}
else if (v.tileLocation.Y > Game1.player.getTileY())
{
Game1.player.faceDirection(2);
}
foreach (var item in Game1.player.items)
{
if(item is StardewValley.Tools.WateringCan)
{
Game1.player.CurrentToolIndex = Game1.player.getIndexOfInventoryItem(item);
}
}
bool move = false;
while ((v.thisLocation.terrainFeatures[v.tileLocation] as StardewValley.TerrainFeatures.HoeDirt).state==0)
{
if(WindowsInput.InputSimulator.IsKeyDown(WindowsInput.VirtualKeyCode.VK_C)==false) WindowsInput.InputSimulator.SimulateKeyDown(WindowsInput.VirtualKeyCode.VK_C);
Vector2 center=new Vector2();
if (Game1.player.facingDirection == 2)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X+1, (int)v.tileLocation.Y);
continue;
}
if (Game1.player.facingDirection == 1)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X-1, (int)v.tileLocation.Y);
continue;
}
if (Game1.player.facingDirection == 0)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y+1);
continue;
}
if (Game1.player.facingDirection == 3)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y-1);
continue;
}
Game1.player.position = center;
//Game1.setMousePosition((int)v.tileLocation.X*Game1.tileSize/2,(int)v.tileLocation.Y*Game1.tileSize/2);
ModCore.CoreMonitor.Log("DOESNT WATER LIKE YOU THINK IT SHOULD");
ModCore.CoreMonitor.Log("player pos: "+Game1.player.position.ToString(),LogLevel.Warn);
ModCore.CoreMonitor.Log("TilePos: "+v.position.ToString(), LogLevel.Error);
}
StarAI.PathFindingCore.Utilities.cleanExceptionList(v);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
// StardustCore.Utilities.masterRemovalList.Add(v);
//v.performRemoveAction(v.tileLocation, v.thisLocation);
v.thisLocation.objects.Remove(v.tileLocation);
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(goodTile);
//StardustCore.Utilities.masterRemovalList.Add(v);
goodTile.performRemoveAction(goodTile.tileLocation, goodTile.thisLocation);
//goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.VK_C);
}
public static void getAllCropsNeededToBeHarvested()
{
foreach (var v in Game1.player.currentLocation.terrainFeatures)
{
if (v.Value is StardewValley.TerrainFeatures.HoeDirt)
{
if ((v.Value as StardewValley.TerrainFeatures.HoeDirt).crop != null)
{
//If my dirt needs to be watered and the crop isn't fully grown.
if (isCropFullGrown((v.Value as StardewValley.TerrainFeatures.HoeDirt).crop))
{
ModCore.CoreMonitor.Log("OK!!!!");
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.LimeGreen));
t.placementAction(Game1.currentLocation, (int)v.Key.X * Game1.tileSize, (int)v.Key.Y * Game1.tileSize);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(t, Game1.currentLocation, (int)v.Key.X * Game1.tileSize, (int)v.Key.Y * Game1.tileSize));
StarAI.PathFindingCore.Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "Harvest"));
cropsToHarvest.Add(t);
}
}
}
}
//Instead of just running this function I should add it to my execution queue.
foreach (var v in cropsToHarvest)
{
object[] obj = new object[2];
obj[0] = v;
//ExecutionCore.TaskList.taskList.Add(new Task(new Action<object>(harvestSingleCrop), obj));
ExecutionCore.CustomTask task = new ExecutionCore.CustomTask(harvestSingleCrop, obj, new ExecutionCore.TaskMetaData("HarvestSingleCrop",new LocationPrerequisite(v.thisLocation) ,null, null, new ExecutionCore.TaskPrerequisites.InventoryFullPrerequisite(true)));
if (task.taskMetaData.cost == Int32.MaxValue)
{
StarAI.PathFindingCore.Utilities.clearExceptionListWithNames(true);
continue;
}
ExecutionCore.TaskList.taskList.Add(task);
obj[1] = task.taskMetaData.pathsToTake[0];
task.objectParameterDataArray = obj;
StarAI.PathFindingCore.Utilities.clearExceptionListWithName("Child");
// waterSingleCrop(v);
}
cropsToHarvest.Clear();
}
public static void harvestSingleCrop(TileNode v,List<TileNode> path)
{
object[] obj = new object[2];
obj[0] = v;
obj[1] = path;
harvestSingleCrop(obj);
}
public static void harvestSingleCrop(object obj)
{
object[] objArray = (object[])obj;
TileNode v = (TileNode)objArray[0];
//List<TileNode> correctPath = Utilities.pathStuff(v);//(List<TileNode>)objArray[1];
List<TileNode> correctPath = (List<TileNode>)objArray[1];
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(goodTile, Game1.currentLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize));
goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
PathFindingLogic.calculateMovement(correctPath);
if (v.tileLocation.X < Game1.player.getTileX())
{
Game1.player.faceDirection(3);
}
else if (v.tileLocation.X > Game1.player.getTileX())
{
Game1.player.faceDirection(1);
}
else if (v.tileLocation.Y < Game1.player.getTileY())
{
Game1.player.faceDirection(0);
}
else if (v.tileLocation.Y > Game1.player.getTileY())
{
Game1.player.faceDirection(2);
}
/*
foreach (var item in Game1.player.items)
{
//if (item is StardewValley.Tools.WateringCan)
//{
// Game1.player.CurrentToolIndex = Game1.player.getIndexOfInventoryItem(item);
//}
}
*/
bool move = false;
while ((v.thisLocation.terrainFeatures[v.tileLocation] as StardewValley.TerrainFeatures.HoeDirt).crop !=null)
{
if (WindowsInput.InputSimulator.IsKeyDown(WindowsInput.VirtualKeyCode.VK_X) == false) WindowsInput.InputSimulator.SimulateKeyDown(WindowsInput.VirtualKeyCode.VK_X);
Vector2 center = new Vector2();
if (Game1.player.facingDirection == 2)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X + 1, (int)v.tileLocation.Y);
continue;
}
if (Game1.player.facingDirection == 1)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X - 1, (int)v.tileLocation.Y);
continue;
}
if (Game1.player.facingDirection == 0)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y + 1);
continue;
}
if (Game1.player.facingDirection == 3)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y - 1);
continue;
}
Game1.player.position = center;
}
StarAI.PathFindingCore.Utilities.cleanExceptionList(v);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
v.thisLocation.objects.Remove(v.tileLocation);
//v.performRemoveAction(v.tileLocation, v.thisLocation);
//StardustCore.Utilities.masterRemovalList.Add(v);
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(goodTile, Game1.currentLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize));
goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.VK_X);
}
public static bool isCropFullGrown(Crop c)
{
if (c.currentPhase >= c.phaseDays.Count - 1)
{
c.currentPhase = c.phaseDays.Count - 1;
c.dayOfCurrentPhase = 0;
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,369 @@
using Microsoft.Xna.Framework;
using StarAI.ExecutionCore.TaskPrerequisites;
using StarAI.PathFindingCore;
using StardewModdingAPI;
using StardewValley;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using xTile.Dimensions;
namespace StarAI.TaskCore.CropLogic
{
class SeedLogic
{
public static void makeAsMuchDirtAsSpecifiedAroundFarmer(GameLocation location, int amount, int radius)
{
List<TileNode> hoeDirtThings = new List<TileNode>();
for(int i = -radius; i <= radius;i++)
{
for (int j = -radius; j <= radius;j++)
{
Vector2 position = new Vector2(Game1.player.getTileX() + i, Game1.player.getTileY() + j);
//if (hoeDirtThings.Count >= amount) continue;
if(canBeHoeDirt(location, position))
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.LightSkyBlue));
//t.placementAction(Game1.currentLocation, (int)i* Game1.tileSize, (int)j * Game1.tileSize);
t.fakePlacementAction(location, (int)position.X,(int)position.Y);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(t, Game1.currentLocation, (int)v.Key.X * Game1.tileSize, (int)v.Key.Y * Game1.tileSize));
PathFindingCore.Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "HoeDirt"));
hoeDirtThings.Add(t);
}
}
}
int taskAmount = 0;
foreach (var v in hoeDirtThings)
{
if (taskAmount >= amount) break;
object[] obj = new object[2];
obj[0] = v;
// ExecutionCore.TaskList.taskList.Add(new Task(new Action<object>(waterSingleCrop), obj));
StardewValley.Tools.Hoe w = new StardewValley.Tools.Hoe();
ExecutionCore.CustomTask task = new ExecutionCore.CustomTask(hoeSingleTileOfDirt, obj, new ExecutionCore.TaskMetaData("Dig Dirt", new LocationPrerequisite(v.thisLocation), new StaminaPrerequisite(true, 3), new ToolPrerequisite(true, w.GetType(), 1)));
if (task.taskMetaData.cost == Int32.MaxValue)
{
StarAI.PathFindingCore.Utilities.clearExceptionListWithNames(true);
Utilities.tileExceptionList.Clear();
continue;
}
ExecutionCore.TaskList.taskList.Add(task);
taskAmount++;
obj[1] = task.taskMetaData.pathsToTake[0];
task.objectParameterDataArray = obj;
// waterSingleCrop(v);
StarAI.PathFindingCore.Utilities.clearExceptionListWithName("Child");
}
hoeDirtThings.Clear();
}
public static void hoeSingleTileOfDirt(object obj)
{
object[] objArray = (object[])obj;
TileNode v = (TileNode)objArray[0];
//List<TileNode> correctPath = Utilities.pathStuff(v);//(List<TileNode>)objArray[1];
List<TileNode> correctPath = (List<TileNode>)objArray[1];
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(goodTile, Game1.currentLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize));
goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
PathFindingLogic.calculateMovement(correctPath);
if (v.tileLocation.X < Game1.player.getTileX())
{
Game1.player.faceDirection(3);
}
else if (v.tileLocation.X > Game1.player.getTileX())
{
Game1.player.faceDirection(1);
}
else if (v.tileLocation.Y < Game1.player.getTileY())
{
Game1.player.faceDirection(0);
}
else if (v.tileLocation.Y > Game1.player.getTileY())
{
Game1.player.faceDirection(2);
}
foreach (var item in Game1.player.items)
{
if (item is StardewValley.Tools.Hoe)
{
Game1.player.CurrentToolIndex = Game1.player.getIndexOfInventoryItem(item);
}
}
bool move = false;
while (Game1.player.currentLocation.isTileHoeDirt(v.tileLocation)==false)
{
if (WindowsInput.InputSimulator.IsKeyDown(WindowsInput.VirtualKeyCode.VK_C) == false) WindowsInput.InputSimulator.SimulateKeyDown(WindowsInput.VirtualKeyCode.VK_C);
Vector2 center = new Vector2();
if (Game1.player.facingDirection == 2)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X + 1, (int)v.tileLocation.Y);
continue;
}
if (Game1.player.facingDirection == 1)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X - 1, (int)v.tileLocation.Y);
continue;
}
if (Game1.player.facingDirection == 0)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y + 1);
continue;
}
if (Game1.player.facingDirection == 3)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y - 1);
continue;
}
Game1.player.position = center;
//Game1.setMousePosition((int)v.tileLocation.X*Game1.tileSize/2,(int)v.tileLocation.Y*Game1.tileSize/2);
ModCore.CoreMonitor.Log("DOESNT Dig dirt LIKE YOU THINK IT SHOULD");
ModCore.CoreMonitor.Log("player pos: " + Game1.player.position.ToString(), LogLevel.Warn);
ModCore.CoreMonitor.Log("TilePos: " + v.position.ToString(), LogLevel.Error);
}
StarAI.PathFindingCore.Utilities.cleanExceptionList(v);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
// StardustCore.Utilities.masterRemovalList.Add(v);
//v.performRemoveAction(v.tileLocation, v.thisLocation);
v.thisLocation.objects.Remove(v.tileLocation);
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(goodTile);
//StardustCore.Utilities.masterRemovalList.Add(v);
goodTile.performRemoveAction(goodTile.tileLocation, goodTile.thisLocation);
//goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.VK_C);
}
public static bool canBeHoeDirt(GameLocation location, Vector2 tileLocation)
{
if (location.doesTileHaveProperty((int)tileLocation.X, (int)tileLocation.Y, "Diggable", "Back") == null || location.isTileOccupied(tileLocation, "") || !location.isTilePassable(new Location((int)tileLocation.X, (int)tileLocation.Y), Game1.viewport))
return false;
else return true;
//this.terrainFeatures.Add(tileLocation, (TerrainFeature)new HoeDirt(!Game1.isRaining || !this.isOutdoors ? 0 : 1));
}
public static Crop parseCropFromSeedIndex(int index)
{
return new Crop(index, 0, 0);
}
public static KeyValuePair<int, Crop> getSeedCropPair(int index) {
return new KeyValuePair<int, Crop>(index, parseCropFromSeedIndex(index));
}
public static void buySeeds()
{
var retList = UtilityCore.SeedCropUtility.sortSeedListByUtility(ShopCore.ShopLogic.getGeneralStoreSeedStock(true));
var item = retList.ElementAt(0);
item.Stack++;
while (Game1.player.money >= item.salePrice())
{
item.Stack++;
Game1.player.money -= item.salePrice();
}
Game1.player.addItemToInventoryBool(item);
}
public static void plantSeeds(GameLocation location2)
{
List<TileNode> seedsToPlant = new List<TileNode>();
GameLocation location = Game1.getLocationFromName("Farm");
string name = "";
foreach (var seed in Game1.player.items)
{
if (seed == null) continue;
if (seed.getCategoryName() == "Seed")
{
if (parseCropFromSeedIndex(seed.parentSheetIndex).seasonsToGrowIn.Contains(Game1.currentSeason))
{
name = seed.Name;
}
}
}
if (name == "")
{
ModCore.CoreMonitor.Log("Error: No valid seeds to plant found in inventory. Try to go buy some");
Utilities.tileExceptionList.Clear();
return;
}
foreach (var terrain in location.terrainFeatures)
{
if (terrain.Value is StardewValley.TerrainFeatures.HoeDirt)
{
//Vector2 position = new Vector2(Game1.player.getTileX() + i, Game1.player.getTileY() + j);
//if (hoeDirtThings.Count >= amount) continue;
if ((terrain.Value as StardewValley.TerrainFeatures.HoeDirt).crop != null) continue;
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.LightSkyBlue));
//t.placementAction(Game1.currentLocation, (int)i* Game1.tileSize, (int)j * Game1.tileSize);
t.fakePlacementAction(location, (int)terrain.Key.X, (int)terrain.Key.Y);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(t, Game1.currentLocation, (int)v.Key.X * Game1.tileSize, (int)v.Key.Y * Game1.tileSize));
PathFindingCore.Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "PlantSeeds"));
seedsToPlant.Add(t);
}
}
int taskAmount = 0;
foreach (var v in seedsToPlant)
{
object[] obj = new object[2];
obj[0] = v;
// ExecutionCore.TaskList.taskList.Add(new Task(new Action<object>(waterSingleCrop), obj));
ExecutionCore.CustomTask task = new ExecutionCore.CustomTask(plantSingleSeedPacket, obj, new ExecutionCore.TaskMetaData("Plant "+name, new LocationPrerequisite(v.thisLocation), null, null));
if (task.taskMetaData.cost == Int32.MaxValue)
{
StarAI.PathFindingCore.Utilities.clearExceptionListWithNames(true);
Utilities.tileExceptionList.Clear();
continue;
}
ExecutionCore.TaskList.taskList.Add(task);
taskAmount++;
obj[1] = task.taskMetaData.pathsToTake[0];
task.objectParameterDataArray = obj;
// waterSingleCrop(v);
StarAI.PathFindingCore.Utilities.clearExceptionListWithName("Child");
Utilities.tileExceptionList.Clear();
}
seedsToPlant.Clear();
}
public static void plantSingleSeedPacket(object obj)
{
object[] objArray = (object[])obj;
TileNode v = (TileNode)objArray[0];
//List<TileNode> correctPath = Utilities.pathStuff(v);//(List<TileNode>)objArray[1];
List<TileNode> correctPath = (List<TileNode>)objArray[1];
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
//StardustCore.Utilities.masterAdditionList.Add(new StardustCore.DataNodes.PlacementNode(goodTile, Game1.currentLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize));
goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
PathFindingLogic.calculateMovement(correctPath);
if (v.tileLocation.X < Game1.player.getTileX())
{
Game1.player.faceDirection(3);
}
else if (v.tileLocation.X > Game1.player.getTileX())
{
Game1.player.faceDirection(1);
}
else if (v.tileLocation.Y < Game1.player.getTileY())
{
Game1.player.faceDirection(0);
}
else if (v.tileLocation.Y > Game1.player.getTileY())
{
Game1.player.faceDirection(2);
}
foreach (var item in Game1.player.items)
{
if (item == null) continue;
if (item.getCategoryName()=="Seed")
{
Game1.player.CurrentToolIndex = Game1.player.getIndexOfInventoryItem(item);
}
}
bool move = false;
while ((v.thisLocation.terrainFeatures[v.tileLocation] as StardewValley.TerrainFeatures.HoeDirt).crop==null)
{
if (WindowsInput.InputSimulator.IsKeyDown(WindowsInput.VirtualKeyCode.VK_X) == false) WindowsInput.InputSimulator.SimulateKeyDown(WindowsInput.VirtualKeyCode.VK_X);
Vector2 center = new Vector2();
if (Game1.player.facingDirection == 2)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X + 1, (int)v.tileLocation.Y);
//continue;
}
if (Game1.player.facingDirection == 1)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X - 1, (int)v.tileLocation.Y);
// continue;
}
if (Game1.player.facingDirection == 0)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y + 1);
//continue;
}
if (Game1.player.facingDirection == 3)
{
center = StarAI.PathFindingCore.Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y - 1);
// continue;
}
//Game1.player.position = center;
Crop c= parseCropFromSeedIndex(Game1.player.ActiveObject.parentSheetIndex);
(v.thisLocation.terrainFeatures[v.tileLocation] as StardewValley.TerrainFeatures.HoeDirt).crop = c;
if (Game1.player.ActiveObject.stack > 1)
{
Game1.player.reduceActiveItemByOne();
// Game1.player.ActiveObject.stack--;
}
else
{
Game1.player.items.Remove(Game1.player.ActiveObject);
Game1.player.ActiveObject = null;
}
//Game1.setMousePosition((int)v.tileLocation.X*Game1.tileSize/2,(int)v.tileLocation.Y*Game1.tileSize/2);
ModCore.CoreMonitor.Log("DOESNT Plant Seeds LIKE YOU THINK IT SHOULD");
ModCore.CoreMonitor.Log("player pos: " + Game1.player.position.ToString(), LogLevel.Warn);
ModCore.CoreMonitor.Log("TilePos: " + v.position.ToString(), LogLevel.Error);
}
StarAI.PathFindingCore.Utilities.cleanExceptionList(v);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
// StardustCore.Utilities.masterRemovalList.Add(v);
//v.performRemoveAction(v.tileLocation, v.thisLocation);
v.thisLocation.objects.Remove(v.tileLocation);
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(goodTile);
//StardustCore.Utilities.masterRemovalList.Add(v);
goodTile.performRemoveAction(goodTile.tileLocation, goodTile.thisLocation);
//goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.VK_X);
}
}
}

View File

@ -0,0 +1,214 @@
using Microsoft.Xna.Framework;
using StarAI.ExecutionCore.TaskPrerequisites;
using StarAI.PathFindingCore;
using StardewValley;
using StardewValley.Menus;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.TaskCore.CropLogic
{
class ShippingLogic
{
public static void goToShippingBinSetUp()
{
List<TileNode> shippingTiles = new List<TileNode>();
if (Game1.player.currentLocation.name == "Farm")
{
//CHEATING AND STUPID WAY BUT WILL PATH TO SHIPPING BIN.
for (int i = 0; i <= 1; i++)
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
t.fakePlacementAction(Game1.currentLocation, 71+i, 14);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "ShippingBin"));
shippingTiles.Add(t);
}
}
int ok = 0;
object[] objList = new object[3];
List<TileNode> tempList = new List<TileNode>();
foreach (var v in shippingTiles)
{
tempList.Add(v);
}
objList[0] = tempList;
// ExecutionCore.TaskList.taskList.Add(new Task(new Action<object>(waterSingleCrop), obj));
StardewValley.Tools.WateringCan w = new StardewValley.Tools.WateringCan();
//ModCore.CoreMonitor.Log("Processing water tiles:" + shippingTiles.Count.ToString() + " / " + twingCount.ToString());
ok++;
int numberOfUses = 1;
ExecutionCore.CustomTask task = new ExecutionCore.CustomTask(goToShippingBin, objList, new ExecutionCore.TaskMetaData("GoToShippingBin", null, null,null,null,null));
task.objectParameterDataArray = objList;
if (task.taskMetaData.cost == Int32.MaxValue)
{
Utilities.clearExceptionListWithNames(true);
return;
}
objList[1] = task.taskMetaData.pathsToTake[0];
objList[2] = task.taskMetaData.pathsToTake[0].ElementAt(0);
ExecutionCore.TaskList.taskList.Add(task);
Utilities.clearExceptionListWithName("Child");
Utilities.tileExceptionList.Clear();
}
public static void goToShippingBin(TileNode v, List<TileNode> path)
{
object[] obj = new object[2];
obj[0] = v;
obj[1] = path;
goToShippingBin(obj);
}
public static void goToShippingBin(object obj)
{
object[] objArray = (object[])obj;
TileNode v = (TileNode)objArray[2];
List<TileNode> correctPath = (List<TileNode>)objArray[1];
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
PathFindingLogic.calculateMovement(correctPath);
Vector2 tileLocation = v.tileLocation;
//ModCore.CoreMonitor.Log(tileLocation.ToString());
//if(v.thisLocation.isTerrainFeatureAt)
//DO SOME LOGIC HERE IF I WANT TO SHIP???
Utilities.cleanExceptionList(v);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(goodTile);
goodTile.performRemoveAction(goodTile.tileLocation, goodTile.thisLocation);
}
}
public static void goToShippingBinShipItem(Item I)
{
List<TileNode> shippingTiles = new List<TileNode>();
ModCore.CoreMonitor.Log(I.Name);
if (I==null) ModCore.CoreMonitor.Log("DIE");
if (Game1.player.currentLocation.name == "Farm")
{
//CHEATING AND STUPID WAY BUT WILL PATH TO SHIPPING BIN.
for (int i = 0; i <= 1; i++)
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
t.fakePlacementAction(Game1.currentLocation, 71 + i, 14);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "ShippingBin"));
shippingTiles.Add(t);
}
}
int ok = 0;
object[] objList = new object[4];
List<TileNode> tempList = new List<TileNode>();
foreach (var v in shippingTiles)
{
tempList.Add(v);
}
objList[0] = tempList;
objList[3] = I;
// ExecutionCore.TaskList.taskList.Add(new Task(new Action<object>(waterSingleCrop), obj));
//ModCore.CoreMonitor.Log("Processing water tiles:" + shippingTiles.Count.ToString() + " / " + twingCount.ToString());
ok++;
int numberOfUses = 1;
ExecutionCore.CustomTask task = new ExecutionCore.CustomTask(goToShippingBinShipItem, objList, new ExecutionCore.TaskMetaData("GoToShippingBin",new LocationPrerequisite(Game1.getLocationFromName("Farm")), null, null, null, null,new ItemPrerequisite(I,I.Stack)));
task.objectParameterDataArray = objList;
if (task.taskMetaData.cost == Int32.MaxValue)
{
Utilities.clearExceptionListWithNames(true);
return;
}
objList[1] = task.taskMetaData.pathsToTake[0];
objList[2] = task.taskMetaData.pathsToTake[0].ElementAt(0);
ExecutionCore.TaskList.taskList.Add(task);
Utilities.clearExceptionListWithName("Child");
Utilities.tileExceptionList.Clear();
}
public static void goToShippingBinShipItem(TileNode v, List<TileNode> path)
{
object[] obj = new object[2];
obj[0] = v;
obj[1] = path;
goToShippingBinShipItem(obj);
}
public static void goToShippingBinShipItem(object obj)
{
object[] objArray = (object[])obj;
Item I= (Item)objArray[3];
TileNode v = (TileNode)objArray[2];
List<TileNode> correctPath = (List<TileNode>)objArray[1];
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
PathFindingLogic.calculateMovement(correctPath);
Vector2 tileLocation = v.tileLocation;
//ModCore.CoreMonitor.Log(tileLocation.ToString());
//if(v.thisLocation.isTerrainFeatureAt)
//DO SOME LOGIC HERE IF I WANT TO SHIP???
int amount = I.Stack;
Item ok= StardustCore.Utilities.getItemFromInventory(I.Name);
Item cool = new StardewValley.Object(I.parentSheetIndex, amount);
//Game1.player.removeItemsFromInventory(StardewValley.Game1.player.getIndexOfInventoryItem(ok), 1);
Game1.shippingBin.Add((StardewValley.Object)cool);
int value= ok.Stack - amount;
ModCore.CoreMonitor.Log("AMOUNT:" + amount);
if (value <= 0) {
Game1.player.items.Remove(ok);
ok = null;
}
else ok.Stack = value;
//Game1.shipObject((StardewValley.Object)I);
ModCore.throwUpShippingMenu = true;
Utilities.cleanExceptionList(v);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(goodTile);
goodTile.performRemoveAction(goodTile.tileLocation, goodTile.thisLocation);
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,398 @@
using Microsoft.Xna.Framework;
using StardewValley;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WindowsInput;
using StarAI.PathFindingCore;
using StarAI.ExecutionCore;
namespace StarAI.TaskCore.MapTransitionLogic
{
class TransitionLogic
{
/// <summary>
/// Will transition to the next map by using warp goals if the map is adjacent to the one I am at and I can path to it.
/// </summary>
/// <param name="location"></param>
/// <param name="targetName"></param>
public static void transitionToAdjacentMap(GameLocation location,string targetName)
{
List<TileNode> warpGoals = new List<TileNode>();
foreach(var v in location.warps)
{
if (v.TargetName == targetName)
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
t.fakePlacementAction(Game1.currentLocation, v.X, v.Y);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "WarpGoal"));
warpGoals.Add(t);
}
}
int ok = 0;
object[] objList = new object[4];
List<TileNode> tempList = new List<TileNode>();
foreach (var v in warpGoals)
{
tempList.Add(v);
}
objList[0] = tempList;
ok++;
int numberOfUses = 1;
ExecutionCore.CustomTask task = new ExecutionCore.CustomTask(goToAdjacentWarpGoal, objList, new ExecutionCore.TaskMetaData("GoTo adj map", null, null, null, null, null));
task.objectParameterDataArray = objList;
if (task.taskMetaData.cost == Int32.MaxValue)
{
Utilities.clearExceptionListWithNames(true);
return;
}
objList[1] = task.taskMetaData.pathsToTake[0];
objList[2] = task.taskMetaData.pathsToTake[0].ElementAt(0);
objList[3] = targetName;
ExecutionCore.TaskList.taskList.Add(task);
Utilities.clearExceptionListWithName("Child");
Utilities.tileExceptionList.Clear();
warpGoals.Clear();
}
public static CustomTask transitionToAdjacentMapReturnTask(GameLocation location, string targetName)
{
List<TileNode> warpGoals = new List<TileNode>();
foreach (var v in location.warps)
{
if (v.TargetName == targetName)
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
t.fakePlacementAction(Game1.currentLocation, v.X, v.Y);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "WarpGoal"));
warpGoals.Add(t);
}
}
int ok = 0;
object[] objList = new object[4];
List<TileNode> tempList = new List<TileNode>();
foreach (var v in warpGoals)
{
tempList.Add(v);
}
objList[0] = tempList;
ok++;
int numberOfUses = 1;
ExecutionCore.CustomTask task = new ExecutionCore.CustomTask(goToAdjacentWarpGoal, objList, new ExecutionCore.TaskMetaData("GoTo adj map", null, null, null, null, null));
task.objectParameterDataArray = objList;
if (task.taskMetaData.cost == Int32.MaxValue)
{
Utilities.clearExceptionListWithNames(true);
return null;
}
objList[1] = task.taskMetaData.pathsToTake[0];
objList[2] = task.taskMetaData.pathsToTake[0].ElementAt(0);
objList[3] = targetName;
Utilities.clearExceptionListWithName("Child");
Utilities.tileExceptionList.Clear();
warpGoals.Clear();
return task;
}
public static List<TileNode> transitionToAdjacentMapReturn(GameLocation location, string targetName)
{
List<TileNode> warpGoals = new List<TileNode>();
foreach (var v in location.warps)
{
if (v.TargetName == targetName)
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
t.fakePlacementAction(Game1.currentLocation, v.X, v.Y);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "WarpGoal"));
warpGoals.Add(t);
}
}
int ok = 0;
object[] objList = new object[4];
List<TileNode> tempList = new List<TileNode>();
foreach (var v in warpGoals)
{
tempList.Add(v);
}
return tempList;
objList[0] = tempList;
ok++;
int numberOfUses = 1;
ExecutionCore.CustomTask task = new ExecutionCore.CustomTask(goToAdjacentWarpGoal, objList, new ExecutionCore.TaskMetaData("Path to adj map", null, null, null, null, null));
task.objectParameterDataArray = objList;
if (task.taskMetaData.cost == Int32.MaxValue)
{
Utilities.clearExceptionListWithNames(true);
return null;
}
objList[1] = task.taskMetaData.pathsToTake[0];
objList[2] = task.taskMetaData.pathsToTake[0].ElementAt(0);
objList[3] = targetName;
ExecutionCore.TaskList.taskList.Add(task);
Utilities.clearExceptionListWithName("Child");
Utilities.tileExceptionList.Clear();
warpGoals.Clear();
}
public static void goToAdjacentWarpGoal(TileNode v, List<TileNode> path)
{
object[] obj = new object[2];
obj[0] = v;
obj[1] = path;
goToAdjacentWarpGoal(obj);
}
public static void goToAdjacentWarpGoal(object obj)
{
object[] objArray = (object[])obj;
TileNode v = (TileNode)objArray[2];
string locationName = (string)objArray[3];
List<TileNode> correctPath = (List<TileNode>)objArray[1];
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
PathFindingLogic.calculateMovement(correctPath);
Vector2 tileLocation = v.tileLocation;
for(int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
foreach (var warp in v.thisLocation.warps)
{
if (warp.X == Game1.player.getTileX()+i && warp.Y == Game1.player.getTileY()+j)
{
Game1.warpFarmer(warp.TargetName, warp.TargetX, warp.TargetY, false);
}
}
}
}
/*
if (Game1.player.facingDirection == 2)
{
if (InputSimulator.IsKeyDown(VirtualKeyCode.VK_S) == false) InputSimulator.SimulateKeyDown(VirtualKeyCode.VK_S);
}
if (Game1.player.facingDirection == 1)
{
if (InputSimulator.IsKeyDown(VirtualKeyCode.VK_D) == false) InputSimulator.SimulateKeyDown(VirtualKeyCode.VK_D);
}
if (Game1.player.facingDirection == 0)
{
if (InputSimulator.IsKeyDown(VirtualKeyCode.VK_W) == false) InputSimulator.SimulateKeyDown(VirtualKeyCode.VK_W);
}
if (Game1.player.facingDirection == 3)
{
if (InputSimulator.IsKeyDown(VirtualKeyCode.VK_A) == false) InputSimulator.SimulateKeyDown(VirtualKeyCode.VK_A);
}
InputSimulator.SimulateKeyUp(VirtualKeyCode.VK_W);
InputSimulator.SimulateKeyUp(VirtualKeyCode.VK_A);
InputSimulator.SimulateKeyUp(VirtualKeyCode.VK_S);
InputSimulator.SimulateKeyUp(VirtualKeyCode.VK_D);
*/
//ModCore.CoreMonitor.Log(tileLocation.ToString());
//if(v.thisLocation.isTerrainFeatureAt)
Utilities.cleanExceptionList(v);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(goodTile);
goodTile.performRemoveAction(goodTile.tileLocation, goodTile.thisLocation);
}
}
public static void transitionToAdjacentMap(GameLocation location, string targetName,int tileX, int tileY)
{
List<TileNode> warpGoals = new List<TileNode>();
foreach (var v in location.warps)
{
if (v.TargetName == targetName)
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
t.fakePlacementAction(Game1.currentLocation, v.X, v.Y);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "WarpGoal"));
warpGoals.Add(t);
}
}
int ok = 0;
object[] objList = new object[10];
List<TileNode> tempList = new List<TileNode>();
foreach (var v in warpGoals)
{
tempList.Add(v);
}
objList[0] = tempList;
ok++;
int numberOfUses = 1;
ExecutionCore.CustomTask task = new ExecutionCore.CustomTask(goToAdjacentWarpGoalTile, objList, new ExecutionCore.TaskMetaData("GoTo adj map tile", null, null, null, null, null));
if (task.taskMetaData.cost == Int32.MaxValue)
{
Utilities.clearExceptionListWithNames(true);
return;
}
objList[1] = task.taskMetaData.pathsToTake[0];
objList[2] = task.taskMetaData.pathsToTake[0].ElementAt(0);
objList[3] = targetName;
objList[4] = new Vector2(tileX, tileY);
task.objectParameterDataArray = objList;
ExecutionCore.TaskList.taskList.Add(task);
Utilities.clearExceptionListWithName("Child");
Utilities.tileExceptionList.Clear();
warpGoals.Clear();
}
public static CustomTask transitionToAdjacentMapReturnTask(GameLocation location, string targetName, int tileX, int tileY)
{
List<TileNode> warpGoals = new List<TileNode>();
foreach (var v in location.warps)
{
if (v.TargetName == targetName)
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
t.fakePlacementAction(Game1.currentLocation, v.X, v.Y);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "WarpGoal"));
warpGoals.Add(t);
}
}
int ok = 0;
object[] objList = new object[10];
List<TileNode> tempList = new List<TileNode>();
foreach (var v in warpGoals)
{
tempList.Add(v);
}
objList[0] = tempList;
ok++;
int numberOfUses = 1;
ExecutionCore.CustomTask task = new ExecutionCore.CustomTask(goToAdjacentWarpGoalTile, objList, new ExecutionCore.TaskMetaData("GoTo adj map tile", null, null, null, null, null));
if (task.taskMetaData.cost == Int32.MaxValue)
{
Utilities.clearExceptionListWithNames(true);
return null;
}
objList[1] = task.taskMetaData.pathsToTake[0];
objList[2] = task.taskMetaData.pathsToTake[0].ElementAt(0);
objList[3] = targetName;
objList[4] = new Vector2(tileX, tileY);
task.objectParameterDataArray = objList;
//ExecutionCore.TaskList.taskList.Add(task);
Utilities.clearExceptionListWithName("Child");
Utilities.tileExceptionList.Clear();
warpGoals.Clear();
return task;
}
public static void goToAdjacentWarpGoalTile(TileNode v, List<TileNode> path,string mapName ,Vector2 position)
{
object[] obj = new object[2];
obj[0] = v;
obj[1] = path;
obj[3] = mapName;
obj[4] = position;
goToAdjacentWarpGoalTile(obj);
}
public static void goToAdjacentWarpGoalTile(object obj)
{
object[] objArray = (object[])obj;
List<TileNode> tileList = (List<TileNode>)objArray[0];
string locationName = (string)objArray[3];
Vector2 position = (Vector2)objArray[4];
List<TileNode> correctPath = (List<TileNode>)objArray[1];
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
PathFindingLogic.calculateMovement(correctPath);
Warp lastWarp = new Warp(-1, -1, "Claire", -1, -1, false);
foreach (var v in tileList)
{
Vector2 tileLocation = v.tileLocation;
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
foreach (var warp in v.thisLocation.warps)
{
if (warp.X == Game1.player.getTileX() + i && warp.Y == Game1.player.getTileY() + j)
{
Game1.warpFarmer(warp.TargetName, warp.TargetX, warp.TargetY, false);
lastWarp = warp;
}
}
}
}
Utilities.cleanExceptionList(v);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(goodTile);
goodTile.performRemoveAction(goodTile.tileLocation, goodTile.thisLocation);
}
}
ModCore.CoreMonitor.Log("Going here I guess???" + locationName + " : " + position);
ModCore.CoreMonitor.Log("From Here???" + Game1.getLocationFromName(lastWarp.TargetName) + " " + lastWarp.TargetX + " " + lastWarp.TargetY);
TileNode s = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
s.fakePlacementAction(Game1.getLocationFromName(lastWarp.TargetName), lastWarp.TargetX, lastWarp.TargetY);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(s, "WarpGoal"));
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
t.fakePlacementAction(Game1.getLocationFromName(locationName), (int)position.X, (int)position.Y);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "WarpGoal"));
PathFindingLogic.calculateMovement(Utilities.getIdealPath(t, s));
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,128 @@
using Microsoft.Xna.Framework;
using StarAI.ExecutionCore;
using StarAI.PathFindingCore;
using StardewValley;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.TaskCore.MapTransitionLogic
{
public class WayPoints
{
public static Dictionary<string, KeyValuePair<string, Vector2>> wayPoints = new Dictionary<string, KeyValuePair<string, Vector2>>();
//Positions listed here will always put the player exactly 1 tile away from what is listed here.
public static void initializeWaypoints()
{
wayPoints.Add("seeds", new KeyValuePair<string, Vector2>("SeedShop", new Vector2(5, 18))); //This waypoint will position the player at the General store 1 tile below the counter.
wayPoints.Add("bed", new KeyValuePair<string, Vector2>("FarmHouse", new Vector2(-1, -1))); //to be initialized after load.
wayPoints.Add("porch", new KeyValuePair<string, Vector2>("Farm", new Vector2(64, 15))); //to be initialized after load.
ModCore.CoreMonitor.Log("Star AI WayPoints: Done initializing: " + wayPoints.Count + " waypoints.");
}
public static void pathToWayPoint(string wayPointName)
{
KeyValuePair<string, Vector2> outValue;
bool isAvailable = wayPoints.TryGetValue(wayPointName, out outValue);
if (isAvailable == true)
{
MapTransitionLogic.WarpGoal.pathToWorldTile(Game1.player.currentLocation, outValue.Key, (int)outValue.Value.X, (int)outValue.Value.Y);
}
}
public static CustomTask pathToWayPointReturnTask(string wayPointName)
{
KeyValuePair<string, Vector2> outValue;
bool isAvailable = wayPoints.TryGetValue(wayPointName, out outValue);
if (isAvailable == true)
{
return MapTransitionLogic.WarpGoal.pathToWorldTileReturnTask(Game1.player.currentLocation, outValue.Key, (int)outValue.Value.X, (int)outValue.Value.Y);
}
return null;
}
public static void printWayPoints()
{
foreach(var v in wayPoints)
{
ModCore.CoreMonitor.Log("Waypoint Name:" + v.Key);
ModCore.CoreMonitor.Log("Waypoint Position:" + v.Value.Key+" "+v.Value.Value);
}
}
/// <summary>
/// To be called after load and after save.
/// </summary>
public static void setUpBedWaypoint()
{
Vector2 vec = Game1.player.mostRecentBed / Game1.tileSize;
int x = (int)Math.Floor(vec.X);
x += 2;
int y = (int)Math.Floor(vec.Y);
vec = new Vector2(x, y);
wayPoints["bed"] = new KeyValuePair<string, Vector2>("FarmHouse",vec);
}
public static void verifyWayPoints()
{
List<string> removalList = new List<string>();
int i = 0;
foreach(var waypoint in wayPoints)
{
i++;
ModCore.CoreMonitor.Log("Validating waypoints " + i + " / " + wayPoints.Count);
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
t.fakePlacementAction(Game1.getLocationFromName(waypoint.Value.Key),(int)waypoint.Value.Value.X,(int)waypoint.Value.Value.Y);
// bool canWaypointBeHere=TileNode.checkIfICanPlaceHere(t, waypoint.Value.Value * Game1.tileSize, Game1.getLocationFromName(waypoint.Value.Key), true, false);
bool canPathHere = false;
foreach(Warp w in Game1.getLocationFromName(waypoint.Value.Key).warps)
{
TileNode s = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
s.fakePlacementAction(Game1.getLocationFromName(waypoint.Value.Key), w.X, w.Y);
var path=Utilities.getIdealPath(t, s);
//If I can't find the goal at first keep trying.
if (path.Count == 0)
{
continue;
}
else
{ //I found the goal so this is a valid waypoint.
canPathHere = true;
break;
}
}
//Valid waypoint don't remove.
if (canPathHere == true)
{
ModCore.CoreMonitor.Log("Waypoint: " + waypoint.Key + " has been validated as a valid waypoint position at:" + waypoint.Value.Key + " " + waypoint.Value.Value,StardewModdingAPI.LogLevel.Alert);
continue;
}
else
{
//Couldn't path to this location. Guess I'll remove it.
ModCore.CoreMonitor.Log("Removing waypoint: " + waypoint.Key, StardewModdingAPI.LogLevel.Alert);
ModCore.CoreMonitor.Log("Can't find path at the location to: " + waypoint.Value.Key + " " + waypoint.Value.Value, StardewModdingAPI.LogLevel.Alert);
removalList.Add(waypoint.Key);
}
}
foreach(var wayPointName in removalList)
{
wayPoints.Remove(wayPointName);
}
Utilities.tileExceptionList.Clear();
}
}
}

View File

@ -0,0 +1,263 @@
using Microsoft.Xna.Framework;
using StarAI.ExecutionCore;
using StarAI.ExecutionCore.TaskPrerequisites;
using StardewModdingAPI;
using StardewValley;
using StardewValley.Tools;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using xTile.Layers;
namespace StarAI.PathFindingCore.WaterLogic
{
public class WaterLogic
{
public static List<TileNode> waterTilesAvailable = new List<TileNode>();
public static void getAllWaterTiles(GameLocation location)
{
object[] arr = new object[1];
arr[0] = location;
getAllWaterTiles(arr);
}
public static void getAllWaterTiles(object obj)
{
int twingCount = 0;
object[] objArr = (object[])obj;
GameLocation location = (GameLocation)objArr[0];
// string targetName = "Weeds";
Layer layer = location.map.GetLayer("Back");
for(int i=0; i <= layer.LayerSize.Width; i++)
{
for (int j = 0; j <= layer.LayerSize.Height; j++)
{
if (location.isOpenWater(i, j))
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
t.fakePlacementAction(location, i,j);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "ChopTree"));
waterTilesAvailable.Add(t);
twingCount++;
}
}
}
int ok = 0;
object[] objList = new object[3];
List<TileNode> tempList = new List<TileNode>();
foreach (var v in waterTilesAvailable)
{
tempList.Add(v);
}
objList[0] = tempList;
// ExecutionCore.TaskList.taskList.Add(new Task(new Action<object>(waterSingleCrop), obj));
StardewValley.Tools.WateringCan w = new StardewValley.Tools.WateringCan();
ModCore.CoreMonitor.Log("Processing water tiles:" + waterTilesAvailable.Count.ToString() + " / " + twingCount.ToString());
ok++;
int numberOfUses = 1;
ExecutionCore.CustomTask task = new ExecutionCore.CustomTask(goToSingleWaterTile, objList, new ExecutionCore.TaskMetaData("GoToWaterTile", new LocationPrerequisite(location), new StaminaPrerequisite(true, 2 * numberOfUses), new ToolPrerequisite(true, w.GetType(), numberOfUses)));
if (task.taskMetaData.cost == Int32.MaxValue)
{
Utilities.clearExceptionListWithNames(true);
return;
}
objList[1] = task.taskMetaData.pathsToTake[0];
objList[2] = task.taskMetaData.pathsToTake[0].ElementAt(0);
task.objectParameterDataArray = objList;
ExecutionCore.TaskList.taskList.Add(task);
Utilities.clearExceptionListWithName("Child");
waterTilesAvailable.Clear();
Utilities.tileExceptionList.Clear();
}
public static CustomTask getAllWaterTilesTask(GameLocation location)
{
object[] arr = new object[1];
arr[0] = location;
return getAllWaterTilesTask(arr);
}
public static CustomTask getAllWaterTilesTask(object obj)
{
int twingCount = 0;
object[] objArr = (object[])obj;
GameLocation location = (GameLocation)objArr[0];
// string targetName = "Weeds";
Layer layer = location.map.GetLayer("Back");
for (int i = 0; i <= layer.LayerSize.Width; i++)
{
for (int j = 0; j <= layer.LayerSize.Height; j++)
{
if (location.isOpenWater(i, j))
{
TileNode t = new TileNode(1, Vector2.Zero, Path.Combine("Tiles", "GenericUncoloredTile.xnb"), Path.Combine("Tiles", "TileData.xnb"), StardustCore.IlluminateFramework.Colors.invertColor(StardustCore.IlluminateFramework.ColorsList.Brown));
t.fakePlacementAction(location, i, j);
Utilities.tileExceptionList.Add(new TileExceptionMetaData(t, "WaterTile"));
waterTilesAvailable.Add(t);
twingCount++;
}
}
}
int ok = 0;
object[] objList = new object[3];
List<TileNode> tempList = new List<TileNode>();
foreach (var v in waterTilesAvailable)
{
tempList.Add(v);
}
objList[0] = tempList;
// ExecutionCore.TaskList.taskList.Add(new Task(new Action<object>(waterSingleCrop), obj));
StardewValley.Tools.WateringCan w = new StardewValley.Tools.WateringCan();
ModCore.CoreMonitor.Log("Processing water tiles:" + waterTilesAvailable.Count.ToString() + " / " + twingCount.ToString());
ok++;
int numberOfUses = 1;
ExecutionCore.CustomTask task = new ExecutionCore.CustomTask(goToSingleWaterTile, objList, new ExecutionCore.TaskMetaData("GoToWaterTile", new LocationPrerequisite(location), new StaminaPrerequisite(true, 2 * numberOfUses), new ToolPrerequisite(true, w.GetType(), numberOfUses)));
if (task.taskMetaData.cost == Int32.MaxValue)
{
Utilities.clearExceptionListWithNames(true);
return null;
}
objList[1] = task.taskMetaData.pathsToTake[0];
objList[2] = task.taskMetaData.pathsToTake[0].ElementAt(0);
task.objectParameterDataArray = objList;
// ExecutionCore.TaskList.taskList.Add(task);
Utilities.clearExceptionListWithName("Child");
waterTilesAvailable.Clear();
Utilities.tileExceptionList.Clear();
return task;
}
public static void goToSingleWaterTile(TileNode v, List<TileNode> path)
{
object[] obj = new object[2];
obj[0] = v;
obj[1] = path;
goToSingleWaterTile(obj);
}
public static void goToSingleWaterTile(object obj)
{
object[] objArray = (object[])obj;
TileNode v = (TileNode)objArray[2];
List<TileNode> correctPath = (List<TileNode>)objArray[1];
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Add(goodTile);
goodTile.placementAction(goodTile.thisLocation, (int)goodTile.tileLocation.X * Game1.tileSize, (int)goodTile.tileLocation.Y * Game1.tileSize);
}
PathFindingLogic.calculateMovement(correctPath);
Vector2 tileLocation = v.tileLocation;
ModCore.CoreMonitor.Log(tileLocation.ToString());
//if(v.thisLocation.isTerrainFeatureAt)
if (v.thisLocation.isOpenWater((int)v.tileLocation.X-1,(int)v.tileLocation.Y)) //v.thisLocation.terrainFeatures[new Vector2(tileLocation.X - 1, tileLocation.Y)] is StardewValley.TerrainFeatures.Tree)
{
ModCore.CoreMonitor.Log("1Good");
Game1.player.faceDirection(3);
}
if (v.thisLocation.isOpenWater((int)v.tileLocation.X + 1, (int)v.tileLocation.Y)) //v.thisLocation.terrainFeatures[new Vector2(tileLocation.X - 1, tileLocation.Y)] is StardewValley.TerrainFeatures.Tree)
{
ModCore.CoreMonitor.Log("2Good");
Game1.player.faceDirection(1);
}
if (v.thisLocation.isOpenWater((int)v.tileLocation.X, (int)v.tileLocation.Y-1)) //v.thisLocation.terrainFeatures[new Vector2(tileLocation.X - 1, tileLocation.Y)] is StardewValley.TerrainFeatures.Tree)
{
ModCore.CoreMonitor.Log("3Good");
Game1.player.faceDirection(0);
}
if (v.thisLocation.isOpenWater((int)v.tileLocation.X, (int)v.tileLocation.Y+1)) //v.thisLocation.terrainFeatures[new Vector2(tileLocation.X - 1, tileLocation.Y)] is StardewValley.TerrainFeatures.Tree)
{
ModCore.CoreMonitor.Log("4Good");
Game1.player.faceDirection(2);
}
StardewValley.Tools.WateringCan w = new StardewValley.Tools.WateringCan();
foreach (var item in Game1.player.items)
{
if (item is StardewValley.Tools.WateringCan)
{
Game1.player.CurrentToolIndex = Game1.player.getIndexOfInventoryItem(item);
w = (WateringCan)item;
}
}
while (w.WaterLeft!=w.waterCanMax)
{
// if (!v.thisLocation.isTerrainFeatureAt((int)v.tileLocation.X, (int)v.tileLocation.Y)) break;
if (WindowsInput.InputSimulator.IsKeyDown(WindowsInput.VirtualKeyCode.VK_C) == false) WindowsInput.InputSimulator.SimulateKeyDown(WindowsInput.VirtualKeyCode.VK_C);
Vector2 center = new Vector2();
if (Game1.player.facingDirection == 2)
{
center = Utilities.parseCenterFromTile((int)v.tileLocation.X + 1, (int)v.tileLocation.Y);
continue;
}
if (Game1.player.facingDirection == 1)
{
center = Utilities.parseCenterFromTile((int)v.tileLocation.X - 1, (int)v.tileLocation.Y);
continue;
}
if (Game1.player.facingDirection == 0)
{
center = Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y + 1);
continue;
}
if (Game1.player.facingDirection == 3)
{
center = Utilities.parseCenterFromTile((int)v.tileLocation.X, (int)v.tileLocation.Y - 1);
continue;
}
Game1.player.position = center;
//Game1.setMousePosition((int)v.tileLocation.X*Game1.tileSize/2,(int)v.tileLocation.Y*Game1.tileSize/2);
ModCore.CoreMonitor.Log("DOESNT Axe LIKE YOU THINK IT SHOULD");
ModCore.CoreMonitor.Log("player pos: " + Game1.player.position.ToString(), LogLevel.Warn);
ModCore.CoreMonitor.Log("TilePos: " + v.position.ToString(), LogLevel.Error);
}
Utilities.cleanExceptionList(v);
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(v);
foreach (var goodTile in correctPath)
{
StardustCore.ModCore.SerializationManager.trackedObjectList.Remove(goodTile);
goodTile.performRemoveAction(goodTile.tileLocation, goodTile.thisLocation);
}
WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.VK_C);
}
}
}

View File

@ -0,0 +1,243 @@
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StarAI.UtilityCore
{
class SeedCropUtility
{
public static Dictionary<int, float> CropSeedUtilityDictionary = new Dictionary<int, float>();
public static Dictionary<int, float> UserCropSeedUtilityDictionary = new Dictionary<int, float>();
public static Dictionary<int, float> ScaleUtilityDictionary = new Dictionary<int, float>();
public static void setUpUserCropUtilityDictionary()
{
UserCropSeedUtilityDictionary.Clear();
Dictionary<KeyValuePair<int, Crop>, float> tempDictionary = new Dictionary<KeyValuePair<int, Crop>, float>();
foreach (var item in Game1.objectInformation)
{
StardewValley.Object test = new StardewValley.Object(item.Key, 1);
if (test.getCategoryName() == "Seed")
{
KeyValuePair<int, Crop> pair = StarAI.TaskCore.CropLogic.SeedLogic.getSeedCropPair(test.parentSheetIndex);
if (pair.Value == null) continue;
//if (utilityValue <= 0) continue;
UserCropSeedUtilityDictionary.Add(test.parentSheetIndex, 0); //CHANGE THIS TO BE BASED ON THE MENU UTILITY
//numberOfInitializedUtilitySeedValues++;
ModCore.CoreMonitor.Log("Star AI: Utility Core: Calculating " + test.name + " for user utility picking with a value of: 0");
}
}
ModCore.CoreMonitor.Log("UTIL COUNT:" + UserCropSeedUtilityDictionary.Count);
}
public static void setUpCropUtilityDictionaryDaily()
{
CropSeedUtilityDictionary.Clear();
Dictionary<int, float> tempDictionary = new Dictionary<int, float>();
int numberOfInitializedUtilitySeedValues = 0;
float totalValue = 0;
foreach (var item in Game1.objectInformation)
{
StardewValley.Object test = new StardewValley.Object(item.Key, 1);
if (test.getCategoryName() == "Seed")
{
KeyValuePair<int, Crop> pair = StarAI.TaskCore.CropLogic.SeedLogic.getSeedCropPair(test.parentSheetIndex);
if (pair.Value == null) continue;
float utilityValue = averageGoldPerDay(pair.Value, test);
if (!pair.Value.seasonsToGrowIn.Contains(Game1.currentSeason)) utilityValue = 0;
totalValue += utilityValue;
utilityValue =(float) Math.Round(utilityValue, 2);
//if (utilityValue <= 0) continue;
tempDictionary.Add(test.parentSheetIndex, utilityValue); //CHANGE THIS TO BE BASED ON THE MENU UTILITY
numberOfInitializedUtilitySeedValues++;
//ModCore.CoreMonitor.Log("Star AI: Utility Core: Calculating " + test.name + " for utility picking with a value of: "+utilityValue.ToString());
}
}
foreach (var c in tempDictionary)
{
KeyValuePair<int, float> hello = c;
float afterValue = hello.Value / totalValue;
CropSeedUtilityDictionary.Add(hello.Key, afterValue);
StardewValley.Object test = new StardewValley.Object(c.Key, 1);
ModCore.CoreMonitor.Log("Star AI: Utility Core: Calculating " + test.name + " for utility picking value of (" + hello.Value + " : " + (afterValue * 100).ToString() + "%)");
}
ModCore.CoreMonitor.Log("Star AI: Utility Core: Calculating " + numberOfInitializedUtilitySeedValues + " seeds for utility picking.");
if (numberOfInitializedUtilitySeedValues == 0)
{
ModCore.CoreMonitor.Log("No seed values initialized. There must be no possible seeds I can grow for the rest of this season.", StardewModdingAPI.LogLevel.Alert);
}
recalculateAllUtilityValues();
}
public static void recalculateAllUtilityValues()
{
ScaleUtilityDictionary.Clear();
float totalValue = 0;
foreach(var v in CropSeedUtilityDictionary)
{
totalValue +=Math.Abs(v.Value);
}
foreach (var v in UserCropSeedUtilityDictionary)
{
totalValue +=Math.Abs(v.Value);
}
Dictionary<int, float> ok = new Dictionary<int, float>();
foreach(var v in CropSeedUtilityDictionary)
{
ok.Add(v.Key, v.Value);
}
Dictionary<int, float> ok2 = new Dictionary<int, float>();
foreach (var v in UserCropSeedUtilityDictionary)
{
ok2.Add(v.Key, v.Value);
}
foreach (var v in ok)
{
CropSeedUtilityDictionary[v.Key] = CropSeedUtilityDictionary[v.Key] / totalValue;
}
foreach (var v in ok2)
{
UserCropSeedUtilityDictionary[v.Key] = UserCropSeedUtilityDictionary[v.Key] / totalValue;
}
ModCore.CoreMonitor.Log("TOTAL VALUE:"+totalValue.ToString());
foreach (var v in CropSeedUtilityDictionary)
{
if (StardustCore.StaticExtentions.HasValue(CropSeedUtilityDictionary[v.Key]) == false)
{
CropSeedUtilityDictionary[v.Key] = 0;
}
if (StardustCore.StaticExtentions.HasValue(UserCropSeedUtilityDictionary[v.Key]) == false)
{
UserCropSeedUtilityDictionary[v.Key] = 0;
}
float scale = CropSeedUtilityDictionary[v.Key] + UserCropSeedUtilityDictionary[v.Key];
if (scale <= 0)
{
scale = 0;
}
ScaleUtilityDictionary.Add(v.Key,scale);
StardewValley.Object obj = new StardewValley.Object(v.Key, 1);
ModCore.CoreMonitor.Log("Updated: " + obj.name + " to now have a percent utility contribution of: "+ (CropSeedUtilityDictionary[v.Key] + UserCropSeedUtilityDictionary[v.Key]).ToString());
}
}
public static float getUtilityScaleValue(int seedIndex)
{
return ScaleUtilityDictionary[seedIndex];
}
public static int numberOfDaysToGrow(Crop c)
{
int total = 0;
foreach(var v in c.phaseDays)
{
if (v != -1) total += v;
}
return (total-100000+1);
}
public static void updateUserUtilities(int seedIndex,float amount)
{
ModCore.CoreMonitor.Log("This is the seed index:" + seedIndex);
UserCropSeedUtilityDictionary[seedIndex] += amount;
//if (UserCropSeedUtilityDictionary[seedIndex] <= 0) UserCropSeedUtilityDictionary[seedIndex] = 0;
UserCropSeedUtilityDictionary[seedIndex] = (float) Math.Round(UserCropSeedUtilityDictionary[seedIndex], 2);
StardewValley.Object obj = new StardewValley.Object(seedIndex, 1);
ModCore.CoreMonitor.Log("Updated: " + obj.name + " to now have a user utility value of " + UserCropSeedUtilityDictionary[seedIndex] + " and a total utlity value of: " +(UserCropSeedUtilityDictionary[seedIndex] + CropSeedUtilityDictionary[seedIndex]));
recalculateAllUtilityValues();
}
//AI cares about money, user might care about other things.
//Doesn't recalculate crops that regrow. Favors crops with mutiple yields. Quantity over quality I suppose.
public static float averageGoldPerDay(Crop c,Item seeds)
{
StardewValley.Object crop = new StardewValley.Object(c.indexOfHarvest, 1);
int days = numberOfDaysToGrow(c);
//ModCore.CoreMonitor.Log("DAYS: " + days);
if (days <= 0) return 0;
int maxHarvest = maxHarvestsRemaining(c);
if (maxHarvest == 0) return 0;
if (c.maxHarvest <= 0)
{
return ((Game1.player.farmingLevel * .02f + 1.01f) * (maxHarvest) * crop.price) - seeds.salePrice() / days;
}
else
{
return ((Game1.player.farmingLevel * .02f + 1.01f) * (maxHarvest *c.maxHarvest) * crop.price) - seeds.salePrice() / days;
}
}
public static int maxHarvestsRemaining(Crop c)
{
return (28-Game1.dayOfMonth)/numberOfDaysToGrow(c);
}
public static List<Item> sortSeedListByUtility(List<Item> seedList)
{
List<KeyValuePair<int, float>> sortList = new List<KeyValuePair<int ,float>>();
foreach(var seeds in seedList)
{
var ret = getKeyBySeedIndex(seeds.parentSheetIndex,ScaleUtilityDictionary);
if (ret.Key == -999) continue;
sortList.Add(ret);
}
//Sort the list by utility of the seeds.
sortList.Sort(delegate (KeyValuePair < int,float> t1, KeyValuePair<int, float> t2)
{
return t1.Value.CompareTo(t2.Value);
});
sortList.Reverse(); //I want max to be first instead of min.
float maxUtility = sortList.ElementAt(0).Value;
List<int> finalList = new List<int>();
foreach(var utilitySeed in sortList)
{
if (utilitySeed.Value >= maxUtility) finalList.Add(utilitySeed.Key);
}
List<Item> finalShopStock = new List<Item>();
foreach(var seedIndex in finalList)
{
foreach(var seeds in seedList)
{
if (seedIndex == seeds.parentSheetIndex) finalShopStock.Add(seeds);
}
}
return finalShopStock;
}
public static KeyValuePair<int, float> getKeyBySeedIndex(int seedIndex,Dictionary<int,float> dic)
{
foreach (var key in dic)
{
if (key.Key == seedIndex) return key;
}
return new KeyValuePair<int, float>(-999, -999);
}
}
}