Merge pull request #48 from Pathoschild/minor-cleanup

Minor cleanup
This commit is contained in:
Joshua Navarro 2018-12-31 12:37:34 -08:00 committed by GitHub
commit 08d1e15e45
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
248 changed files with 5576 additions and 16707 deletions

67
.editorconfig Normal file
View File

@ -0,0 +1,67 @@
# topmost editorconfig
root: true
##########
## General formatting
## documentation: https://editorconfig.org
##########
[*]
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
charset = utf-8
[*.{csproj,json,nuspec,targets}]
indent_size = 2
[*.csproj]
insert_final_newline = false
##########
## C# formatting
## documentation: https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference
##########
[*.cs]
#sort 'system' usings first
dotnet_sort_system_directives_first = true
# use 'this.' qualifier
dotnet_style_qualification_for_field = true:error
dotnet_style_qualification_for_property = true:error
dotnet_style_qualification_for_method = true:error
dotnet_style_qualification_for_event = true:error
# use language keywords (like int) instead of type (like Int32)
dotnet_style_predefined_type_for_locals_parameters_members = true:error
dotnet_style_predefined_type_for_member_access = true:error
# don't use 'var' for language keywords
csharp_style_var_for_built_in_types = false:error
# suggest modern C# features where simpler
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_conditional_delegate_call = true:suggestion
csharp_prefer_simple_default_expression = true:suggestion
# prefer method block bodies
csharp_style_expression_bodied_methods = false:suggestion
csharp_style_expression_bodied_constructors = false:suggestion
# prefer property expression bodies
csharp_style_expression_bodied_properties = true:suggestion
csharp_style_expression_bodied_indexers = true:suggestion
csharp_style_expression_bodied_accessors = true:suggestion
# prefer inline out variables
csharp_style_inlined_variable_declaration = true:warning
# avoid superfluous braces
csharp_prefer_braces = false:suggestion

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -11,8 +11,6 @@
<AssemblyName>AdvancedSaveBackup</AssemblyName> <AssemblyName>AdvancedSaveBackup</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -67,6 +65,9 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Pathoschild.Stardew.ModBuildConfig" Version="2.2.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.IO.Compression" /> <Reference Include="System.IO.Compression" />
@ -83,19 +84,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="manifest.json" /> <None Include="manifest.json" />
<None Include="packages.config" />
<None Include="README.md" /> <None Include="README.md" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\analyzers\dotnet\cs\StardewModdingAPI.ModBuildConfig.Analyzer.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\deploy.targets" /> <Import Project="$(SolutionDir)\deploy.targets" />
<Import Project="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\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>
<Error Condition="!Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets'))" />
</Target>
</Project> </Project>

View File

@ -1,4 +1,4 @@
namespace Omegasis.SaveBackup.Framework namespace Omegasis.SaveBackup.Framework
{ {
/// <summary>The mod configuration.</summary> /// <summary>The mod configuration.</summary>
internal class ModConfig internal class ModConfig

View File

@ -1,4 +1,4 @@
using System; using System;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Linq; using System.Linq;

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Pathoschild.Stardew.ModBuildConfig" version="2.2.0" targetFramework="net45" />
</packages>

View File

@ -1,4 +1,4 @@
using System; using System;
using Omegasis.AutoSpeed.Framework; using Omegasis.AutoSpeed.Framework;
using StardewModdingAPI; using StardewModdingAPI;
using StardewModdingAPI.Events; using StardewModdingAPI.Events;

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -11,8 +11,6 @@
<AssemblyName>AutoSpeed</AssemblyName> <AssemblyName>AutoSpeed</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -67,6 +65,9 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Pathoschild.Stardew.ModBuildConfig" Version="2.2.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
@ -81,19 +82,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="manifest.json" /> <None Include="manifest.json" />
<None Include="packages.config" />
<None Include="README.md" /> <None Include="README.md" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\analyzers\dotnet\cs\StardewModdingAPI.ModBuildConfig.Analyzer.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\deploy.targets" /> <Import Project="$(SolutionDir)\deploy.targets" />
<Import Project="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\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>
<Error Condition="!Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets'))" />
</Target>
</Project> </Project>

View File

@ -1,4 +1,4 @@
namespace Omegasis.AutoSpeed.Framework namespace Omegasis.AutoSpeed.Framework
{ {
/// <summary>The mod configuration.</summary> /// <summary>The mod configuration.</summary>
internal class ModConfig internal class ModConfig

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Pathoschild.Stardew.ModBuildConfig" version="2.2.0" targetFramework="net45" />
</packages>

View File

@ -1,4 +1,4 @@
using Omegasis.BillboardAnywhere.Framework; using Omegasis.BillboardAnywhere.Framework;
using StardewModdingAPI; using StardewModdingAPI;
using StardewModdingAPI.Events; using StardewModdingAPI.Events;
using StardewValley; using StardewValley;

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -11,8 +11,6 @@
<AssemblyName>BillboardAnywhere</AssemblyName> <AssemblyName>BillboardAnywhere</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -67,6 +65,9 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Pathoschild.Stardew.ModBuildConfig" Version="2.2.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
@ -83,19 +84,8 @@
<None Include="manifest.json" /> <None Include="manifest.json" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="packages.config" />
<None Include="README.md" /> <None Include="README.md" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\analyzers\dotnet\cs\StardewModdingAPI.ModBuildConfig.Analyzer.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\deploy.targets" /> <Import Project="$(SolutionDir)\deploy.targets" />
<Import Project="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\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>
<Error Condition="!Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets'))" />
</Target>
</Project> </Project>

View File

@ -1,4 +1,4 @@
namespace Omegasis.BillboardAnywhere.Framework namespace Omegasis.BillboardAnywhere.Framework
{ {
/// <summary>The mod configuration.</summary> /// <summary>The mod configuration.</summary>
internal class ModConfig internal class ModConfig

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Pathoschild.Stardew.ModBuildConfig" version="2.2.0" targetFramework="net45" />
</packages>

View File

@ -1,6 +1,5 @@
using System; using System;
using System.IO; using System.IO;
using System.Linq;
using Omegasis.BuildEndurance.Framework; using Omegasis.BuildEndurance.Framework;
using StardewModdingAPI; using StardewModdingAPI;
using StardewModdingAPI.Events; using StardewModdingAPI.Events;
@ -17,9 +16,6 @@ namespace Omegasis.BuildEndurance
/// <summary>The relative path for the current player's data file.</summary> /// <summary>The relative path for the current player's data file.</summary>
private string DataFilePath => Path.Combine("data", $"{Constants.SaveFolderName}.json"); private string DataFilePath => Path.Combine("data", $"{Constants.SaveFolderName}.json");
/// <summary>The absolute path for the current player's legacy data file.</summary>
private string LegacyDataFilePath => Path.Combine(this.Helper.DirectoryPath, "PlayerData", $"BuildEndurance_data_{Game1.player.Name}.txt");
/// <summary>The mod settings.</summary> /// <summary>The mod settings.</summary>
private ModConfig Config; private ModConfig Config;
@ -38,10 +34,10 @@ namespace Omegasis.BuildEndurance
/// <summary>Whether the player was eating last time we checked.</summary> /// <summary>Whether the player was eating last time we checked.</summary>
private bool WasEating; private bool WasEating;
public IModHelper ModHelper; public IModHelper ModHelper;
public IMonitor ModMonitor; public IMonitor ModMonitor;
/********* /*********
** Public methods ** Public methods
*********/ *********/
@ -107,7 +103,7 @@ namespace Omegasis.BuildEndurance
} }
// give XP when player stays up too late or collapses // give XP when player stays up too late or collapses
if (!this.WasCollapsed && shouldFarmerPassout()) if (!this.WasCollapsed && this.shouldFarmerPassout())
{ {
this.PlayerData.CurrentExp += this.Config.ExpForCollapsing; this.PlayerData.CurrentExp += this.Config.ExpForCollapsing;
@ -128,7 +124,6 @@ namespace Omegasis.BuildEndurance
this.WasEating = false; this.WasEating = false;
// load player data // load player data
this.MigrateLegacyData();
this.PlayerData = this.Helper.ReadJsonFile<PlayerData>(this.DataFilePath) ?? new PlayerData(); this.PlayerData = this.Helper.ReadJsonFile<PlayerData>(this.DataFilePath) ?? new PlayerData();
if (this.PlayerData.OriginalMaxStamina == 0) if (this.PlayerData.OriginalMaxStamina == 0)
this.PlayerData.OriginalMaxStamina = Game1.player.MaxStamina; this.PlayerData.OriginalMaxStamina = Game1.player.MaxStamina;
@ -187,44 +182,7 @@ namespace Omegasis.BuildEndurance
this.Helper.WriteJsonFile(this.DataFilePath, this.PlayerData); this.Helper.WriteJsonFile(this.DataFilePath, this.PlayerData);
} }
/// <summary>Migrate the legacy settings for the current player.</summary> /// <summary>Try and emulate the old Game1.shouldFarmerPassout logic.</summary>
private void MigrateLegacyData()
{
// skip if no legacy data or new data already exists
if (!File.Exists(this.LegacyDataFilePath) || File.Exists(this.DataFilePath))
return;
// migrate to new file
try
{
string[] text = File.ReadAllLines(this.LegacyDataFilePath);
this.Helper.WriteJsonFile(this.DataFilePath, new PlayerData
{
CurrentLevel = Convert.ToInt32(text[3]),
CurrentExp = Convert.ToDouble(text[5]),
ExpToNextLevel = Convert.ToDouble(text[7]),
BaseStaminaBonus = Convert.ToInt32(text[9]),
CurrentLevelStaminaBonus = Convert.ToInt32(text[11]),
ClearModEffects = Convert.ToBoolean(text[14]),
OriginalMaxStamina = Convert.ToInt32(text[16]),
NightlyStamina = Convert.ToInt32(text[18])
});
FileInfo file = new FileInfo(this.LegacyDataFilePath);
file.Delete();
if (!file.Directory.EnumerateFiles().Any())
file.Directory.Delete();
}
catch (Exception ex)
{
this.Monitor.Log($"Error migrating data from the legacy 'PlayerData' folder for the current player. Technical details:\n {ex}", LogLevel.Error);
}
}
/// <summary>
/// Try and emulate the old Game1.shouldFarmerPassout logic.
/// </summary>
/// <returns></returns>
public bool shouldFarmerPassout() public bool shouldFarmerPassout()
{ {
if (Game1.player.stamina <= 0 || Game1.player.health <= 0 || Game1.timeOfDay >= 2600) return true; if (Game1.player.stamina <= 0 || Game1.player.health <= 0 || Game1.timeOfDay >= 2600) return true;

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -11,8 +11,6 @@
<AssemblyName>BuildEndurance</AssemblyName> <AssemblyName>BuildEndurance</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -67,6 +65,9 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Pathoschild.Stardew.ModBuildConfig" Version="2.2.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
@ -82,19 +83,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="manifest.json" /> <None Include="manifest.json" />
<None Include="packages.config" />
<None Include="README.md" /> <None Include="README.md" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\analyzers\dotnet\cs\StardewModdingAPI.ModBuildConfig.Analyzer.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\deploy.targets" /> <Import Project="$(SolutionDir)\deploy.targets" />
<Import Project="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\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>
<Error Condition="!Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets'))" />
</Target>
</Project> </Project>

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Pathoschild.Stardew.ModBuildConfig" version="2.2.0" targetFramework="net45" />
</packages>

View File

@ -1,6 +1,5 @@
using System; using System;
using System.IO; using System.IO;
using System.Linq;
using Omegasis.BuildHealth.Framework; using Omegasis.BuildHealth.Framework;
using StardewModdingAPI; using StardewModdingAPI;
using StardewModdingAPI.Events; using StardewModdingAPI.Events;
@ -17,9 +16,6 @@ namespace Omegasis.BuildHealth
/// <summary>The relative path for the current player's data file.</summary> /// <summary>The relative path for the current player's data file.</summary>
private string DataFilePath => Path.Combine("data", $"{Constants.SaveFolderName}.json"); private string DataFilePath => Path.Combine("data", $"{Constants.SaveFolderName}.json");
/// <summary>The absolute path for the current player's legacy data file.</summary>
private string LegacyDataFilePath => Path.Combine(this.Helper.DirectoryPath, "PlayerData", $"BuildHealth_data_{Game1.player.Name}.txt");
/// <summary>The mod settings and player data.</summary> /// <summary>The mod settings and player data.</summary>
private ModConfig Config; private ModConfig Config;
@ -103,7 +99,7 @@ namespace Omegasis.BuildHealth
this.LastHealth = player.health; this.LastHealth = player.health;
// give XP when player stays up too late or collapses // give XP when player stays up too late or collapses
if (!this.WasCollapsed && shouldFarmerPassout()) if (!this.WasCollapsed && this.shouldFarmerPassout())
{ {
this.PlayerData.CurrentExp += this.Config.ExpForCollapsing; this.PlayerData.CurrentExp += this.Config.ExpForCollapsing;
this.WasCollapsed = true; this.WasCollapsed = true;
@ -122,7 +118,6 @@ namespace Omegasis.BuildHealth
this.WasCollapsed = false; this.WasCollapsed = false;
// load player data // load player data
this.MigrateLegacyData();
this.PlayerData = this.Helper.ReadJsonFile<PlayerData>(this.DataFilePath) ?? new PlayerData(); this.PlayerData = this.Helper.ReadJsonFile<PlayerData>(this.DataFilePath) ?? new PlayerData();
if (this.PlayerData.OriginalMaxHealth == 0) if (this.PlayerData.OriginalMaxHealth == 0)
this.PlayerData.OriginalMaxHealth = Game1.player.maxHealth; this.PlayerData.OriginalMaxHealth = Game1.player.maxHealth;
@ -177,39 +172,6 @@ namespace Omegasis.BuildHealth
this.Helper.WriteJsonFile(this.DataFilePath, this.PlayerData); this.Helper.WriteJsonFile(this.DataFilePath, this.PlayerData);
} }
/// <summary>Migrate the legacy settings for the current player.</summary>
private void MigrateLegacyData()
{
// skip if no legacy data or new data already exists
if (!File.Exists(this.LegacyDataFilePath) || File.Exists(this.DataFilePath))
return;
// migrate to new file
try
{
string[] text = File.ReadAllLines(this.LegacyDataFilePath);
this.Helper.WriteJsonFile(this.DataFilePath, new PlayerData
{
CurrentLevel = Convert.ToInt32(text[3]),
CurrentExp = Convert.ToDouble(text[5]),
ExpToNextLevel = Convert.ToDouble(text[7]),
BaseHealthBonus = Convert.ToInt32(text[9]),
CurrentLevelHealthBonus = Convert.ToInt32(text[11]),
ClearModEffects = Convert.ToBoolean(text[14]),
OriginalMaxHealth = Convert.ToInt32(text[16])
});
FileInfo file = new FileInfo(this.LegacyDataFilePath);
file.Delete();
if (!file.Directory.EnumerateFiles().Any())
file.Directory.Delete();
}
catch (Exception ex)
{
this.Monitor.Log($"Error migrating data from the legacy 'PlayerData' folder for the current player. Technical details:\n {ex}", LogLevel.Error);
}
}
public bool shouldFarmerPassout() public bool shouldFarmerPassout()
{ {
if (Game1.player.stamina <= 0 || Game1.player.health <= 0 || Game1.timeOfDay >= 2600) return true; if (Game1.player.stamina <= 0 || Game1.player.health <= 0 || Game1.timeOfDay >= 2600) return true;

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -11,8 +11,6 @@
<AssemblyName>BuildHealth</AssemblyName> <AssemblyName>BuildHealth</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -67,6 +65,9 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Pathoschild.Stardew.ModBuildConfig" Version="2.2.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
@ -82,19 +83,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="manifest.json" /> <None Include="manifest.json" />
<None Include="packages.config" />
<None Include="README.md" /> <None Include="README.md" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\analyzers\dotnet\cs\StardewModdingAPI.ModBuildConfig.Analyzer.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\deploy.targets" /> <Import Project="$(SolutionDir)\deploy.targets" />
<Import Project="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\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>
<Error Condition="!Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets'))" />
</Target>
</Project> </Project>

View File

@ -1,4 +1,4 @@
namespace Omegasis.BuildHealth.Framework namespace Omegasis.BuildHealth.Framework
{ {
/// <summary>The mod settings and player data.</summary> /// <summary>The mod settings and player data.</summary>
internal class ModConfig internal class ModConfig

View File

@ -1,4 +1,4 @@
namespace Omegasis.BuildHealth.Framework namespace Omegasis.BuildHealth.Framework
{ {
/// <summary>The data for the current player.</summary> /// <summary>The data for the current player.</summary>
internal class PlayerData internal class PlayerData

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Pathoschild.Stardew.ModBuildConfig" version="2.2.0" targetFramework="net45" />
</packages>

View File

@ -1,4 +1,4 @@
using Omegasis.BuyBackCollectables.Framework; using Omegasis.BuyBackCollectables.Framework;
using StardewModdingAPI; using StardewModdingAPI;
using StardewModdingAPI.Events; using StardewModdingAPI.Events;
using StardewValley; using StardewValley;

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -11,8 +11,6 @@
<AssemblyName>BuyBackCollectables</AssemblyName> <AssemblyName>BuyBackCollectables</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -67,6 +65,9 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Pathoschild.Stardew.ModBuildConfig" Version="2.2.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
@ -84,19 +85,8 @@
<None Include="manifest.json" /> <None Include="manifest.json" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="packages.config" />
<None Include="README.md" /> <None Include="README.md" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\analyzers\dotnet\cs\StardewModdingAPI.ModBuildConfig.Analyzer.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\deploy.targets" /> <Import Project="$(SolutionDir)\deploy.targets" />
<Import Project="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\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>
<Error Condition="!Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets'))" />
</Target>
</Project> </Project>

View File

@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;

View File

@ -1,4 +1,4 @@
namespace Omegasis.BuyBackCollectables.Framework namespace Omegasis.BuyBackCollectables.Framework
{ {
/// <summary>The mod configuration.</summary> /// <summary>The mod configuration.</summary>
internal class ModConfig internal class ModConfig

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Pathoschild.Stardew.ModBuildConfig" version="2.2.0" targetFramework="net45" />
</packages>

View File

@ -1,20 +1,14 @@
using CustomNPCFramework.Framework.Enums;
using CustomNPCFramework.Framework.Graphics;
using CustomNPCFramework.Framework.ModularNPCS;
using CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases;
using CustomNPCFramework.Framework.ModularNPCS.ColorCollections;
using CustomNPCFramework.Framework.NPCS;
using CustomNPCFramework.Framework.Utilities;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI;
using StardewValley;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using CustomNPCFramework.Framework.Enums;
using System.Text; using CustomNPCFramework.Framework.Graphics;
using System.Threading.Tasks; using CustomNPCFramework.Framework.ModularNpcs.ColorCollections;
using CustomNPCFramework.Framework.NPCS;
using CustomNPCFramework.Framework.Utilities;
using Microsoft.Xna.Framework;
using StardewModdingAPI;
using StardewValley;
namespace CustomNPCFramework namespace CustomNPCFramework
{ {
@ -44,91 +38,73 @@ namespace CustomNPCFramework
/// Find way to make sideways shirts render correctly. /// Find way to make sideways shirts render correctly.
/// ///
///Get suggestions from modding community on requests and ways to improve the mod. ///Get suggestions from modding community on requests and ways to improve the mod.
/// </summary> /// </summary>
public class Class1 : Mod public class Class1 : Mod
{ {
/// <summary> /// <summary>The mod helper for the mod.</summary>
/// The mod helper for the mod.
/// </summary>
public static IModHelper ModHelper; public static IModHelper ModHelper;
/// <summary>
/// The mod monitor for the mod. /// <summary>The mod monitor for the mod.</summary>
/// </summary>
public static IMonitor ModMonitor; public static IMonitor ModMonitor;
/// <summary> /// <summary>The npc tracker for the mod. Keeps track of all npcs added by the custom framework and cleans them up during saving.</summary>
/// The npc tracker for the mod. Keeps track of all npcs added by the custom framework and cleans them up during saving. public static NpcTracker npcTracker;
/// </summary>
public static NPCTracker npcTracker; /// <summary>Keeps track of all of the asets/textures added in by the framework. Also manages all of the asset managers that are the ones actually managing the textures.</summary>
/// <summary>
/// Keeps track of all of the asets/textures added in by the framework. Also manages all of the asset managers that are the ones actually managing the textures.
/// </summary>
public static AssetPool assetPool; public static AssetPool assetPool;
public static IManifest Manifest; public static IManifest Manifest;
/// <summary> /// <summary>The mod entry point, called after the mod is first loaded.</summary>
/// Ran when loading the SMAPI. Used to initialize data. /// <param name="helper">Provides simplified APIs for writing mods.</param>
/// </summary>
/// <param name="helper"></param>
public override void Entry(IModHelper helper) public override void Entry(IModHelper helper)
{ {
ModHelper = this.Helper; ModHelper = this.Helper;
ModMonitor = this.Monitor; ModMonitor = this.Monitor;
Manifest = ModManifest; Manifest = this.ModManifest;
StardewModdingAPI.Events.SaveEvents.AfterLoad += SaveEvents_LoadChar; StardewModdingAPI.Events.SaveEvents.AfterLoad += this.SaveEvents_LoadChar;
StardewModdingAPI.Events.SaveEvents.BeforeSave += SaveEvents_BeforeSave; StardewModdingAPI.Events.SaveEvents.BeforeSave += this.SaveEvents_BeforeSave;
StardewModdingAPI.Events.SaveEvents.AfterSave += SaveEvents_AfterSave; StardewModdingAPI.Events.SaveEvents.AfterSave += this.SaveEvents_AfterSave;
StardewModdingAPI.Events.PlayerEvents.Warped += LocationEvents_CurrentLocationChanged; StardewModdingAPI.Events.PlayerEvents.Warped += this.LocationEvents_CurrentLocationChanged;
StardewModdingAPI.Events.GameEvents.UpdateTick += GameEvents_UpdateTick; StardewModdingAPI.Events.GameEvents.UpdateTick += this.GameEvents_UpdateTick;
npcTracker = new NPCTracker(); npcTracker = new NpcTracker();
assetPool = new AssetPool(); assetPool = new AssetPool();
var assetManager = new AssetManager(); var assetManager = new AssetManager();
assetPool.addAssetManager(new KeyValuePair<string, AssetManager>("testNPC", assetManager)); assetPool.addAssetManager(new KeyValuePair<string, AssetManager>("testNPC", assetManager));
initializeExamples(); this.initializeExamples();
initializeAssetPool(); this.initializeAssetPool();
assetPool.loadAllAssets(); assetPool.loadAllAssets();
} }
/// <summary> /// <summary>Initialize the asset pool with some test variables.</summary>
/// Initialize the asset pool with some test variables.
/// </summary>
public void initializeAssetPool() public void initializeAssetPool()
{ {
string path = Path.Combine(ModHelper.DirectoryPath, "Content", "Graphics", "NPCS"); string path = Path.Combine(ModHelper.DirectoryPath, "Content", "Graphics", "NPCS");
assetPool.getAssetManager("testNPC").addPathCreateDirectory(new KeyValuePair<string, string>("characters", path)); assetPool.getAssetManager("testNPC").addPathCreateDirectory(new KeyValuePair<string, string>("characters", path));
} }
/// <summary> /// <summary>A function that is called when the game finishes saving.</summary>
/// A function that is called when the game finishes saving. /// <param name="sender">The event sender.</param>
/// </summary> /// <param name="e">The event arguments.</param>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveEvents_AfterSave(object sender, EventArgs e) private void SaveEvents_AfterSave(object sender, EventArgs e)
{ {
npcTracker.afterSave(); npcTracker.afterSave();
} }
/// <summary> /// <summary>A function that is called when the game is about to load. Used to clean up all the npcs from the game world to prevent it from crashing.</summary>
/// A function that is called when the game is about to load. Used to clean up all the npcs from the game world to prevent it from crashing. /// <param name="sender">The event sender.</param>
/// </summary> /// <param name="e">The event arguments.</param>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveEvents_BeforeSave(object sender, EventArgs e) private void SaveEvents_BeforeSave(object sender, EventArgs e)
{ {
npcTracker.cleanUpBeforeSave(); npcTracker.cleanUpBeforeSave();
} }
/// <summary> /// <summary>Called upon 60 times a second. For testing purposes only. Will remove in future release.</summary>
/// Called upon 60 times a second. For testing purposes only. Will remove in future release. /// <param name="sender">The event sender.</param>
/// </summary> /// <param name="e">The event arguments.</param>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GameEvents_UpdateTick(object sender, EventArgs e) private void GameEvents_UpdateTick(object sender, EventArgs e)
{ {
/* /*
@ -147,47 +123,37 @@ namespace CustomNPCFramework
*/ */
} }
/// <summary> /// <summary>Called when the player's location changes.</summary>
/// Called when the player's location changes. /// <param name="sender">The event sender.</param>
/// </summary> /// <param name="e">The event arguments.</param>
/// <param name="sender"></param> private void LocationEvents_CurrentLocationChanged(object sender, StardewModdingAPI.Events.EventArgsPlayerWarped e) { }
/// <param name="e"></param>
private void LocationEvents_CurrentLocationChanged(object sender, StardewModdingAPI.Events.EventArgsPlayerWarped e)
{
} /// <summary>Used to spawn a custom npc just as an example. Don't keep this code. GENERATE NPC AND CALL THE CODE</summary>
/// <param name="sender">The event sender.</param>
/// <summary> /// <param name="e">The event arguments.</param>
/// Used to spawn a custom npc just as an example. Don't keep this code.
/// GENERATE NPC AND CALL THE CODE
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveEvents_LoadChar(object sender, EventArgs e) private void SaveEvents_LoadChar(object sender, EventArgs e)
{ {
ExtendedNPC myNpc3 = assetPool.generateNPC(Genders.female, 0, 1,new StandardColorCollection(null, null, Color.Blue, null, Color.Yellow, null)); ExtendedNpc myNpc3 = assetPool.generateNPC(Genders.female, 0, 1, new StandardColorCollection(null, null, Color.Blue, null, Color.Yellow, null));
MerchantNPC merch = new MerchantNPC(new List<Item>() MerchantNpc merch = new MerchantNpc(new List<Item>()
{ {
new StardewValley.Object(475,999) new StardewValley.Object(475,999)
}, myNpc3); }, myNpc3);
npcTracker.addNewNPCToLocation(Game1.getLocationFromName("BusStop", false), merch,new Vector2(2,23)); npcTracker.addNewNpcToLocation(Game1.getLocationFromName("BusStop", false), merch, new Vector2(2, 23));
} }
/// <summary> /// <summary>Used to initialize examples for other modders to look at as reference.</summary>
/// Used to initialize examples for other modders to look at as reference.
/// </summary>
public void initializeExamples() public void initializeExamples()
{ {
return; return;
string dirPath = Path.Combine(ModHelper.DirectoryPath, "Content", "Templates"); string dirPath = Path.Combine(ModHelper.DirectoryPath, "Content", "Templates");
var aManager=assetPool.getAssetManager("testNPC"); var aManager = assetPool.getAssetManager("testNPC");
aManager.addPathCreateDirectory(new KeyValuePair<string, string>("templates", dirPath)); aManager.addPathCreateDirectory(new KeyValuePair<string, string>("templates", dirPath));
string filePath =Path.Combine(dirPath, "Example.json"); string filePath = Path.Combine(dirPath, "Example.json");
if (!File.Exists(filePath)) if (!File.Exists(filePath))
{ {
string getRelativePath = getShortenedDirectory(filePath); string getRelativePath = getShortenedDirectory(filePath);
ModMonitor.Log("THIS IS THE PATH::: " + getRelativePath); ModMonitor.Log("THIS IS THE PATH::: " + getRelativePath);
AssetInfo info = new AssetInfo("MyExample",new NamePairings("StandingExampleL", "StandingExampleR", "StandingExampleU", "StandingExampleD"), new NamePairings("MovingExampleL", "MovingExampleR", "MovingExampleU", "MovingExampleD"), new NamePairings("SwimmingExampleL", "SwimmingExampleR", "SwimmingExampleU", "SwimmingExampleD"), new NamePairings("SittingExampleL", "SittingExampleR", "SittingExampleU", "SittingExampleD"), new Vector2(16, 16), false); AssetInfo info = new AssetInfo("MyExample", new NamePairings("StandingExampleL", "StandingExampleR", "StandingExampleU", "StandingExampleD"), new NamePairings("MovingExampleL", "MovingExampleR", "MovingExampleU", "MovingExampleD"), new NamePairings("SwimmingExampleL", "SwimmingExampleR", "SwimmingExampleU", "SwimmingExampleD"), new NamePairings("SittingExampleL", "SittingExampleR", "SittingExampleU", "SittingExampleD"), new Vector2(16, 16), false);
info.writeToJson(filePath); info.writeToJson(filePath);
} }
@ -205,31 +171,22 @@ namespace CustomNPCFramework
} }
} }
/// <summary> /// <summary>Used to splice the mod directory to get relative paths.</summary>
/// Used to splice the mod directory to get relative paths.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string getShortenedDirectory(string path) public static string getShortenedDirectory(string path)
{ {
string lol = (string)path.Clone(); string lol = (string)path.Clone();
string[] spliter = lol.Split(new string[] { ModHelper.DirectoryPath },StringSplitOptions.None); string[] spliter = lol.Split(new string[] { ModHelper.DirectoryPath }, StringSplitOptions.None);
try try
{ {
return spliter[1]; return spliter[1];
} }
catch(Exception err) catch
{ {
err.ToString();
return spliter[0]; return spliter[0];
} }
} }
/// <summary> /// <summary>Used to finish cleaning up absolute asset paths into a shortened relative path.</summary>
/// Used to finish cleaning up absolute asset paths into a shortened relative path.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string getRelativeDirectory(string path) public static string getRelativeDirectory(string path)
{ {
string s = getShortenedDirectory(path); string s = getShortenedDirectory(path);

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -11,9 +11,6 @@
<AssemblyName>CustomNPCFramework</AssemblyName> <AssemblyName>CustomNPCFramework</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<TargetFrameworkProfile />
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -70,6 +67,9 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Pathoschild.Stardew.ModBuildConfig" Version="2.2.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
@ -93,20 +93,20 @@
<Compile Include="Framework\Enums\Genders.cs" /> <Compile Include="Framework\Enums\Genders.cs" />
<Compile Include="Framework\Graphics\AssetPool.cs" /> <Compile Include="Framework\Graphics\AssetPool.cs" />
<Compile Include="Framework\Graphics\TextureGroups\TextureGroup.cs" /> <Compile Include="Framework\Graphics\TextureGroups\TextureGroup.cs" />
<Compile Include="Framework\ModularNPCS\AnimatedSpriteCollection.cs" /> <Compile Include="Framework\ModularNpcs\AnimatedSpriteCollection.cs" />
<Compile Include="Framework\ModularNPCS\AnimatedSpriteExtended.cs" /> <Compile Include="Framework\ModularNpcs\AnimatedSpriteExtended.cs" />
<Compile Include="Framework\ModularNPCS\CharacterAnimationBases\StandardCharacterAnimation.cs" /> <Compile Include="Framework\ModularNpcs\CharacterAnimationBases\StandardCharacterAnimation.cs" />
<Compile Include="Framework\ModularNPCS\CharacterAnimationBases\CharacterAnimationBase.cs" /> <Compile Include="Framework\ModularNpcs\CharacterAnimationBases\CharacterAnimationBase.cs" />
<Compile Include="Framework\Enums\Direction.cs" /> <Compile Include="Framework\Enums\Direction.cs" />
<Compile Include="Framework\ModularNPCS\ColorCollections\StandardColorCollection.cs" /> <Compile Include="Framework\ModularNpcs\ColorCollections\StandardColorCollection.cs" />
<Compile Include="Framework\ModularNPCS\ModularRenderers\AnimationKeys.cs" /> <Compile Include="Framework\ModularNpcs\ModularRenderers\AnimationKeys.cs" />
<Compile Include="Framework\ModularNPCS\ModularRenderers\BasicRenderer.cs" /> <Compile Include="Framework\ModularNpcs\ModularRenderers\BasicRenderer.cs" />
<Compile Include="Framework\ModularNPCS\Portrait.cs" /> <Compile Include="Framework\ModularNpcs\Portrait.cs" />
<Compile Include="Framework\ModularNPCS\Sprite.cs" /> <Compile Include="Framework\ModularNpcs\Sprite.cs" />
<Compile Include="Framework\NPCNames.cs" /> <Compile Include="Framework\NpcNames.cs" />
<Compile Include="Framework\NPCS\ExtendedNPC.cs" /> <Compile Include="Framework\NPCS\ExtendedNpc.cs" />
<Compile Include="Framework\NPCS\MerchantNPC.cs" /> <Compile Include="Framework\NPCS\MerchantNpc.cs" />
<Compile Include="Framework\Utilities\NPCTracker.cs" /> <Compile Include="Framework\Utilities\NpcTracker.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@ -116,24 +116,7 @@
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="packages.config" /> <None Include="manifest.json" />
</ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\analyzers\dotnet\cs\StardewModdingAPI.ModBuildConfig.Analyzer.dll" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\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>
<Error Condition="!Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets'))" />
</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>
-->
</Project> </Project>

View File

@ -1,31 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.Enums namespace CustomNPCFramework.Framework.Enums
{ {
/// <summary> /// <summary>A enum of different types of animations supported by the framework.</summary>
/// A enum of different types of animations supported by the framework.
/// </summary>
public enum AnimationType public enum AnimationType
{ {
/// <summary> /// <summary>A key to be used whenever an npc uses a standing animation.</summary>
/// A key to be used whenever an npc uses a standing animation.
/// </summary>
standing, standing,
/// <summary>
/// A key to be used wheneven an npc uses a walking/moving animation. /// <summary>A key to be used wheneven an npc uses a walking/moving animation.</summary>
/// </summary>
walking, walking,
/// <summary>
/// A key to be used whenever an npc uses a swimming animation. /// <summary>A key to be used whenever an npc uses a swimming animation.</summary>
/// </summary>
swimming, swimming,
/// <summary>
/// A key to be used whenever an npc uses a sitting animation. /// <summary>A key to be used whenever an npc uses a sitting animation.</summary>
/// </summary>
sitting sitting
} }
} }

View File

@ -1,36 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.Enums namespace CustomNPCFramework.Framework.Enums
{ {
/// <summary> /// <summary>An enum to be used to signify directions. The enum order corresponds to the same order Stardew Valley uses for directions.</summary>
/// An enum to be used to signify directions.
/// The enum order corresponds to the same order Stardew Valley uses for directions where
/// Up=0
/// Right=1
/// Down=2
/// Left=3
/// </summary>
public enum Direction public enum Direction
{ {
/// <summary> /// <summary>Used to signify something to face/move up.</summary>
/// Used to signify something to face/move up. up = 0,
/// </summary>
up, /// <summary>Used to signify something to face/move right.</summary>
/// <summary> right = 1,
/// Used to signify something to face/move right.
/// </summary> /// <summary>Used to signify something to face/move down.</summary>
right, down = 2,
/// <summary>
/// Used to signify something to face/move down. /// <summary>Used to signify something to face/move left.</summary>
/// </summary> left = 3
down,
/// <summary>
/// Used to signify something to face/move left.
/// </summary>
left
} }
} }

View File

@ -1,28 +1,17 @@
using System; using StardewValley;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.Enums namespace CustomNPCFramework.Framework.Enums
{ {
/// <summary> /// <summary>Gender enum to signify the different genders for NPCs. Do what you want with this. For code simplicity anything that is non-binary is specified under other.</summary>
/// Gender enum to signify the different genders for npcs.
/// Do what you want with this. For code simplicity anything that is non-binary is specified under other.
/// </summary>
public enum Genders public enum Genders
{ {
/// <summary> /// <summary>Used for npcs to signify that they are the male gender.</summary>
/// Used for npcs to signify that they are the male gender. male = NPC.male,
/// </summary>
male, /// <summary>Used for npcs to signify that they are the female gender.</summary>
/// <summary> female = NPC.female,
/// Used for npcs to signify that they are the female gender.
/// </summary> /// <summary>Used for npcs to signify that they are a non gender binary gender.</summary>
female, other = NPC.undefined
/// <summary>
/// Used for npcs to signify that they are a non gender binary gender.
/// </summary>
other
} }
} }

View File

@ -1,55 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.Enums namespace CustomNPCFramework.Framework.Enums
{ {
/// <summary> /// <summary>An enum used to signify the different asset types that can be used for NPCs.</summary>
/// An enum used to signify the different asset types that can be used for npcs.
/// </summary>
public enum PartType public enum PartType
{ {
/// <summary> /// <summary>Used to signify that the asset is of the body part category. Without this the npc is basically a ghost.</summary>
/// Used to signify that the asset is of the body part category. Without this the npc is basically a ghost.
/// </summary>
body, body,
/// <summary>
/// Used to signify that the asset is of the eyes part category. The window to the soul. /// <summary>Used to signify that the asset is of the eyes part category. The window to the soul.</summary>
/// </summary>
eyes, eyes,
/// <summary>
/// Used to signify that the asset is of the hair part category. Volume looks good in 2D. /// <summary>Used to signify that the asset is of the hair part category. Volume looks good in 2D.</summary>
/// </summary>
hair, hair,
/// <summary>
/// Used to signify that the asset is of the shirt part category.No shirt = no service. /// <summary>Used to signify that the asset is of the shirt part category.No shirt = no service.</summary>
/// </summary>
shirt, shirt,
/// <summary>
/// Used to signify that the asset is of the pants/bottoms part category. Also known as bottoms, skirts, shorts, etc. /// <summary>Used to signify that the asset is of the pants/bottoms part category. Also known as bottoms, skirts, shorts, etc.</summary>
/// </summary>
pants, pants,
/// <summary>
/// Used to signify that the asset is of the shoes part category. Lace up those kicks. /// <summary>Used to signify that the asset is of the shoes part category. Lace up those kicks.</summary>
/// </summary>
shoes, shoes,
/// <summary>
/// Used to signify that the asset is of the accessort part category. Got to wear that bling. /// <summary>Used to signify that the asset is of the accessort part category. Got to wear that bling.</summary>
/// </summary>
accessory, accessory,
/// <summary>
/// Used to signify that the asset is of the other part category. Who knows what this really is... /// <summary>Used to signify that the asset is of the other part category. Who knows what this really is...</summary>
/// </summary>
other, other,
/// <summary>
/// Used to signify that the asset is of the swimsuit part category. Got to be decent when taking a dip. /// <summary>Used to signify that the asset is of the swimsuit part category. Got to be decent when taking a dip.</summary>
/// </summary>
swimsuit, swimsuit,
/// <summary>
/// Used to signify that the asset is of the amrs part category. Arms need to be rendered above a shirt on npcs otherwise they get covered. /// <summary>Used to signify that the asset is of the amrs part category. Arms need to be rendered above a shirt on npcs otherwise they get covered.</summary>
/// </summary>
arms arms
} }
} }

View File

@ -1,36 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.Enums namespace CustomNPCFramework.Framework.Enums
{ {
/// <summary> /// <summary>An enum signifying the different seasons that are supported when choosing NPC graphics.</summary>
/// An enum signifying the different seasons that are supported when chosing npc graphics.
/// </summary>
public enum Seasons public enum Seasons
{ {
/// <summary> /// <summary>The spring season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the spring time. Also used for functionality to check seasons.</summary>
/// The spring season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the spring time.
/// Also used for functionality to check seasons.
/// </summary>
spring, spring,
/// <summary>
/// The summer season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the summer time. /// <summary>The summer season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the summer time. Also used for functionality to check seasons.</summary>
/// Also used for functionality to check seasons.
/// </summary>
summer, summer,
/// <summary>
/// The fall season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the fall time. /// <summary>The fall season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the fall time. Also used for functionality to check seasons.</summary>
/// Also used for functionality to check seasons.
/// </summary>
fall, fall,
/// <summary>
/// The winter season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the winter time. /// <summary>The winter season. This ensures that a corresponding graphic with this enum in it's seasons list can be chosen in the winter time. Also used for functionality to check seasons.</summary>
/// Also used for functionality to check seasons.
/// </summary>
winter winter
} }
} }

View File

@ -1,89 +1,62 @@
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.Graphics namespace CustomNPCFramework.Framework.Graphics
{ {
/// <summary> /// <summary>A class to be used to hold information regarding assets such as the name of the assets and the paths to the images.</summary>
/// A class to be used to hold information regarding assets such as the name of the assets and the paths to the images.
/// </summary>
public class AssetInfo public class AssetInfo
{ {
/// <summary> /// <summary>The name of the asset to be used in the main asset pool.</summary>
/// The name of the asset to be used in the main asset pool.
/// </summary>
public string assetName; public string assetName;
/// <summary>
/// The list of files to be used for the standing animation. /// <summary>The list of files to be used for the standing animation.</summary>
/// </summary>
public NamePairings standingAssetPaths; public NamePairings standingAssetPaths;
/// <summary>
/// The list of files to be used for the swimming animation. /// <summary>The list of files to be used for the swimming animation.</summary>
/// </summary>
public NamePairings swimmingAssetPaths; public NamePairings swimmingAssetPaths;
/// <summary>
/// The list of files to be used with the moving animation. /// <summary>The list of files to be used with the moving animation.</summary>
/// </summary>
public NamePairings movingAssetPaths; public NamePairings movingAssetPaths;
/// <summary>
/// The list of files to be used with the sitting animation. /// <summary>The list of files to be used with the sitting animation.</summary>
/// </summary>
public NamePairings sittingAssetPaths; public NamePairings sittingAssetPaths;
/// <summary>
/// The size of the asset texture. Width and height. /// <summary>The size of the asset texture. Width and height.</summary>
/// </summary>
public Vector2 assetSize; public Vector2 assetSize;
/// <summary>
/// Not really used anymore. More of a legacy feature. /// <summary>Not really used anymore. More of a legacy feature.</summary>
/// </summary>
public bool randomizeUponLoad; public bool randomizeUponLoad;
/// <summary> /// <summary>Construct an instance.</summary>
/// Empty constructor. public AssetInfo() { }
/// </summary>
public AssetInfo()
{
} /// <summary>Construct an instance.</summary>
/// <summary>
/// Constructor that assigns values to the class.
/// </summary>
/// <param name="assetName">The name of the asset. This is the name that will be referenced in any asset manager or asset pool.</param> /// <param name="assetName">The name of the asset. This is the name that will be referenced in any asset manager or asset pool.</param>
/// <param name="StandingAssetPaths">The name of the files to be used for the standing animation.</param> /// <param name="standingAssetPaths">The name of the files to be used for the standing animation.</param>
/// <param name="MovingAssetPaths">The name of the files to be used for the moving animation.</param> /// <param name="movingAssetPaths">The name of the files to be used for the moving animation.</param>
/// <param name="SwimmingAssetPaths">The name of the files to be used for the swimming animation.</param> /// <param name="swimmingAssetPaths">The name of the files to be used for the swimming animation.</param>
/// <param name="SittingAssetPaths">The name of the files to be used for the sitting animation.</param> /// <param name="sittingAssetPaths">The name of the files to be used for the sitting animation.</param>
/// <param name="assetSize">The size of the asset. Width and height of the texture.</param> /// <param name="assetSize">The size of the asset. Width and height of the texture.</param>
/// <param name="randomizeUponLoad">Legacy, not really used anymore.</param> /// <param name="randomizeUponLoad">Legacy, not really used anymore.</param>
public AssetInfo(string assetName,NamePairings StandingAssetPaths, NamePairings MovingAssetPaths, NamePairings SwimmingAssetPaths, NamePairings SittingAssetPaths, Vector2 assetSize, bool randomizeUponLoad) public AssetInfo(string assetName, NamePairings standingAssetPaths, NamePairings movingAssetPaths, NamePairings swimmingAssetPaths, NamePairings sittingAssetPaths, Vector2 assetSize, bool randomizeUponLoad)
{ {
this.assetName = assetName; this.assetName = assetName;
this.sittingAssetPaths = SittingAssetPaths; this.sittingAssetPaths = sittingAssetPaths;
this.standingAssetPaths = StandingAssetPaths; this.standingAssetPaths = standingAssetPaths;
this.movingAssetPaths = MovingAssetPaths; this.movingAssetPaths = movingAssetPaths;
this.swimmingAssetPaths = SwimmingAssetPaths; this.swimmingAssetPaths = swimmingAssetPaths;
this.assetSize = assetSize; this.assetSize = assetSize;
this.randomizeUponLoad = randomizeUponLoad; this.randomizeUponLoad = randomizeUponLoad;
} }
/// <summary> /// <summary>Save the json to a certain location.</summary>
/// Save the json to a certain location. /// <param name="path">The absolute path to save.</param>
/// </summary>
/// <param name="path"></param>
public void writeToJson(string path) public void writeToJson(string path)
{ {
Class1.ModHelper.WriteJsonFile<AssetInfo>(path, this); Class1.ModHelper.WriteJsonFile<AssetInfo>(path, this);
} }
/// <summary> /// <summary>Read the json from a certain location.</summary>
/// Read the json from a certain location. /// <param name="path">The absolute path to save.</param>
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static AssetInfo readFromJson(string path) public static AssetInfo readFromJson(string path)
{ {
return Class1.ModHelper.ReadJsonFile<AssetInfo>(path); return Class1.ModHelper.ReadJsonFile<AssetInfo>(path);

View File

@ -1,286 +1,229 @@
using CustomNPCFramework.Framework.Enums;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using CustomNPCFramework.Framework.Enums;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.Graphics namespace CustomNPCFramework.Framework.Graphics
{ {
/// <summary> /// <summary>Used to hold assets from specified directories.</summary>
/// Used to hold assets from specified directories.
/// </summary>
public class AssetManager public class AssetManager
{ {
/// <summary> /// <summary>A list of all of the assets held by this asset manager.</summary>
/// A list of all of the assets held by this asset manager.
/// </summary>
public List<AssetSheet> assets; public List<AssetSheet> assets;
/// <summary>
/// A list of all of the directories managed by this asset manager.
/// </summary>
public Dictionary<string,string> paths;
/// <summary> /// <summary>A list of all of the directories managed by this asset manager.</summary>
/// Basic constructor. public Dictionary<string, string> paths;
/// </summary>
/// <summary>Construct an instance.</summary>
public AssetManager() public AssetManager()
{ {
this.assets = new List<AssetSheet>(); this.assets = new List<AssetSheet>();
this.paths = new Dictionary<string, string>(); this.paths = new Dictionary<string, string>();
} }
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor.
/// </summary>
/// <param name="assetsPathsToLoadFrom">A list of all directories to be managed by the asset manager. Name, path is the key pair value.</param> /// <param name="assetsPathsToLoadFrom">A list of all directories to be managed by the asset manager. Name, path is the key pair value.</param>
public AssetManager(Dictionary<string,string> assetsPathsToLoadFrom) public AssetManager(Dictionary<string, string> assetsPathsToLoadFrom)
{ {
this.assets = new List<AssetSheet>(); this.assets = new List<AssetSheet>();
this.paths = assetsPathsToLoadFrom; this.paths = assetsPathsToLoadFrom;
} }
/// <summary> /// <summary>Default loading function from hardcoded paths.</summary>
/// Default loading function from hard coded paths.
/// </summary>
public void loadAssets() public void loadAssets()
{ {
foreach(var path in this.paths) foreach (var path in this.paths)
{ this.ProcessDirectory(path.Value);
ProcessDirectory(path.Value);
}
} }
/// <summary> /// <summary>Process all .json files in the given directory. If there are more nested directories, keep digging to find more .json files. Also allows us to specify a broader directory like Content/Grahphics/ModularNPC/Hair to have multiple hair styles.</summary>
/// Taken from Microsoft c# documented webpages. /// <param name="targetDirectory">The absolute directory path to process.</param>
/// Process all .json files in the given directory. If there are more nested directories, keep digging to find more .json files. Also allows us to specify a broader directory like Content/Grahphics/ModularNPC/Hair to have multiple hair styles. /// <remarks>Taken from Microsoft c# documented webpages.</remarks>
/// </summary>
/// <param name="targetDirectory"></param>
private void ProcessDirectory(string targetDirectory) private void ProcessDirectory(string targetDirectory)
{ {
// Process the list of files found in the directory. // Process the list of files found in the directory.
string[] files = Directory.GetFiles(targetDirectory, "*.json"); string[] files = Directory.GetFiles(targetDirectory, "*.json");
foreach (var file in files) foreach (string file in files)
{ this.ProcessFile(file, targetDirectory);
ProcessFile(file,targetDirectory);
}
// Recurse into subdirectories of this directory. // Recurse into subdirectories of this directory.
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory); string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries) foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory); this.ProcessDirectory(subdirectory);
} }
/// <summary> /// <summary>Actually load in the asset information.</summary>
/// Actually load in the asset information. /// <param name="file">The absolute file path to process.</param>
/// </summary> /// <param name="path">The absolute directory path containing the file.</param>
/// <param name="file"></param> private void ProcessFile(string file, string path)
/// <param name="path"></param>
private void ProcessFile(string file,string path)
{ {
try try
{ {
ExtendedAssetInfo info = ExtendedAssetInfo.readFromJson(file); ExtendedAssetInfo info = ExtendedAssetInfo.readFromJson(file);
AssetSheet sheet = new AssetSheet(info, path); AssetSheet sheet = new AssetSheet(info, path);
addAsset(sheet); this.addAsset(sheet);
Class1.ModMonitor.Log("Loaded in new modular asset: " + info.assetName + " asset type: " + info.type); Class1.ModMonitor.Log("Loaded in new modular asset: " + info.assetName + " asset type: " + info.type);
} }
catch (Exception err) catch
{ {
AssetInfo info = AssetInfo.readFromJson(file); AssetInfo info = AssetInfo.readFromJson(file);
AssetSheet sheet = new AssetSheet(info, path); AssetSheet sheet = new AssetSheet(info, path);
addAsset(sheet); this.addAsset(sheet);
} }
} }
/// <summary> /// <summary>Add an asset to be handled from the asset manager.</summary>
/// Add an asset to be handled from the asset manager. /// <param name="asset">The asset sheet.</param>
/// </summary>
/// <param name="asset"></param>
public void addAsset(AssetSheet asset) public void addAsset(AssetSheet asset)
{ {
this.assets.Add(asset); this.assets.Add(asset);
} }
/// <summary> /// <summary>Get an individual asset by its name.</summary>
/// Get an individual asset by its name. /// <param name="s">The asset name.</param>
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public AssetSheet getAssetByName(string s) public AssetSheet getAssetByName(string s)
{ {
foreach(var v in assets) foreach (var v in this.assets)
{ {
if (v.assetInfo.assetName == s) return v; if (v.assetInfo.assetName == s)
return v;
} }
return null; return null;
} }
/// <summary> /// <summary>Add a new path to the asset manager and create the directory for it.</summary>
/// Add a new path to the asset manager and create the directory for it. /// <param name="path">The absolute path to add.</param>
/// </summary> public void addPathCreateDirectory(KeyValuePair<string, string> path)
/// <param name="path"></param>
public void addPathCreateDirectory(KeyValuePair<string,string> path)
{ {
this.addPath(path); this.addPath(path);
string dir = Path.Combine(Class1.ModHelper.DirectoryPath, path.Value); string dir = Path.Combine(Class1.ModHelper.DirectoryPath, path.Value);
if (!Directory.Exists(dir)) if (!Directory.Exists(dir))
{
Directory.CreateDirectory(Path.Combine(Class1.ModHelper.DirectoryPath, path.Value)); Directory.CreateDirectory(Path.Combine(Class1.ModHelper.DirectoryPath, path.Value));
} }
}
/// <summary> /// <summary>Add a path to the dictionary.</summary>
/// Add a path to the dictionary. /// <param name="path">The absolute path to add.</param>
/// </summary> private void addPath(KeyValuePair<string, string> path)
/// <param name="path"></param>
private void addPath(KeyValuePair<string,string> path)
{ {
this.paths.Add(path.Key, path.Value); this.paths.Add(path.Key, path.Value);
} }
/// <summary> /// <summary>Create appropriate directories for the path.</summary>
/// Create appropriate directories for the path.
/// </summary>
private void createDirectoriesFromPaths() private void createDirectoriesFromPaths()
{ {
foreach(var v in paths) foreach (var v in this.paths)
{ Directory.CreateDirectory(Path.Combine(Class1.ModHelper.DirectoryPath, v.Value));
Directory.CreateDirectory(Path.Combine(Class1.ModHelper.DirectoryPath,v.Value));
}
} }
/// <summary> /// <summary>Get a list of assets which match the given critera.</summary>
/// Returns a list of assets from this manager that match the given critera. /// <param name="gender">The gender to match.</param>
/// </summary>
/// <param name="gender">The criteria we are searching for this time is gender.</param>
/// <returns></returns>
public List<AssetSheet> getListOfAssetsThatMatchThisCriteria(Genders gender) public List<AssetSheet> getListOfAssetsThatMatchThisCriteria(Genders gender)
{ {
List<AssetSheet> aSheet = new List<AssetSheet>(); List<AssetSheet> sheets = new List<AssetSheet>();
foreach(var v in this.assets) foreach (var v in this.assets)
{ {
if(v.assetInfo is ExtendedAssetInfo) if (v.assetInfo is ExtendedAssetInfo info)
{ {
if ((v.assetInfo as ExtendedAssetInfo).gender == gender) aSheet.Add(v); if (info.gender == gender)
sheets.Add(v);
} }
} }
return aSheet; return sheets;
} }
/// <summary> /// <summary>Get a list of assets which match the given critera.</summary>
/// Get a list of all the assets of this kind of part. /// <param name="type">The part type to match.</param>
/// </summary>
/// <param name="type">The type of part to return a list of from this asset manager.</param>
/// <returns></returns>
public List<AssetSheet> getListOfAssetsThatMatchThisCriteria(PartType type) public List<AssetSheet> getListOfAssetsThatMatchThisCriteria(PartType type)
{ {
List<AssetSheet> aSheet = new List<AssetSheet>(); List<AssetSheet> sheets = new List<AssetSheet>();
foreach (var v in this.assets) foreach (var v in this.assets)
{ {
if (v.assetInfo is ExtendedAssetInfo) if (v.assetInfo is ExtendedAssetInfo info)
{ {
if ((v.assetInfo as ExtendedAssetInfo).type == type) aSheet.Add(v); if (info.type == type)
sheets.Add(v);
} }
} }
return aSheet; return sheets;
} }
/// <summary> /// <summary>Get a list of assets which match the given critera.</summary>
/// Get a list of assets that match the critera. /// <param name="gender">The gender to match.</param>
/// </summary> /// <param name="type">The part type to match.</param>
/// <param name="gender">The gender criteria for this asset, such as if this part belongs to either a female or male character.</param> public List<AssetSheet> getListOfAssetsThatMatchThisCriteria(Genders gender, PartType type)
/// <param name="type">The type of asset to return. Hair eyes, shoes, etc.</param>
/// <returns></returns>
public List<AssetSheet> getListOfAssetsThatMatchThisCriteria(Genders gender,PartType type)
{ {
List<AssetSheet> aSheet = new List<AssetSheet>(); List<AssetSheet> sheets = new List<AssetSheet>();
foreach (var v in this.assets) foreach (var v in this.assets)
{ {
if (v.assetInfo is ExtendedAssetInfo) if (v.assetInfo is ExtendedAssetInfo info)
{ {
if ((v.assetInfo as ExtendedAssetInfo).type == type && (v.assetInfo as ExtendedAssetInfo).gender == gender) aSheet.Add(v); if (info.type == type && info.gender == gender)
sheets.Add(v);
} }
} }
return aSheet; return sheets;
} }
/// <summary> /// <summary>Get a list of assets which match the given critera.</summary>
/// Returns a list of assets from this manager that match the given critera. /// <param name="season">The season to match.</param>
/// </summary>
/// <param name="gender">The criteria we are searching for this time is gender.</param>
/// <returns></returns>
public List<AssetSheet> getListOfAssetsThatMatchThisCriteria(Seasons season) public List<AssetSheet> getListOfAssetsThatMatchThisCriteria(Seasons season)
{ {
List<AssetSheet> aSheet = new List<AssetSheet>(); List<AssetSheet> sheets = new List<AssetSheet>();
foreach (var v in this.assets) foreach (var v in this.assets)
{ {
if (v.assetInfo is ExtendedAssetInfo) if (v.assetInfo is ExtendedAssetInfo info)
{ {
foreach (var sea in (v.assetInfo as ExtendedAssetInfo).seasons) { foreach (var sea in info.seasons)
if (sea == season) aSheet.Add(v); {
if (sea == season)
sheets.Add(v);
break; //Only need to find first validation that this is a valid asset. break; //Only need to find first validation that this is a valid asset.
} }
} }
} }
return aSheet; return sheets;
} }
/// <summary> /// <summary>Get a list of assets which match the given critera.</summary>
/// Get a list of assets that match this criteria of gender and seasons. /// <param name="gender">The gender to match.</param>
/// </summary> /// <param name="season">The season to match.</param>
/// <param name="gender"></param> public List<AssetSheet> getListOfAssetsThatMatchThisCriteria(Genders gender, Seasons season)
/// <param name="season"></param>
/// <returns></returns>
public List<AssetSheet> getListOfAssetsThatMatchThisCriteria(Genders gender,Seasons season)
{ {
List<AssetSheet> aSheet = new List<AssetSheet>(); List<AssetSheet> sheets = new List<AssetSheet>();
foreach (var v in this.assets) foreach (var v in this.assets)
{ {
if (v.assetInfo is ExtendedAssetInfo) if (v.assetInfo is ExtendedAssetInfo info)
{ {
foreach (var sea in (v.assetInfo as ExtendedAssetInfo).seasons) foreach (var sea in info.seasons)
{ {
if (sea == season && (v.assetInfo as ExtendedAssetInfo).gender==gender) aSheet.Add(v); if (sea == season && info.gender == gender)
sheets.Add(v);
break; //Only need to find first validation that this is a valid asset. break; //Only need to find first validation that this is a valid asset.
} }
} }
} }
return aSheet; return sheets;
} }
/// <summary> /// <summary>Get a list of assets which match the given critera.</summary>
/// Get a list of asssets that match certain critera. /// <param name="gender">The gender to match.</param>
/// </summary> /// <param name="season">The season to match.</param>
/// <param name="gender">The gengder certain assets belong to, such as male or female.</param> /// <param name="type">The part type to match.</param>
/// <param name="season">The season that an asset can be displayed in. Good for seasonal assets.</param>
/// <param name="type">The type of part to return a list of such as hair, eyes, or pants.</param>
/// <returns></returns>
public List<AssetSheet> getListOfAssetsThatMatchThisCriteria(Genders gender, Seasons season, PartType type) public List<AssetSheet> getListOfAssetsThatMatchThisCriteria(Genders gender, Seasons season, PartType type)
{ {
List<AssetSheet> aSheet = new List<AssetSheet>(); List<AssetSheet> sheets = new List<AssetSheet>();
foreach (var v in this.assets) foreach (var v in this.assets)
{ {
if (v.assetInfo is ExtendedAssetInfo) if (v.assetInfo is ExtendedAssetInfo info)
{ {
foreach (var sea in (v.assetInfo as ExtendedAssetInfo).seasons) foreach (var sea in info.seasons)
{ {
//Class1.ModMonitor.Log("Searching: seasons"); if (sea == season && info.gender == gender && info.type == type)
if (sea == season && (v.assetInfo as ExtendedAssetInfo).gender == gender && (v.assetInfo as ExtendedAssetInfo).type == type) sheets.Add(v);
{
aSheet.Add(v);
}
else
{
//Class1.ModMonitor.Log("Not what I was looking for.");
} }
} }
} }
return sheets;
} }
//Class1.ModMonitor.Log("ok it's over: "+aSheet.Count.ToString());
return aSheet;
}
} }
} }

View File

@ -1,32 +1,26 @@

using CustomNPCFramework.Framework.Enums;
using CustomNPCFramework.Framework.ModularNPCS;
using CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases;
using CustomNPCFramework.Framework.ModularNPCS.ColorCollections;
using CustomNPCFramework.Framework.ModularNPCS.ModularRenderers;
using CustomNPCFramework.Framework.NPCS;
using Microsoft.Xna.Framework;
using StardewValley;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using CustomNPCFramework.Framework.Enums;
using System.Threading.Tasks; using CustomNPCFramework.Framework.ModularNpcs;
using CustomNPCFramework.Framework.ModularNpcs.CharacterAnimationBases;
using CustomNPCFramework.Framework.ModularNpcs.ColorCollections;
using CustomNPCFramework.Framework.ModularNpcs.ModularRenderers;
using CustomNPCFramework.Framework.NPCS;
using StardewValley;
namespace CustomNPCFramework.Framework.Graphics namespace CustomNPCFramework.Framework.Graphics
{ {
/// <summary>Used to hold a collection of strings.</summary>
/// <summary>
/// Used to hold a collection of strings.
/// </summary>
public class NamePairings public class NamePairings
{ {
public string leftString; public string leftString;
public string rightString; public string rightString;
public string upString; public string upString;
public string downString; public string downString;
public NamePairings(string LeftString,string RightString, string UpString, string DownString)
public NamePairings(string LeftString, string RightString, string UpString, string DownString)
{ {
this.leftString = LeftString; this.leftString = LeftString;
this.rightString = RightString; this.rightString = RightString;
@ -35,37 +29,26 @@ namespace CustomNPCFramework.Framework.Graphics
} }
} }
/// <summary> /// <summary>Used to contain all of the asset managers.</summary>
/// Used to contain all of the asset managers.
/// </summary>
public class AssetPool public class AssetPool
{ {
/// <summary>A dictionary holding all of the asset managers. (Name, AssetManager)</summary>
/// <summary>
/// A dictionary holding all of the asset managers. (Name, AssetManager)
/// </summary>
public Dictionary<string, AssetManager> assetPool; public Dictionary<string, AssetManager> assetPool;
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor.
/// </summary>
public AssetPool() public AssetPool()
{ {
this.assetPool = new Dictionary<string, AssetManager>(); this.assetPool = new Dictionary<string, AssetManager>();
} }
/// <summary> /// <summary>Adds an asset manager to the asset pool.</summary>
/// Adds an asset manager to the asset pool.
/// </summary>
/// <param name="pair">A key value pair with the convention being (Manager Name, Asset Manager)</param> /// <param name="pair">A key value pair with the convention being (Manager Name, Asset Manager)</param>
public void addAssetManager(KeyValuePair<string, AssetManager> pair) public void addAssetManager(KeyValuePair<string, AssetManager> pair)
{ {
this.assetPool.Add(pair.Key, pair.Value); this.assetPool.Add(pair.Key, pair.Value);
} }
/// <summary> /// <summary>Adds an asset manager to the asset pool.</summary>
/// Adds an asset manager to the asset pool.
/// </summary>
/// <param name="assetManagerName">The name of the asset manager to be added.</param> /// <param name="assetManagerName">The name of the asset manager to be added.</param>
/// <param name="assetManager">The asset manager object to be added to the asset pool.</param> /// <param name="assetManager">The asset manager object to be added to the asset pool.</param>
public void addAssetManager(string assetManagerName, AssetManager assetManager) public void addAssetManager(string assetManagerName, AssetManager assetManager)
@ -73,99 +56,74 @@ namespace CustomNPCFramework.Framework.Graphics
this.assetPool.Add(assetManagerName, assetManager); this.assetPool.Add(assetManagerName, assetManager);
} }
/// <summary> /// <summary>Get an asset manager from the asset pool from a name.</summary>
/// Get an asset manager from the asset pool from a name.
/// </summary>
/// <param name="name">The name of the asset manager to return.</param> /// <param name="name">The name of the asset manager to return.</param>
/// <returns></returns>
public AssetManager getAssetManager(string name) public AssetManager getAssetManager(string name)
{ {
assetPool.TryGetValue(name, out AssetManager asset); this.assetPool.TryGetValue(name, out AssetManager asset);
return asset; return asset;
} }
/// <summary> /// <summary>Remove an asset manager from the asset pool.</summary>
/// Remove an asset manager from the asset pool.
/// </summary>
/// <param name="key">The name of the asset manager to remove.</param> /// <param name="key">The name of the asset manager to remove.</param>
public void removeAssetManager(string key) public void removeAssetManager(string key)
{ {
assetPool.Remove(key); this.assetPool.Remove(key);
} }
/// <summary> /// <summary>Go through all of the asset managers and load assets according to their respective paths.</summary>
/// Go through all of the asset managers and load assets according to their respective paths.
/// </summary>
public void loadAllAssets() public void loadAllAssets()
{ {
foreach (KeyValuePair<string, AssetManager> assetManager in this.assetPool) foreach (KeyValuePair<string, AssetManager> assetManager in this.assetPool)
{
assetManager.Value.loadAssets(); assetManager.Value.loadAssets();
} }
}
/// <summary> /// <summary>Creates an extended animated sprite object given the asset name in the asset manager.</summary>
/// Creates an extended animated sprite object given the asset name in the asset manager. /// <param name="name">The asset name.</param>
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public AnimatedSpriteExtended getAnimatedSpriteFromAsset(string name) public AnimatedSpriteExtended getAnimatedSpriteFromAsset(string name)
{ {
assetPool.TryGetValue(name, out AssetManager asset); this.assetPool.TryGetValue(name, out AssetManager asset);
var assetSheet = asset.getAssetByName(name); var assetSheet = asset.getAssetByName(name);
return new AnimatedSpriteExtended(assetSheet.path.Clone().ToString(),assetSheet.index, (int)assetSheet.assetInfo.assetSize.X, (int)assetSheet.assetInfo.assetSize.Y); return new AnimatedSpriteExtended(assetSheet.path.Clone().ToString(), assetSheet.index, (int)assetSheet.assetInfo.assetSize.X, (int)assetSheet.assetInfo.assetSize.Y);
} }
/// <summary>Generates a new AnimatedSpriteCollection object from the data held in an asset sheet.</summary>
/// <summary>
/// Generates a new AnimatedSpriteCollection object from the data held in an asset sheet.
/// </summary>
/// <param name="assetSheet">An asset sheet that holds the data for textures.</param> /// <param name="assetSheet">An asset sheet that holds the data for textures.</param>
/// <param name="type">The type of asset to get from the sheet. Hair, eyes, shoes, etc.</param> /// <param name="type">The type of asset to get from the sheet. Hair, eyes, shoes, etc.</param>
/// <returns></returns>
public AnimatedSpriteCollection getSpriteCollectionFromSheet(AssetSheet assetSheet, AnimationType type) public AnimatedSpriteCollection getSpriteCollectionFromSheet(AssetSheet assetSheet, AnimationType type)
{ {
var left = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.left, type),assetSheet); var left = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.left, type), assetSheet);
var right = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.right, type), assetSheet); var right = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.right, type), assetSheet);
var up = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.up, type), assetSheet); var up = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.up, type), assetSheet);
var down = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.down, type), assetSheet); var down = new AnimatedSpriteExtended(assetSheet.clone().getTexture(Direction.down, type), assetSheet);
return new AnimatedSpriteCollection(left, right, up, down, Direction.down); return new AnimatedSpriteCollection(left, right, up, down, Direction.down);
} }
/// <summary>Gets an animated sprite collection (ie a hair style facing all four directions) from a list of asset names.</summary>
/// <summary>
/// Gets an animated sprite collection (ie a hair style facing all four directions) from a list of asset names.
/// </summary>
/// <param name="left">The name of the asset for the left facing sprite.</param> /// <param name="left">The name of the asset for the left facing sprite.</param>
/// <param name="right">The name of the asset for the right facing sprite.</param> /// <param name="right">The name of the asset for the right facing sprite.</param>
/// <param name="up">The name of the asset for the up facing sprite.</param> /// <param name="up">The name of the asset for the up facing sprite.</param>
/// <param name="down">The name of the asset for the down facing sprite.</param> /// <param name="down">The name of the asset for the down facing sprite.</param>
/// <param name="startingDirection"></param> /// <param name="startingDirection">The sprite's starting direction.</param>
/// <returns></returns>
public AnimatedSpriteCollection getAnimatedSpriteCollectionFromAssets(string left, string right, string up, string down, Direction startingDirection = Direction.down) public AnimatedSpriteCollection getAnimatedSpriteCollectionFromAssets(string left, string right, string up, string down, Direction startingDirection = Direction.down)
{ {
var Left = getAnimatedSpriteFromAsset(left); var leftSprite = this.getAnimatedSpriteFromAsset(left);
var Right = getAnimatedSpriteFromAsset(right); var rightSprite = this.getAnimatedSpriteFromAsset(right);
var Up = getAnimatedSpriteFromAsset(up); var upSprite = this.getAnimatedSpriteFromAsset(up);
var Down = getAnimatedSpriteFromAsset(down); var downSprite = this.getAnimatedSpriteFromAsset(down);
return new AnimatedSpriteCollection(Left, Right, Up, Down, startingDirection); return new AnimatedSpriteCollection(leftSprite, rightSprite, upSprite, downSprite, startingDirection);
} }
/// <summary> /// <summary>Get an AnimatedSpriteCollection from a name pairing.</summary>
/// Get an AnimatedSpriteCollection from a name pairing.
/// </summary>
/// <param name="pair">A collection of strings that hold information on directional textures.</param> /// <param name="pair">A collection of strings that hold information on directional textures.</param>
/// <param name="startingDirection">The direction in which the sprite should face.</param> /// <param name="startingDirection">The direction in which the sprite should face.</param>
/// <returns></returns>
public AnimatedSpriteCollection getAnimatedSpriteCollectionFromAssets(NamePairings pair, Direction startingDirection = Direction.down) public AnimatedSpriteCollection getAnimatedSpriteCollectionFromAssets(NamePairings pair, Direction startingDirection = Direction.down)
{ {
return getAnimatedSpriteCollectionFromAssets(pair.leftString, pair.rightString, pair.upString, pair.downString); return this.getAnimatedSpriteCollectionFromAssets(pair.leftString, pair.rightString, pair.upString, pair.downString);
} }
/// <summary> /// <summary>Get a collection of sprites to generate a collective animated sprite.</summary>
/// Get a collection of sprites to generate a collective animated sprite.
/// </summary>
/// <param name="BodySprites">The collection of sprites to be used for the boyd of the npc.</param> /// <param name="BodySprites">The collection of sprites to be used for the boyd of the npc.</param>
/// <param name="EyeSprites">The collection of sprites to be used for the eye of the npc.</param> /// <param name="EyeSprites">The collection of sprites to be used for the eye of the npc.</param>
/// <param name="HairSprites">The collection of sprites to be used for the hair of the npc.</param> /// <param name="HairSprites">The collection of sprites to be used for the hair of the npc.</param>
@ -174,48 +132,44 @@ namespace CustomNPCFramework.Framework.Graphics
/// <param name="ShoesSprites">The collection of sprites to be used for the shoes of the npc.</param> /// <param name="ShoesSprites">The collection of sprites to be used for the shoes of the npc.</param>
/// <param name="AccessoriesSprites">The collection of sprites to be used for the accessories of the npc.</param> /// <param name="AccessoriesSprites">The collection of sprites to be used for the accessories of the npc.</param>
/// <param name="DrawColors">The collection of collors to be used for chaing the color of an individual asset.</param> /// <param name="DrawColors">The collection of collors to be used for chaing the color of an individual asset.</param>
/// <returns></returns> public StandardCharacterAnimation GetStandardCharacterAnimation(NamePairings BodySprites, NamePairings EyeSprites, NamePairings HairSprites, NamePairings ShirtsSprites, NamePairings PantsSprites, NamePairings ShoesSprites, List<NamePairings> AccessoriesSprites, StandardColorCollection DrawColors = null)
public StandardCharacterAnimation GetStandardCharacterAnimation(NamePairings BodySprites, NamePairings EyeSprites, NamePairings HairSprites, NamePairings ShirtsSprites, NamePairings PantsSprites, NamePairings ShoesSprites,List<NamePairings> AccessoriesSprites,StandardColorCollection DrawColors=null)
{ {
var body = getAnimatedSpriteCollectionFromAssets(BodySprites); var body = this.getAnimatedSpriteCollectionFromAssets(BodySprites);
var eyes = getAnimatedSpriteCollectionFromAssets(EyeSprites); var eyes = this.getAnimatedSpriteCollectionFromAssets(EyeSprites);
var hair = getAnimatedSpriteCollectionFromAssets(HairSprites); var hair = this.getAnimatedSpriteCollectionFromAssets(HairSprites);
var shirts = getAnimatedSpriteCollectionFromAssets(ShirtsSprites); var shirts = this.getAnimatedSpriteCollectionFromAssets(ShirtsSprites);
var pants = getAnimatedSpriteCollectionFromAssets(PantsSprites); var pants = this.getAnimatedSpriteCollectionFromAssets(PantsSprites);
var shoes = getAnimatedSpriteCollectionFromAssets(ShoesSprites); var shoes = this.getAnimatedSpriteCollectionFromAssets(ShoesSprites);
List<AnimatedSpriteCollection> accessories = new List<AnimatedSpriteCollection>(); List<AnimatedSpriteCollection> accessories = new List<AnimatedSpriteCollection>();
foreach(var v in AccessoriesSprites) foreach (var v in AccessoriesSprites)
{ accessories.Add(this.getAnimatedSpriteCollectionFromAssets(v));
accessories.Add(getAnimatedSpriteCollectionFromAssets(v));
} if (DrawColors == null)
if (DrawColors == null) DrawColors = new StandardColorCollection(); DrawColors = new StandardColorCollection();
return new StandardCharacterAnimation(body,eyes,hair,shirts,pants,shoes,accessories,DrawColors);
return new StandardCharacterAnimation(body, eyes, hair, shirts, pants, shoes, accessories, DrawColors);
} }
/// <summary> /// <summary>Get a list of parts that can apply for this criteria.</summary>
/// Get a list of parts that can apply for this criteria.
/// </summary>
/// <param name="assetManagerName">The name of the asset manager.</param> /// <param name="assetManagerName">The name of the asset manager.</param>
/// <param name="gender">The gender critera.</param> /// <param name="gender">The gender critera.</param>
/// <param name="season">The season critera.</param> /// <param name="season">The season critera.</param>
/// <param name="type">The part type critera.</param> /// <param name="type">The part type critera.</param>
/// <returns></returns> public List<AssetSheet> getListOfApplicableBodyParts(string assetManagerName, Genders gender, Seasons season, PartType type)
public List<AssetSheet> getListOfApplicableBodyParts(string assetManagerName,Genders gender, Seasons season, PartType type)
{ {
var parts = this.getAssetManager(assetManagerName).getListOfAssetsThatMatchThisCriteria(gender, season, type); var parts = this.getAssetManager(assetManagerName).getListOfAssetsThatMatchThisCriteria(gender, season, type);
return parts; return parts;
} }
/// <summary>Generate a basic NPC based on the NPC data here.</summary>
/// <summary> /// <param name="gender">The NPC gender.</param>
/// Generate a basic npc based off of all all of the NPC data here. /// <param name="minNumOfAccessories">The minimum number of accessories to generate.</param>
/// </summary> /// <param name="maxNumOfAccessories">The maximum number of accessories to generate.</param>
/// <param name="gender"></param> /// <param name="drawColors">The colors for the NPC's different assets.</param>
/// <param name="minNumOfAccessories"></param> public ExtendedNpc generateNPC(Genders gender, int minNumOfAccessories, int maxNumOfAccessories, StandardColorCollection drawColors = null)
/// <param name="maxNumOfAccessories"></param>
public ExtendedNPC generateNPC(Genders gender, int minNumOfAccessories, int maxNumOfAccessories ,StandardColorCollection DrawColors=null)
{ {
Seasons myseason=Seasons.spring; Seasons myseason = Seasons.spring;
if (Game1.currentSeason == "spring") myseason = Seasons.spring; if (Game1.currentSeason == "spring") myseason = Seasons.spring;
if (Game1.currentSeason == "summer") myseason = Seasons.summer; if (Game1.currentSeason == "summer") myseason = Seasons.summer;
@ -233,95 +187,87 @@ namespace CustomNPCFramework.Framework.Graphics
//Get all applicable parts from this current asset manager //Get all applicable parts from this current asset manager
foreach (var assetManager in this.assetPool) foreach (var assetManager in this.assetPool)
{ {
var body = getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.body); var body = this.getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.body);
foreach (var piece in body) bodyList.Add(piece); foreach (var piece in body) bodyList.Add(piece);
var eyes = getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.eyes); var eyes = this.getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.eyes);
foreach (var piece in eyes) eyesList.Add(piece); foreach (var piece in eyes) eyesList.Add(piece);
var hair = getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.hair); var hair = this.getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.hair);
foreach (var piece in hair) hairList.Add(piece); foreach (var piece in hair) hairList.Add(piece);
var shirt = getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.shirt); var shirt = this.getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.shirt);
foreach (var piece in shirt) shirtList.Add(piece); foreach (var piece in shirt) shirtList.Add(piece);
var pants = getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.pants); var pants = this.getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.pants);
foreach (var piece in pants) pantsList.Add(piece); foreach (var piece in pants) pantsList.Add(piece);
var shoes = getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.shoes); var shoes = this.getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.shoes);
foreach (var piece in shoes) shoesList.Add(piece); foreach (var piece in shoes) shoesList.Add(piece);
var accessory = getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.accessory); var accessory = this.getListOfApplicableBodyParts(assetManager.Key, gender, myseason, PartType.accessory);
foreach (var piece in accessory) accessoryList.Add(piece); foreach (var piece in accessory) accessoryList.Add(piece);
} }
Random r = new Random(System.DateTime.Now.Millisecond); Random r = new Random(DateTime.Now.Millisecond);
int amount = 0; int amount = r.Next(minNumOfAccessories, maxNumOfAccessories + 1);
amount = r.Next(minNumOfAccessories,maxNumOfAccessories + 1); //Necessary since r.next returns a num between min and (max-1) int bodyIndex;
int eyesIndex;
int hairIndex;
int shirtIndex;
int pantsIndex;
int shoesIndex;
int bodyIndex = 0; if (bodyList.Count != 0)
int eyesIndex = 0;
int hairIndex = 0;
int shirtIndex = 0;
int pantsIndex = 0;
int shoesIndex = 0;
if (bodyList.Count != 0) {
bodyIndex = r.Next(0, bodyList.Count - 1); bodyIndex = r.Next(0, bodyList.Count - 1);
}
else else
{ {
Class1.ModMonitor.Log("Error: Not enough body templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error); Class1.ModMonitor.Log("Error: Not enough body templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error);
return null; return null;
} }
if (eyesList.Count != 0) { if (eyesList.Count != 0)
eyesIndex = r.Next(0, eyesList.Count - 1); eyesIndex = r.Next(0, eyesList.Count - 1);
}
else else
{ {
Class1.ModMonitor.Log("Error: Not enough eyes templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error); Class1.ModMonitor.Log("Error: Not enough eyes templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error);
return null; return null;
} }
if (hairList.Count != 0) { if (hairList.Count != 0)
hairIndex = r.Next(0, hairList.Count - 1); hairIndex = r.Next(0, hairList.Count - 1);
}
else else
{ {
Class1.ModMonitor.Log("Error: Not enough hair templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error); Class1.ModMonitor.Log("Error: Not enough hair templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error);
return null; return null;
} }
if (shirtList.Count != 0) { if (shirtList.Count != 0)
shirtIndex = r.Next(0, shirtList.Count - 1); shirtIndex = r.Next(0, shirtList.Count - 1);
}
else else
{ {
Class1.ModMonitor.Log("Error: Not enough shirt templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error); Class1.ModMonitor.Log("Error: Not enough shirt templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error);
return null; return null;
} }
if (pantsList.Count != 0) { if (pantsList.Count != 0)
pantsIndex = r.Next(0, pantsList.Count - 1); pantsIndex = r.Next(0, pantsList.Count - 1);
}
else else
{ {
Class1.ModMonitor.Log("Error: Not enough pants templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error); Class1.ModMonitor.Log("Error: Not enough pants templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error);
return null; return null;
} }
if (shoesList.Count != 0) { if (shoesList.Count != 0)
shoesIndex = r.Next(0, shoesList.Count - 1); shoesIndex = r.Next(0, shoesList.Count - 1);
}
else else
{ {
Class1.ModMonitor.Log("Error: Not enough shoes templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error); Class1.ModMonitor.Log("Error: Not enough shoes templates to generate an npc. Aborting", StardewModdingAPI.LogLevel.Error);
return null; return null;
} }
List<int> accIntList = new List<int>(); List<int> accIntList = new List<int>();
if (accessoryList.Count != 0) if (accessoryList.Count != 0)
{ {
@ -333,97 +279,80 @@ namespace CustomNPCFramework.Framework.Graphics
} }
//Get a single sheet to pull from. //Get a single sheet to pull from.
AssetSheet bodySheet; AssetSheet bodySheet = bodyList.ElementAt(bodyIndex);
AssetSheet eyesSheet; AssetSheet eyesSheet = eyesList.ElementAt(eyesIndex);
AssetSheet hairSheet; AssetSheet hairSheet = hairList.ElementAt(hairIndex);
AssetSheet shirtSheet; AssetSheet shirtSheet = shirtList.ElementAt(shirtIndex);
AssetSheet shoesSheet; AssetSheet pantsSheet = pantsList.ElementAt(pantsIndex);
AssetSheet pantsSheet; AssetSheet shoesSheet = shoesList.ElementAt(shoesIndex);
bodySheet = bodyList.ElementAt(bodyIndex);
eyesSheet = eyesList.ElementAt(eyesIndex);
hairSheet = hairList.ElementAt(hairIndex);
shirtSheet = shirtList.ElementAt(shirtIndex);
pantsSheet = pantsList.ElementAt(pantsIndex);
shoesSheet = shoesList.ElementAt(shoesIndex);
List<AssetSheet> accessorySheet = new List<AssetSheet>(); List<AssetSheet> accessorySheet = new List<AssetSheet>();
foreach (int v in accIntList)
foreach (var v in accIntList)
{
accessorySheet.Add(accessoryList.ElementAt(v)); accessorySheet.Add(accessoryList.ElementAt(v));
}
if (DrawColors == null) DrawColors = new StandardColorCollection(); if (drawColors == null)
var render = generateBasicRenderer(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet,DrawColors); drawColors = new StandardColorCollection();
ExtendedNPC npc = new ExtendedNPC(new Sprite(getDefaultSpriteImage(bodySheet)), render, new Microsoft.Xna.Framework.Vector2(0,0) * Game1.tileSize, 2, NPCNames.getRandomNPCName(gender));
return npc; var render = this.generateBasicRenderer(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet, drawColors);
return new ExtendedNpc(new Sprite(this.getDefaultSpriteImage(bodySheet)), render, new Microsoft.Xna.Framework.Vector2(0, 0) * Game1.tileSize, 2, NpcNames.getRandomNpcName(gender));
} }
/// <summary> /// <summary>Creates a character renderer (a collection of textures) from a bunch of different asset sheets.</summary>
/// Creates a character renderer (a collection of textures) from a bunch of different asset sheets. /// <param name="bodySheet">The textures for the NPC's body.</param>
/// </summary> /// <param name="eyesSheet">The textures for the NPC's eyes.</param>
/// <param name="bodySheet">The textures for the npc's body.</param> /// <param name="hairSheet">The textures for the NPC's hair.</param>
/// <param name="eyesSheet">The textures for the npc's eyes.</param> /// <param name="shirtSheet">The textures for the NPC's shirt.</param>
/// <param name="hairSheet">The textures for the npc's hair.</param> /// <param name="pantsSheet">The textures for the NPC's pants.</param>
/// <param name="shirtSheet">The textures for the npc's shirt.</param> /// <param name="shoesSheet">The textures for the NPC's shoes.</param>
/// <param name="pantsSheet">The textures for the npc's pants.</param> /// <param name="accessorySheet">The textures for the NPC's accessories.</param>
/// <param name="shoesSheet">The textures for the npc's shoes.</param> /// <param name="drawColors">The colors for the NPC's different assets.</param>
/// <param name="accessorySheet">The textures for the npc's accessories.</param> public virtual BasicRenderer generateBasicRenderer(AssetSheet bodySheet, AssetSheet eyesSheet, AssetSheet hairSheet, AssetSheet shirtSheet, AssetSheet pantsSheet, AssetSheet shoesSheet, List<AssetSheet> accessorySheet, StandardColorCollection drawColors = null)
/// <param name="DrawColors">The colors for the npc's different assets.</param>
/// <returns></returns>
public virtual BasicRenderer generateBasicRenderer(AssetSheet bodySheet, AssetSheet eyesSheet, AssetSheet hairSheet, AssetSheet shirtSheet, AssetSheet pantsSheet, AssetSheet shoesSheet, List<AssetSheet> accessorySheet, StandardColorCollection DrawColors=null)
{ {
if (DrawColors == null) DrawColors = new StandardColorCollection(); if (drawColors == null)
//Get all of the appropriate animations. drawColors = new StandardColorCollection();
AnimationType type = AnimationType.standing;
var standingAnimation = generateCharacterAnimation(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet, type,DrawColors);
type = AnimationType.walking;
var movingAnimation = generateCharacterAnimation(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet, type,DrawColors);
type = AnimationType.swimming;
var swimmingAnimation = generateCharacterAnimation(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet, type,DrawColors);
BasicRenderer render = new BasicRenderer(standingAnimation, movingAnimation, swimmingAnimation); // Get all of the appropriate animations.
return render; StandardCharacterAnimation standingAnimation = this.generateCharacterAnimation(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet, AnimationType.standing, drawColors);
StandardCharacterAnimation movingAnimation = this.generateCharacterAnimation(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet, AnimationType.walking, drawColors);
StandardCharacterAnimation swimmingAnimation = this.generateCharacterAnimation(bodySheet, eyesSheet, hairSheet, shirtSheet, pantsSheet, shoesSheet, accessorySheet, AnimationType.swimming, drawColors);
return new BasicRenderer(standingAnimation, movingAnimation, swimmingAnimation);
} }
/// <summary> /// <summary>Generate a Standard Character Animation from some asset sheets. (collection of textures to animations)</summary>
/// Generate a Standard Character Animation from some asset sheets. /// <param name="body">The textures for the NPC's body.</param>
/// (collection of textures to animations) /// <param name="eyes">The textures for the NPC's eyes.</param>
/// </summary> /// <param name="hair">The textures for the NPC's hair.</param>
/// <param name="body">The textures for the npc's body.</param> /// <param name="shirt">The textures for the NPC's shirt.</param>
/// <param name="eyes">The textures for the npc's eyes.</param> /// <param name="pants">The textures for the NPC's pants.</param>
/// <param name="hair">The textures for the npc's hair.</param> /// <param name="shoes">The textures for the NPC's shoes.</param>
/// <param name="shirt">The textures for the npc's shirt.</param> /// <param name="accessories">The textures for the NPC's accessories.</param>
/// <param name="pants">The textures for the npc's pants.</param> /// <param name="animationType">The animation type to generate.</param>
/// <param name="shoes">The textures for the npc's shoes.</param> /// <param name="drawColors">The colors for the NPC's different assets.</param>
/// <param name="accessoryType">The textures for the npc's accessories.</param> public virtual StandardCharacterAnimation generateCharacterAnimation(AssetSheet body, AssetSheet eyes, AssetSheet hair, AssetSheet shirt, AssetSheet pants, AssetSheet shoes, List<AssetSheet> accessories, AnimationType animationType, StandardColorCollection drawColors = null)
/// <param name="DrawColors">The colors for the npc's different assets.</param>
/// <returns></returns>
public virtual StandardCharacterAnimation generateCharacterAnimation(AssetSheet body, AssetSheet eyes, AssetSheet hair, AssetSheet shirt, AssetSheet pants, AssetSheet shoes,List<AssetSheet> accessories, AnimationType animationType, StandardColorCollection DrawColors=null)
{ {
var bodySprite = getSpriteCollectionFromSheet(body, animationType); AnimatedSpriteCollection bodySprite = this.getSpriteCollectionFromSheet(body, animationType);
var eyesSprite = getSpriteCollectionFromSheet(eyes, animationType); AnimatedSpriteCollection eyesSprite = this.getSpriteCollectionFromSheet(eyes, animationType);
var hairSprite = getSpriteCollectionFromSheet(hair, animationType); AnimatedSpriteCollection hairSprite = this.getSpriteCollectionFromSheet(hair, animationType);
var shirtSprite = getSpriteCollectionFromSheet(shirt, animationType); AnimatedSpriteCollection shirtSprite = this.getSpriteCollectionFromSheet(shirt, animationType);
var pantsSprite = getSpriteCollectionFromSheet(pants, animationType); AnimatedSpriteCollection pantsSprite = this.getSpriteCollectionFromSheet(pants, animationType);
var shoesSprite = getSpriteCollectionFromSheet(shoes, animationType); AnimatedSpriteCollection shoesSprite = this.getSpriteCollectionFromSheet(shoes, animationType);
List<AnimatedSpriteCollection> accessoryCollection = new List<AnimatedSpriteCollection>(); List<AnimatedSpriteCollection> accessoryCollection = new List<AnimatedSpriteCollection>();
foreach (var v in accessories) foreach (var v in accessories)
{ {
AnimatedSpriteCollection acc = getSpriteCollectionFromSheet(v, AnimationType.standing); AnimatedSpriteCollection acc = this.getSpriteCollectionFromSheet(v, AnimationType.standing);
accessoryCollection.Add(acc); accessoryCollection.Add(acc);
} }
if (DrawColors == null) DrawColors = new StandardColorCollection();
StandardCharacterAnimation standingAnimation = new StandardCharacterAnimation(bodySprite, eyesSprite, hairSprite, shirtSprite, pantsSprite, shoesSprite, accessoryCollection,DrawColors); if (drawColors == null)
return standingAnimation; drawColors = new StandardColorCollection();
return new StandardCharacterAnimation(bodySprite, eyesSprite, hairSprite, shirtSprite, pantsSprite, shoesSprite, accessoryCollection, drawColors);
} }
/// <summary> /// <summary>Get the string for the standard character sprite to be used from this asset sheet.</summary>
/// Get the string for the standard character sprite to be used from this asset sheet.
/// </summary>
/// <param name="imageGraphics">The standard asset sheet to be used.</param> /// <param name="imageGraphics">The standard asset sheet to be used.</param>
/// <returns></returns>
public virtual string getDefaultSpriteImage(AssetSheet imageGraphics) public virtual string getDefaultSpriteImage(AssetSheet imageGraphics)
{ {
return Class1.getRelativeDirectory(Path.Combine(imageGraphics.path, imageGraphics.assetInfo.standingAssetPaths.downString)); return Class1.getRelativeDirectory(Path.Combine(imageGraphics.path, imageGraphics.assetInfo.standingAssetPaths.downString));

View File

@ -1,131 +1,95 @@
using CustomNPCFramework.Framework.Enums; using System.Collections.Generic;
using CustomNPCFramework.Framework.Enums;
using CustomNPCFramework.Framework.Graphics.TextureGroups; using CustomNPCFramework.Framework.Graphics.TextureGroups;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardustCore.UIUtilities; using StardustCore.UIUtilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.Graphics namespace CustomNPCFramework.Framework.Graphics
{ {
/// <summary> /// <summary>Used to handle loading different textures and handling opperations on those textures.</summary>
/// Used to handle loading different textures and handling opperations on those textures.
/// </summary>
public class AssetSheet public class AssetSheet
{ {
/// <summary> /// <summary>Used to hold the textures for the AssetSheet.</summary>
/// Used to hold the textures for the AssetSheet. public TextureGroup textures;
/// </summary>
public TextureGroups.TextureGroup textures;
/// <summary> /// <summary>Used to hold the info for the paths to these textures.</summary>
/// Used to hold the info for the paths to these textures.
/// </summary>
public AssetInfo assetInfo; public AssetInfo assetInfo;
/// <summary> /// <summary>The path to this assetinfo.json file</summary>
/// The path to this assetinfo.json file
/// </summary>
public string path; public string path;
/// <summary> /// <summary>The source rectangle for the current texture to draw.</summary>
/// The soruce rectangle for the current texture to draw.
/// </summary>
public Rectangle currentAsset; public Rectangle currentAsset;
public int index; public int index;
/// <summary>
/// Constructor. /// <summary>Construct an instance.</summary>
/// </summary>
/// <param name="info">The asset info file to be read in or created. Holds path information.</param> /// <param name="info">The asset info file to be read in or created. Holds path information.</param>
/// <param name="path">The path to the assetinfo file.</param> /// <param name="path">The path to the assetinfo file.</param>
/// <param name="direction">The direction to set the animation.</param> /// <param name="direction">The direction to set the animation.</param>
public AssetSheet(AssetInfo info,string path,Direction direction=Direction.down) public AssetSheet(AssetInfo info, string path, Direction direction = Direction.down)
{ {
this.assetInfo = info; this.assetInfo = info;
this.textures = new TextureGroup(info,path,direction); this.textures = new TextureGroup(info, path, direction);
try try
{ {
this.path = Class1.getShortenedDirectory(path); this.path = Class1.getShortenedDirectory(path);
} }
catch(Exception err) catch
{ {
this.path = path; this.path = path;
} }
this.index = 0; this.index = 0;
} }
/// <summary>
/// Get the path to the current texture. /// <summary>Get the path to the current texture.</summary>
/// </summary>
/// <returns></returns>
public virtual KeyValuePair<string, Texture2DExtended> getPathTexturePair() public virtual KeyValuePair<string, Texture2DExtended> getPathTexturePair()
{ {
return new KeyValuePair<string, Texture2DExtended>(this.path, this.textures.currentTexture.currentTexture); return new KeyValuePair<string, Texture2DExtended>(this.path, this.textures.currentTexture.currentTexture);
} }
/// <summary>Used just to get a copy of this asset sheet.</summary>
/// <summary>
/// Used just to get a copy of this asset sheet.
/// </summary>
public virtual AssetSheet clone() public virtual AssetSheet clone()
{ {
var asset = new AssetSheet(this.assetInfo,(string)this.path.Clone()); var asset = new AssetSheet(this.assetInfo, (string)this.path.Clone());
return asset; return asset;
} }
/// <summary> /// <summary>Sets the textures for this sheet to face left.</summary>
/// Sets the textures for this sheet to face left.
/// </summary>
public virtual void setLeft() public virtual void setLeft()
{ {
this.textures.setLeft(); this.textures.setLeft();
} }
/// <summary> /// <summary>Sets the textures for this sheet to face up.</summary>
/// Sets the textures for this sheet to face up.
/// </summary>
public virtual void setUp() public virtual void setUp()
{ {
this.textures.setUp(); this.textures.setUp();
} }
/// <summary> /// <summary>Sets the textures for this sheet to face down.</summary>
/// Sets the textures for this sheet to face down.
/// </summary>
public virtual void setDown() public virtual void setDown()
{ {
this.textures.setDown(); this.textures.setDown();
} }
/// <summary> /// <summary>Sets the textures for this sheet to face left.</summary>
/// Sets the textures for this sheet to face left.
/// </summary>
public virtual void setRight() public virtual void setRight()
{ {
this.textures.setRight(); this.textures.setRight();
} }
/// <summary> /// <summary>Get the current animation texture.</summary>
/// Get the current animation texture.
/// </summary>
/// <returns></returns>
public virtual Texture2DExtended getCurrentSpriteTexture() public virtual Texture2DExtended getCurrentSpriteTexture()
{ {
return this.textures.currentTexture.currentTexture; return this.textures.currentTexture.currentTexture;
} }
/// <summary> /// <summary>Get the specific texture depending on the direction and animation type.</summary>
/// Get the specific texture depending on the direction and animation type. /// <param name="direction">The facing direction.</param>
/// </summary> /// <param name="type">The animation type.</param>
/// <param name="direction"></param> public virtual Texture2DExtended getTexture(Direction direction, AnimationType type)
/// <param name="type"></param>
/// <returns></returns>
public virtual Texture2DExtended getTexture(Direction direction,AnimationType type)
{ {
return this.textures.getTextureFromAnimation(type).getTextureFromDirection(direction); return this.textures.getTextureFromAnimation(type).getTextureFromDirection(direction);
} }

View File

@ -1,134 +1,138 @@
using CustomNPCFramework.Framework.Enums; using System.IO;
using Microsoft.Xna.Framework.Graphics; using CustomNPCFramework.Framework.Enums;
using StardewModdingAPI; using StardewModdingAPI;
using StardustCore.UIUtilities; using StardustCore.UIUtilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.Graphics namespace CustomNPCFramework.Framework.Graphics
{ {
/// <summary> /// <summary>A class that's used to hold textures for different directions.</summary>
/// A class that's used to hold textures for different directions.
/// </summary>
public class DirectionalTexture public class DirectionalTexture
{ {
/// <summary> /// <summary>The left texture for this group.</summary>
/// The left texture for this group.
/// </summary>
public Texture2DExtended leftTexture; public Texture2DExtended leftTexture;
/// <summary>
/// The right texture for this group. /// <summary>The right texture for this group.</summary>
/// </summary>
public Texture2DExtended rightTexture; public Texture2DExtended rightTexture;
/// <summary> /// <summary>The down textiure for this group.</summary>
/// The down textiure for this group.
/// </summary>
public Texture2DExtended downTexture; public Texture2DExtended downTexture;
/// <summary>
/// The up texture for this group. /// <summary>The up texture for this group.</summary>
/// </summary>
public Texture2DExtended upTexture; public Texture2DExtended upTexture;
/// <summary> /// <summary>The current texture for this group.</summary>
/// The current texture for this group.
/// </summary>
public Texture2DExtended currentTexture; public Texture2DExtended currentTexture;
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor.
/// </summary>
/// <param name="left">The left texture to use.</param> /// <param name="left">The left texture to use.</param>
/// <param name="right">The right texture to use.</param> /// <param name="right">The right texture to use.</param>
/// <param name="up">The up texture to use.</param> /// <param name="up">The up texture to use.</param>
/// <param name="down">The down texture to use.</param> /// <param name="down">The down texture to use.</param>
/// <param name="direction">The direction texture for the sprite to face.</param> /// <param name="direction">The direction texture for the sprite to face.</param>
public DirectionalTexture(Texture2DExtended left, Texture2DExtended right, Texture2DExtended up, Texture2DExtended down, Direction direction=Direction.down) public DirectionalTexture(Texture2DExtended left, Texture2DExtended right, Texture2DExtended up, Texture2DExtended down, Direction direction = Direction.down)
{ {
this.leftTexture = left; this.leftTexture = left;
this.rightTexture = right; this.rightTexture = right;
this.upTexture = up; this.upTexture = up;
this.downTexture = down; this.downTexture = down;
if (direction == Direction.left) this.currentTexture = leftTexture; switch (direction)
if (direction == Direction.right) this.currentTexture = rightTexture; {
if (direction == Direction.up) this.currentTexture = upTexture; case Direction.left:
if (direction == Direction.down) this.currentTexture = downTexture; this.currentTexture = this.leftTexture;
break;
case Direction.right:
this.currentTexture = this.rightTexture;
break;
case Direction.up:
this.currentTexture = this.upTexture;
break;
case Direction.down:
this.currentTexture = this.downTexture;
break;
}
} }
public DirectionalTexture(IModHelper helper, NamePairings info, string path, Direction direction = Direction.down)
public DirectionalTexture(IModHelper helper ,NamePairings info, string path, Direction direction = Direction.down)
{ {
string leftString = Class1.getShortenedDirectory(Path.Combine(path, info.leftString + ".png")).Remove(0, 1);
new Texture2DExtended(helper, Class1.Manifest, path);
string leftString= Class1.getShortenedDirectory(Path.Combine(path, info.leftString + ".png")).Remove(0, 1);
string rightString = Class1.getShortenedDirectory(Path.Combine(path, info.rightString + ".png")).Remove(0, 1); string rightString = Class1.getShortenedDirectory(Path.Combine(path, info.rightString + ".png")).Remove(0, 1);
string upString = Class1.getShortenedDirectory(Path.Combine(path, info.upString + ".png")).Remove(0, 1); string upString = Class1.getShortenedDirectory(Path.Combine(path, info.upString + ".png")).Remove(0, 1);
string downString = Class1.getShortenedDirectory(Path.Combine(path, info.downString + ".png")).Remove(0, 1); string downString = Class1.getShortenedDirectory(Path.Combine(path, info.downString + ".png")).Remove(0, 1);
this.leftTexture = new Texture2DExtended(helper, Class1.Manifest, leftString); this.leftTexture = new Texture2DExtended(helper, Class1.Manifest, leftString);
this.rightTexture = new Texture2DExtended(helper, Class1.Manifest, rightString); this.rightTexture = new Texture2DExtended(helper, Class1.Manifest, rightString);
this.upTexture = new Texture2DExtended(helper, Class1.Manifest, upString); this.upTexture = new Texture2DExtended(helper, Class1.Manifest, upString);
this.downTexture = new Texture2DExtended(helper, Class1.Manifest, downString); this.downTexture = new Texture2DExtended(helper, Class1.Manifest, downString);
if (direction == Direction.left) this.currentTexture = leftTexture; switch (direction)
if (direction == Direction.right) this.currentTexture = rightTexture; {
if (direction == Direction.up) this.currentTexture = upTexture; case Direction.left:
if (direction == Direction.down) this.currentTexture = downTexture; this.currentTexture = this.leftTexture;
break;
case Direction.right:
this.currentTexture = this.rightTexture;
break;
case Direction.up:
this.currentTexture = this.upTexture;
break;
case Direction.down:
this.currentTexture = this.downTexture;
break;
}
} }
/// <summary> /// <summary>Sets the direction of this current texture to left.</summary>
/// Sets the direction of this current texture to left.
/// </summary>
public void setLeft() public void setLeft()
{ {
this.currentTexture = leftTexture; this.currentTexture = this.leftTexture;
} }
/// <summary> /// <summary>Sets the direction of this current texture to up.</summary>
/// Sets the direction of this current texture to up.
/// </summary>
public void setUp() public void setUp()
{ {
this.currentTexture = upTexture; this.currentTexture = this.upTexture;
} }
/// <summary> /// <summary>Sets the direction of this current texture to down.</summary>
/// Sets the direction of this current texture to down.
/// </summary>
public void setDown() public void setDown()
{ {
this.currentTexture = downTexture; this.currentTexture = this.downTexture;
} }
/// <summary> /// <summary>Sets the direction of this current texture to right.</summary>
/// Sets the direction of this current texture to right.
/// </summary>
public void setRight() public void setRight()
{ {
this.currentTexture = rightTexture; this.currentTexture = this.rightTexture;
} }
/// <summary> /// <summary>Gets the texture from this texture group depending on the direction.</summary>
/// Gets the texture from this texture group depending on the direction. /// <param name="direction">The facing direction.</param>
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
public virtual Texture2DExtended getTextureFromDirection(Direction direction) public virtual Texture2DExtended getTextureFromDirection(Direction direction)
{ {
if (direction == Direction.left) return this.leftTexture; switch (direction)
if (direction == Direction.right) return this.rightTexture; {
if (direction == Direction.up) return this.upTexture; case Direction.left:
if (direction == Direction.down) return this.downTexture; return this.leftTexture;
case Direction.right:
return this.rightTexture;
case Direction.up:
return this.upTexture;
case Direction.down:
return this.downTexture;
default:
return null; return null;
} }
} }
}
} }

View File

@ -1,73 +1,55 @@
using CustomNPCFramework.Framework.Enums;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using CustomNPCFramework.Framework.Enums;
using System.Text; using Microsoft.Xna.Framework;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.Graphics namespace CustomNPCFramework.Framework.Graphics
{ {
/// <summary> /// <summary>An expanded Asset info class that deals with seasons and genders.</summary>
/// An expanded Asset info class that deals with seasons and genders. public class ExtendedAssetInfo : AssetInfo
/// </summary>
public class ExtendedAssetInfo :AssetInfo
{ {
/// <summary> /// <summary>The genders this part is associated with.</summary>
/// The genders this part is associated with. 0=Male, 1=female, 2=other.
/// </summary>
public Genders gender; public Genders gender;
/// <summary>
/// A list of seasons where this part can be displayed /// <summary>A list of seasons where this part can be displayed.</summary>
/// </summary> public List<Seasons> seasons = new List<Seasons>();
public List<Seasons> seasons=new List<Seasons>();
/// <summary> /// <summary>The part type to be used for this asset such as hair, eyes, etc.</summary>
/// The part type to be used for this asset such as hair, eyes, etc.
/// </summary>
public PartType type; public PartType type;
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor. public ExtendedAssetInfo() { }
/// </summary>
public ExtendedAssetInfo() /// <summary>Construct an instance.</summary>
/// <param name="name">The name of the asset. This is the name that will be referenced in any asset manager or asset pool.</param>
/// <param name="standingAssetPaths">The name of the files to be used for the standing animation.</param>
/// <param name="movingAssetPaths">The name of the files to be used for the moving animation.</param>
/// <param name="swimmingAssetPaths">The name of the files to be used for the swimming animation.</param>
/// <param name="sittingAssetPaths">The name of the files to be used for the sitting animation.</param>
/// <param name="assetSize">The size of the asset. Width and height of the texture.</param>
/// <param name="randomizeOnLoad">Legacy, not really used anymore.</param>
/// <param name="gender">The type of gender this asset will be associated with.</param>
/// <param name="season">The type of season this asset will be associated with.</param>
/// <param name="type">The part type to be used for this asset such as hair, eyes, etc.</param>
public ExtendedAssetInfo(string name, NamePairings standingAssetPaths, NamePairings movingAssetPaths, NamePairings swimmingAssetPaths, NamePairings sittingAssetPaths, Vector2 assetSize, bool randomizeOnLoad, Genders gender, List<Seasons> season, PartType type)
: base(name, standingAssetPaths, movingAssetPaths, swimmingAssetPaths, sittingAssetPaths, assetSize, randomizeOnLoad)
{ {
this.seasons = new List<Seasons>(); this.gender = gender;
this.seasons = season ?? new List<Seasons>();
this.type = type;
} }
/// <summary> /// <summary>Save the json to a certain location.</summary>
/// Constructor. /// <param name="path">The absolute path to write.</param>
/// </summary>
/// <param name="name"></param>
/// <param name="assetSize"></param>
/// <param name="randomizeOnLoad"></param>
/// <param name="Gender">The type of gender this asset will be associated with.</param>
/// <param name="Season">The type of season this asset will be associated with.</param>
public ExtendedAssetInfo(string name, NamePairings StandingAssetPaths, NamePairings MovingAssetPaths, NamePairings SwimmingAssetPaths, NamePairings SittingAssetPaths, Vector2 assetSize, bool randomizeOnLoad, Genders Gender, List<Seasons> Season, PartType Type): base(name,StandingAssetPaths,MovingAssetPaths,SwimmingAssetPaths,SittingAssetPaths, assetSize, randomizeOnLoad)
{
this.gender = Gender;
this.seasons = Season;
if (this.seasons == null) this.seasons = new List<Seasons>();
this.type = Type;
}
/// <summary>
/// Save the json to a certain location.
/// </summary>
/// <param name="path"></param>
public new void writeToJson(string path) public new void writeToJson(string path)
{ {
Class1.ModHelper.WriteJsonFile<ExtendedAssetInfo>(path, this); Class1.ModHelper.WriteJsonFile<ExtendedAssetInfo>(path, this);
} }
/// <summary> /// <summary>Read the json from a certain location.</summary>
/// Read the json from a certain location. /// <param name="path">The absolute path to read.</param>
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public new static ExtendedAssetInfo readFromJson(string path) public new static ExtendedAssetInfo readFromJson(string path)
{ {
return Class1.ModHelper.ReadJsonFile<ExtendedAssetInfo>(path); return Class1.ModHelper.ReadJsonFile<ExtendedAssetInfo>(path);
} }
} }
} }

View File

@ -1,96 +1,67 @@
using CustomNPCFramework.Framework.Enums; using CustomNPCFramework.Framework.Enums;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.Graphics.TextureGroups namespace CustomNPCFramework.Framework.Graphics.TextureGroups
{ {
/// <summary> /// <summary>A group of a textures used to hold all of the textures associated with a single asset such as a hair style or a shirt.</summary>
/// A group of a textures used to hold all of the textures associated with a single asset such as a hair style or a shirt.
/// </summary>
public class TextureGroup public class TextureGroup
{ {
/// <summary> /// <summary>The directional (Left, Right, Up, Down) textures to be used when the NPC is standing.</summary>
/// The directional (Left, Right, Up, Down) textures to be used when the NPC is standing.
/// </summary>
public DirectionalTexture standingTexture; public DirectionalTexture standingTexture;
/// <summary>
/// The directional (Left, Right, Up, Down) textures to be used when the NPC is sitting. /// <summary>The directional (Left, Right, Up, Down) textures to be used when the NPC is sitting.</summary>
/// </summary>
public DirectionalTexture sittingTexture; public DirectionalTexture sittingTexture;
/// <summary>
/// The directional (Left, Right, Up, Down) textures to be used when the NPC is swimming. /// <summary>The directional (Left, Right, Up, Down) textures to be used when the NPC is swimming.</summary>
/// </summary>
public DirectionalTexture swimmingTexture; public DirectionalTexture swimmingTexture;
/// <summary>
/// The directional (Left, Right, Up, Down) textures to be used when the NPC is moving. /// <summary>The directional (Left, Right, Up, Down) textures to be used when the NPC is moving.</summary>
/// </summary>
public DirectionalTexture movingTexture; public DirectionalTexture movingTexture;
/// <summary> /// <summary>The current directional texture to be used by the npc. Can be things such as the standing, swimming, moving, or sitting texture.</summary>
/// The current directional texture to be used by the npc. Can be things such as the standing, swimming, moving, or sitting texture.
/// </summary>
public DirectionalTexture currentTexture; public DirectionalTexture currentTexture;
/// <summary> /// <summary>Asset info loaded in from the corresponding .json file.</summary>
/// Asset info loaded in from the corresponding .json file. private readonly AssetInfo info;
/// </summary>
private AssetInfo info;
/// <summary>
/// The path to the .json file.
/// </summary>
private string path;
/// <summary>
/// The current direction of the texture group. See Direction.cs
/// </summary>
private Direction dir;
/// <summary>
/// The type of asset this is. Body, hair, eyes, shirt,etc...
/// </summary>
private AnimationType type;
/// <summary> /// <summary>The path to the .json file.</summary>
/// Constructor. private readonly string path;
/// </summary>
/// <summary>The current direction of the texture group.</summary>
private readonly Direction dir;
/// <summary>The type of asset this is. Body, hair, eyes, shirt, etc.</summary>
private readonly AnimationType type;
/// <summary>Construct an instance.</summary>
/// <param name="info">The asset info file to be stored with this texture group.</param> /// <param name="info">The asset info file to be stored with this texture group.</param>
/// <param name="path">Use to locate the files on disk.</param> /// <param name="path">Use to locate the files on disk.</param>
/// <param name="direction">Used to determine the current direction/animation to load</param> /// <param name="direction">Used to determine the current direction/animation to load</param>
/// <param name="animationType">The type of asset this is. Eyes, Hair, Shirts, etc</param> /// <param name="animationType">The type of asset this is. Eyes, Hair, Shirts, etc</param>
public TextureGroup(AssetInfo info, string path,Direction direction ,AnimationType animationType=AnimationType.standing) public TextureGroup(AssetInfo info, string path, Direction direction, AnimationType animationType = AnimationType.standing)
{ {
this.standingTexture = new DirectionalTexture(Class1.ModHelper,info.standingAssetPaths, path, direction); this.standingTexture = new DirectionalTexture(Class1.ModHelper, info.standingAssetPaths, path, direction);
this.sittingTexture = new DirectionalTexture(Class1.ModHelper, info.sittingAssetPaths, path, direction); this.sittingTexture = new DirectionalTexture(Class1.ModHelper, info.sittingAssetPaths, path, direction);
this.swimmingTexture = new DirectionalTexture(Class1.ModHelper, info.swimmingAssetPaths, path, direction); this.swimmingTexture = new DirectionalTexture(Class1.ModHelper, info.swimmingAssetPaths, path, direction);
this.movingTexture = new DirectionalTexture(Class1.ModHelper,info.movingAssetPaths, path, direction); this.movingTexture = new DirectionalTexture(Class1.ModHelper, info.movingAssetPaths, path, direction);
this.info = info; this.info = info;
this.path = path; this.path = path;
this.dir = direction; this.dir = direction;
this.type = animationType; this.type = animationType;
if (animationType == AnimationType.standing) this.currentTexture = standingTexture; if (animationType == AnimationType.standing) this.currentTexture = this.standingTexture;
if (animationType == AnimationType.sitting) this.currentTexture = sittingTexture; if (animationType == AnimationType.sitting) this.currentTexture = this.sittingTexture;
if (animationType == AnimationType.swimming) this.currentTexture = swimmingTexture; if (animationType == AnimationType.swimming) this.currentTexture = this.swimmingTexture;
if (animationType == AnimationType.walking) this.currentTexture = movingTexture; if (animationType == AnimationType.walking) this.currentTexture = this.movingTexture;
} }
/// <summary> /// <summary>Gets a clone of this texture group. </summary>
/// Gets a clone of this texture group.
/// </summary>
/// <returns></returns>
public TextureGroup clone() public TextureGroup clone()
{ {
return new TextureGroup(this.info, this.path, this.dir, this.type); return new TextureGroup(this.info, this.path, this.dir, this.type);
} }
/// <summary>Sets all of the different animations to use their left facing sprites.</summary>
/// <summary>
/// Sets all of the different animations to use their left facing sprites.
/// </summary>
public virtual void setLeft() public virtual void setLeft()
{ {
this.movingTexture.setLeft(); this.movingTexture.setLeft();
@ -99,9 +70,7 @@ namespace CustomNPCFramework.Framework.Graphics.TextureGroups
this.swimmingTexture.setLeft(); this.swimmingTexture.setLeft();
} }
/// <summary> /// <summary>Sets all of the different animations to use their up facing sprites.</summary>
/// Sets all of the different animations to use their up facing sprites.
/// </summary>
public virtual void setUp() public virtual void setUp()
{ {
this.movingTexture.setUp(); this.movingTexture.setUp();
@ -110,9 +79,7 @@ namespace CustomNPCFramework.Framework.Graphics.TextureGroups
this.swimmingTexture.setUp(); this.swimmingTexture.setUp();
} }
/// <summary> /// <summary>Sets all of the different animations to use their down facing sprites.</summary>
/// Sets all of the different animations to use their down facing sprites.
/// </summary>
public virtual void setDown() public virtual void setDown()
{ {
this.movingTexture.setDown(); this.movingTexture.setDown();
@ -121,9 +88,7 @@ namespace CustomNPCFramework.Framework.Graphics.TextureGroups
this.swimmingTexture.setDown(); this.swimmingTexture.setDown();
} }
/// <summary> /// <summary>Sets all of the different animations to use their right facing sprites.</summary>
/// Sets all of the different animations to use their right facing sprites.
/// </summary>
public virtual void setRight() public virtual void setRight()
{ {
this.movingTexture.setRight(); this.movingTexture.setRight();
@ -132,11 +97,8 @@ namespace CustomNPCFramework.Framework.Graphics.TextureGroups
this.swimmingTexture.setRight(); this.swimmingTexture.setRight();
} }
/// <summary> /// <summary>Gets the appropriate animation texture based on the type of animation key passed in.</summary>
/// Get's the appropriate animation texture based on the type of animation key passed in. /// <param name="type">The animation type.</param>
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public virtual DirectionalTexture getTextureFromAnimation(AnimationType type) public virtual DirectionalTexture getTextureFromAnimation(AnimationType type)
{ {
if (type == AnimationType.standing) return this.standingTexture; if (type == AnimationType.standing) return this.standingTexture;
@ -145,6 +107,5 @@ namespace CustomNPCFramework.Framework.Graphics.TextureGroups
if (type == AnimationType.sitting) return this.sittingTexture; if (type == AnimationType.sitting) return this.sittingTexture;
return null; return null;
} }
} }
} }

View File

@ -1,78 +1,62 @@
using CustomNPCFramework.Framework.Enums; using CustomNPCFramework.Framework.Enums;
using CustomNPCFramework.Framework.NPCS; using CustomNPCFramework.Framework.NPCS;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using StardewValley; using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.ModularNPCS namespace CustomNPCFramework.Framework.ModularNpcs
{ {
/// <summary> /// <summary>Used to hold all of the sprites for a single asset such as hair or bodies.</summary>
/// Used to hold all of the sprites for a single asset such as hair or bodies.
/// </summary>
public class AnimatedSpriteCollection public class AnimatedSpriteCollection
{ {
/// <summary> /// <summary>The left sprite for this sprite asset part.</summary>
/// The left sprite for this sprite asset part.
/// </summary>
AnimatedSpriteExtended leftSprite; AnimatedSpriteExtended leftSprite;
/// <summary>
/// The right sprite for this sprite asset part. /// <summary>The right sprite for this sprite asset part.</summary>
/// </summary>
AnimatedSpriteExtended rightSprite; AnimatedSpriteExtended rightSprite;
/// <summary>
/// The up sprite for this sprite asset part. /// <summary>The up sprite for this sprite asset part.</summary>
/// </summary>
AnimatedSpriteExtended upSprite; AnimatedSpriteExtended upSprite;
/// <summary>
/// The down sprite for this sprite asset part. /// <summary>The down sprite for this sprite asset part.</summary>
/// </summary>
AnimatedSpriteExtended downSprite; AnimatedSpriteExtended downSprite;
/// <summary> /// <summary>The current sprite for this sprite collection. This is one of the four directions for this collection.</summary>
/// The current sprite for this sprite collection. This is one of the four directions for this collection.
/// </summary>
public AnimatedSpriteExtended currentSprite; public AnimatedSpriteExtended currentSprite;
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor.
/// </summary>
/// <param name="LeftSprite">Left animated sprite for this piece.</param> /// <param name="LeftSprite">Left animated sprite for this piece.</param>
/// <param name="RightSprite">Right animated sprite for this piece.</param> /// <param name="RightSprite">Right animated sprite for this piece.</param>
/// <param name="UpSprite">Up animated sprite for this piece.</param> /// <param name="UpSprite">Up animated sprite for this piece.</param>
/// <param name="DownSprite">Down animated sprite for this piece.</param> /// <param name="DownSprite">Down animated sprite for this piece.</param>
/// <param name="startingSpriteDirection"></param> /// <param name="startingSpriteDirection">The sprite's initial facing direction.</param>
public AnimatedSpriteCollection(AnimatedSpriteExtended LeftSprite,AnimatedSpriteExtended RightSprite,AnimatedSpriteExtended UpSprite,AnimatedSpriteExtended DownSprite,Direction startingSpriteDirection) public AnimatedSpriteCollection(AnimatedSpriteExtended LeftSprite, AnimatedSpriteExtended RightSprite, AnimatedSpriteExtended UpSprite, AnimatedSpriteExtended DownSprite, Direction startingSpriteDirection)
{ {
this.leftSprite = LeftSprite; this.leftSprite = LeftSprite;
this.rightSprite = RightSprite; this.rightSprite = RightSprite;
this.upSprite = UpSprite; this.upSprite = UpSprite;
this.downSprite = DownSprite; this.downSprite = DownSprite;
if (startingSpriteDirection == Direction.down) switch (startingSpriteDirection)
{ {
setDown(); case Direction.down:
} this.setDown();
if (startingSpriteDirection == Direction.left) break;
{
setLeft(); case Direction.left:
} this.setLeft();
if (startingSpriteDirection == Direction.right) break;
{
setRight(); case Direction.right:
} this.setRight();
if (startingSpriteDirection == Direction.up) break;
{
setUp(); case Direction.up:
this.setUp();
break;
} }
} }
/// <summary> /// <summary>Reloads all of the directional textures for this texture collection.</summary>
/// Reloads all of the directional textures for this texture collection.
/// </summary>
public virtual void reload() public virtual void reload()
{ {
this.leftSprite.reload(); this.leftSprite.reload();
@ -81,109 +65,66 @@ namespace CustomNPCFramework.Framework.ModularNPCS
this.downSprite.reload(); this.downSprite.reload();
} }
/// <summary> /// <summary>Sets the current sprite direction to face left.</summary>
/// Sets the current sprite direction to face left.
/// </summary>
public void setLeft() public void setLeft()
{ {
this.currentSprite = leftSprite; this.currentSprite = this.leftSprite;
} }
/// <summary> /// <summary>Sets the current sprite direction to face right.</summary>
/// Sets the current sprite direction to face right.
/// </summary>
public void setRight() public void setRight()
{ {
this.currentSprite = rightSprite; this.currentSprite = this.rightSprite;
} }
/// <summary> /// <summary>Sets the current sprite direction to face down.</summary>
/// Sets the current sprite direction to face down.
/// </summary>
public void setDown() public void setDown()
{ {
this.currentSprite = downSprite; this.currentSprite = this.downSprite;
} }
/// <summary> /// <summary>Sets the current sprite direction to face up.</summary>
/// Sets the current sprite direction to face up.
/// </summary>
public void setUp() public void setUp()
{ {
this.currentSprite = upSprite; this.currentSprite = this.upSprite;
} }
/// <summary> /// <summary>Used to draw the sprite to the screen.</summary>
/// Used to draw the sprite to the screen.
/// </summary>
/// <param name="b"></param>
/// <param name="screenPosition"></param>
/// <param name="layerDepth"></param>
public void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth) public void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth)
{ {
b.Draw(this.currentSprite.sprite.Texture, screenPosition, new Rectangle?(this.currentSprite.sprite.sourceRect), Color.White, 0.0f, Vector2.Zero, (float)Game1.pixelZoom, this.currentSprite.sprite.currentAnimation == null || !this.currentSprite.sprite.currentAnimation[this.currentSprite.sprite.currentAnimationIndex].flip ? SpriteEffects.None : SpriteEffects.FlipHorizontally, layerDepth); b.Draw(this.currentSprite.sprite.Texture, screenPosition, new Rectangle?(this.currentSprite.sprite.sourceRect), Color.White, 0.0f, Vector2.Zero, (float)Game1.pixelZoom, this.currentSprite.sprite.currentAnimation == null || !this.currentSprite.sprite.currentAnimation[this.currentSprite.sprite.currentAnimationIndex].flip ? SpriteEffects.None : SpriteEffects.FlipHorizontally, layerDepth);
} }
/// <summary> /// <summary>Used to draw the sprite to the screen.</summary>
/// Used to draw the sprite to the screen.
/// </summary>
/// <param name="b"></param>
/// <param name="screenPosition"></param>
/// <param name="layerDepth"></param>
/// <param name="xOffset"></param>
/// <param name="yOffset"></param>
/// <param name="c"></param>
/// <param name="flip"></param>
/// <param name="scale"></param>
/// <param name="rotation"></param>
/// <param name="characterSourceRectOffset"></param>
public void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth, int xOffset, int yOffset, Color c, bool flip = false, float scale = 1f, float rotation = 0.0f, bool characterSourceRectOffset = false) public void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth, int xOffset, int yOffset, Color c, bool flip = false, float scale = 1f, float rotation = 0.0f, bool characterSourceRectOffset = false)
{ {
b.Draw(this.currentSprite.sprite.Texture, screenPosition, new Rectangle?(new Rectangle(this.currentSprite.sprite.sourceRect.X + xOffset, this.currentSprite.sprite.sourceRect.Y + yOffset, this.currentSprite.sprite.sourceRect.Width, this.currentSprite.sprite.sourceRect.Height)), c, rotation, characterSourceRectOffset ? new Vector2((float)(this.currentSprite.sprite.SpriteWidth / 2), (float)((double)this.currentSprite.sprite.SpriteHeight * 3.0 / 4.0)) : Vector2.Zero, scale, flip || this.currentSprite.sprite.currentAnimation != null && this.currentSprite.sprite.currentAnimation[this.currentSprite.sprite.currentAnimationIndex].flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, layerDepth); b.Draw(this.currentSprite.sprite.Texture, screenPosition, new Rectangle?(new Rectangle(this.currentSprite.sprite.sourceRect.X + xOffset, this.currentSprite.sprite.sourceRect.Y + yOffset, this.currentSprite.sprite.sourceRect.Width, this.currentSprite.sprite.sourceRect.Height)), c, rotation, characterSourceRectOffset ? new Vector2((float)(this.currentSprite.sprite.SpriteWidth / 2), (float)((double)this.currentSprite.sprite.SpriteHeight * 3.0 / 4.0)) : Vector2.Zero, scale, flip || this.currentSprite.sprite.currentAnimation != null && this.currentSprite.sprite.currentAnimation[this.currentSprite.sprite.currentAnimationIndex].flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, layerDepth);
} }
/// <summary> /// <summary>A very verbose asset drawer.</summary>
/// A very verbose asset drawer. public void draw(SpriteBatch b, ExtendedNpc npc, Vector2 position, Rectangle sourceRectangle, Color color, float alpha, Vector2 origin, float scale, SpriteEffects effects, float layerDepth)
/// </summary>
/// <param name="b"></param>
/// <param name="npc"></param>
/// <param name="position"></param>
/// <param name="sourceRectangle"></param>
/// <param name="color"></param>
/// <param name="alpha"></param>
/// <param name="origin"></param>
/// <param name="scale"></param>
/// <param name="effects"></param>
/// <param name="layerDepth"></param>
public void draw(SpriteBatch b, ExtendedNPC npc, Vector2 position, Rectangle sourceRectangle,Color color, float alpha,Vector2 origin,float scale,SpriteEffects effects,float layerDepth)
{ {
//DEFINITELY FIX THIS PART. Something is wrong with how these two functions handle the drawing of my npc to the scene. //DEFINITELY FIX THIS PART. Something is wrong with how these two functions handle the drawing of my npc to the scene.
//this.draw(b, position, layerDepth); //this.draw(b, position, layerDepth);
b.Draw(this.currentSprite.sprite.Texture,position,this.currentSprite.sprite.sourceRect, color, 0.0f, origin,scale,effects,layerDepth); b.Draw(this.currentSprite.sprite.Texture, position, this.currentSprite.sprite.sourceRect, color, 0.0f, origin, scale, effects, layerDepth);
//b.Draw(this.Sprite.Texture, npc.getLocalPosition(Game1.viewport) + new Vector2((float)(this.sprite.spriteWidth * Game1.pixelZoom / 2), (float)(this.GetBoundingBox().Height / 2)) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(this.Sprite.SourceRect), Color.White * alpha, this.rotation, new Vector2((float)(this.sprite.spriteWidth / 2), (float)((double)this.sprite.spriteHeight * 3.0 / 4.0)), Math.Max(0.2f, this.scale) * (float)Game1.pixelZoom, this.flip || this.sprite.currentAnimation != null && this.sprite.currentAnimation[this.sprite.currentAnimationIndex].flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, this.drawOnTop ? 0.991f : (float)this.getStandingY() / 10000f)); //b.Draw(this.Sprite.Texture, npc.getLocalPosition(Game1.viewport) + new Vector2((float)(this.sprite.spriteWidth * Game1.pixelZoom / 2), (float)(this.GetBoundingBox().Height / 2)) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(this.Sprite.SourceRect), Color.White * alpha, this.rotation, new Vector2((float)(this.sprite.spriteWidth / 2), (float)((double)this.sprite.spriteHeight * 3.0 / 4.0)), Math.Max(0.2f, this.scale) * (float)Game1.pixelZoom, this.flip || this.sprite.currentAnimation != null && this.sprite.currentAnimation[this.sprite.currentAnimationIndex].flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, this.drawOnTop ? 0.991f : (float)this.getStandingY() / 10000f));
} }
/// <summary>Animate the current sprite. Theoreticlly works from index offset to how many frames</summary>
/// <summary>
/// Animate the current sprite. Theoreticlly works from index offset to how many frames
/// </summary>
/// <param name="intervalDelay">The delay in milliseconds between frames.</param> /// <param name="intervalDelay">The delay in milliseconds between frames.</param>
public void Animate(float intervalDelay,bool loop=true) public void Animate(float intervalDelay, bool loop = true)
{ {
this.Animate(Game1.currentGameTime, 0,2, intervalDelay,this.currentSprite.sprite,loop); this.Animate(Game1.currentGameTime, 0, 2, intervalDelay, this.currentSprite.sprite, loop);
} }
/// <summary> /// <summary>Animate the current sprite.</summary>
/// Animate the current sprite.
/// </summary>
/// <param name="gameTime">The game time from Monogames/XNA</param> /// <param name="gameTime">The game time from Monogames/XNA</param>
/// <param name="startFrame">The starting frame of the animation on the sprite sheet.</param> /// <param name="startFrame">The starting frame of the animation on the sprite sheet.</param>
/// <param name="numberOfFrames">The number of frames to animate the sprite.</param> /// <param name="numberOfFrames">The number of frames to animate the sprite.</param>
/// <param name="interval">The delay between frames in milliseconds.</param> /// <param name="interval">The delay between frames in milliseconds.</param>
/// <param name="sprite">The animated sprite from the npc.</param> /// <param name="sprite">The animated sprite from the npc.</param>
/// <param name="loop">If true, the animation plays over and over again.</param> /// <param name="loop">If true, the animation plays over and over again.</param>
/// <returns></returns> public virtual bool Animate(GameTime gameTime, int startFrame, int numberOfFrames, float interval, AnimatedSprite sprite, bool loop = true)
public virtual bool Animate(GameTime gameTime, int startFrame, int numberOfFrames, float interval, AnimatedSprite sprite, bool loop=true)
{ {
if (sprite.CurrentFrame >= startFrame + numberOfFrames + 1 || sprite.CurrentFrame < startFrame) if (sprite.CurrentFrame >= startFrame + numberOfFrames + 1 || sprite.CurrentFrame < startFrame)
sprite.CurrentFrame = startFrame + sprite.CurrentFrame % numberOfFrames; sprite.CurrentFrame = startFrame + sprite.CurrentFrame % numberOfFrames;
@ -204,10 +145,7 @@ namespace CustomNPCFramework.Framework.ModularNPCS
return false; return false;
} }
/// <summary> /// <summary>Update the source rectangle on the sprite sheet. Needed for animation.</summary>
/// Update the source rectangle on the sprite sheet. Needed for animation.
/// </summary>
/// <param name="sprite"></param>
public virtual void UpdateSourceRect(AnimatedSprite sprite) public virtual void UpdateSourceRect(AnimatedSprite sprite)
{ {
if (sprite.ignoreSourceRectUpdates) if (sprite.ignoreSourceRectUpdates)
@ -217,11 +155,8 @@ namespace CustomNPCFramework.Framework.ModularNPCS
//sprite.SourceRect = new Rectangle(, 0, sprite.spriteWidth, sprite.spriteHeight); //sprite.SourceRect = new Rectangle(, 0, sprite.spriteWidth, sprite.spriteHeight);
} }
/// <summary> /// <summary>Animate the current sprite. Theoreticlly works from index offset to how many frames</summary>
/// Animate the current sprite. Theoreticlly works from index offset to how many frames public void Animate(float intervalFromCharacter, int startFrame, int endFrame, bool loop)
/// </summary>
/// <param name="intervalFromCharacter"></param>
public void Animate(float intervalFromCharacter,int startFrame,int endFrame, bool loop)
{ {
this.currentSprite.sprite.loop = loop; this.currentSprite.sprite.loop = loop;
this.currentSprite.sprite.Animate(Game1.currentGameTime, startFrame, endFrame, intervalFromCharacter); this.currentSprite.sprite.Animate(Game1.currentGameTime, startFrame, endFrame, intervalFromCharacter);

View File

@ -1,32 +1,21 @@
using CustomNPCFramework.Framework.Graphics; using CustomNPCFramework.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using StardewValley; using StardewValley;
using StardustCore.UIUtilities; using StardustCore.UIUtilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.ModularNPCS namespace CustomNPCFramework.Framework.ModularNpcs
{ {
/// <summary> /// <summary>Used as a wrapper for the AnimatedSprite class.</summary>
/// Used as a wrapper for the AnimatedSprite class.
/// </summary>
public class AnimatedSpriteExtended public class AnimatedSpriteExtended
{ {
/// <summary> /// <summary>The actual sprite of the object.</summary>
/// The actual sprite of the object.
/// </summary>
public AnimatedSprite sprite; public AnimatedSprite sprite;
/// <summary>
/// The path to the texture to load the sprite from. /// <summary>The path to the texture to load the sprite from.</summary>
/// </summary>
public string path; public string path;
/// <summary>Construct an instance.</summary>
public AnimatedSpriteExtended(Texture2DExtended texture,AssetSheet assetSheet) public AnimatedSpriteExtended(Texture2DExtended texture, AssetSheet assetSheet)
{ {
//Set the sprite texture //Set the sprite texture
this.sprite = new AnimatedSprite(); this.sprite = new AnimatedSprite();
@ -39,25 +28,17 @@ namespace CustomNPCFramework.Framework.ModularNPCS
this.sprite.SpriteWidth = (int)assetSheet.assetInfo.assetSize.X; this.sprite.SpriteWidth = (int)assetSheet.assetInfo.assetSize.X;
this.sprite.SpriteHeight = (int)assetSheet.assetInfo.assetSize.Y; this.sprite.SpriteHeight = (int)assetSheet.assetInfo.assetSize.Y;
} }
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor. public AnimatedSpriteExtended(string path, int currentFrame, int spriteWidth, int spriteHeight)
/// </summary>
/// <param name="path"></param>
/// <param name="currentFrame"></param>
/// <param name="spriteWidth"></param>
/// <param name="spriteHeight"></param>
public AnimatedSpriteExtended(string path ,int currentFrame, int spriteWidth, int spriteHeight)
{ {
this.path = Class1.getRelativeDirectory(path); this.path = Class1.getRelativeDirectory(path);
//Set the sprite texture //Set the sprite texture
this.sprite = new AnimatedSprite(); this.sprite = new AnimatedSprite();
Texture2D load = Class1.ModHelper.Content.Load<Texture2D>(this.path); Texture2D load = Class1.ModHelper.Content.Load<Texture2D>(this.path);
var thing=Class1.ModHelper.Reflection.GetField<Texture2D>(this.sprite, "Texture", true); var thing = Class1.ModHelper.Reflection.GetField<Texture2D>(this.sprite, "Texture", true);
thing.SetValue(load); thing.SetValue(load);
//Set the fields. //Set the fields.
@ -68,9 +49,7 @@ namespace CustomNPCFramework.Framework.ModularNPCS
//this.sprite = new AnimatedSprite(texture, currentFrame, spriteWidth, spriteHeight); //this.sprite = new AnimatedSprite(texture, currentFrame, spriteWidth, spriteHeight);
} }
/// <summary> /// <summary>Reloads the asset from disk.</summary>
/// Reloads the asset from disk.
/// </summary>
public void reload() public void reload()
{ {
//Set the sprite texture //Set the sprite texture

View File

@ -1,131 +1,43 @@
using CustomNPCFramework.Framework.NPCS; using CustomNPCFramework.Framework.NPCS;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.ModularNPCS namespace CustomNPCFramework.Framework.ModularNpcs
{ {
/// <summary> /// <summary>Used as a base class for character animations.</summary>
/// Used as a base class for character animations.
/// </summary>
public class CharacterAnimationBase public class CharacterAnimationBase
{ {
/// <summary>Set the character sprites to left.</summary>
public virtual void setLeft() { }
/// <summary> /// <summary>Set the character sprites to right.</summary>
/// Constructor. public virtual void setRight() { }
/// </summary>
public CharacterAnimationBase()
{
}
/// <summary> /// <summary>Set the character sprites to up.</summary>
/// Set the character sprites to left. public virtual void setUp() { }
/// </summary>
public virtual void setLeft()
{
}
/// <summary> /// <summary>Set the character sprites to down.</summary>
/// Set the character sprites to right. public virtual void setDown() { }
/// </summary>
public virtual void setRight()
{
} /// <summary>Used to reload the sprite textures.</summary>
public virtual void reload() { }
/// <summary> /// <summary>Animate the sprites.</summary>
/// Set the character sprites to up.
/// </summary>
public virtual void setUp()
{
}
/// <summary>
/// Set the character sprites to down.
/// </summary>
public virtual void setDown()
{
}
/// <summary>
/// Used to reload the sprite textures.
/// </summary>
public virtual void reload()
{
}
/// <summary>
/// Animate the sprites.
/// </summary>
/// <param name="animationInterval">How long between animation frames in milliseconds.</param> /// <param name="animationInterval">How long between animation frames in milliseconds.</param>
public virtual void Animate(float animationInterval) public virtual void Animate(float animationInterval) { }
{
} /// <summary>Used to animate sprites.</summary>
/// <summary>
/// Used to animate sprites.
/// </summary>
/// <param name="animationInterval">How long between animation frames in milliseconds.</param> /// <param name="animationInterval">How long between animation frames in milliseconds.</param>
/// <param name="loop">Loop the animation.</param> /// <param name="loop">Loop the animation.</param>
public virtual void Animate(float animationInterval, bool loop=true) public virtual void Animate(float animationInterval, bool loop = true) { }
{
} /// <summary>Used to draw the sprite to the screen.</summary>
public virtual void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth) { }
/// <summary> /// <summary>Used to draw the sprite to the screen.</summary>
/// Used to draw the sprite to the screen. public virtual void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth, int xOffset, int yOffset, Color c, bool flip = false, float scale = 1f, float rotation = 0.0f, bool characterSourceRectOffset = false) { }
/// </summary>
/// <param name="b"></param>
/// <param name="screenPosition"></param>
/// <param name="layerDepth"></param>
public virtual void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth)
{
}
/// <summary>
/// Used to draw the sprite to the screen.
/// </summary>
/// <param name="b"></param>
/// <param name="screenPosition"></param>
/// <param name="layerDepth"></param>
/// <param name="xOffset"></param>
/// <param name="yOffset"></param>
/// <param name="c"></param>
/// <param name="flip"></param>
/// <param name="scale"></param>
/// <param name="rotation"></param>
/// <param name="characterSourceRectOffset"></param>
public virtual void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth, int xOffset, int yOffset, Color c, bool flip = false, float scale = 1f, float rotation = 0.0f, bool characterSourceRectOffset = false)
{
}
/// <summary>
/// A very verbose asset drawer.
/// </summary>
/// <param name="b"></param>
/// <param name="npc"></param>
/// <param name="position"></param>
/// <param name="sourceRectangle"></param>
/// <param name="color"></param>
/// <param name="alpha"></param>
/// <param name="origin"></param>
/// <param name="scale"></param>
/// <param name="effects"></param>
/// <param name="layerDepth"></param>
public virtual void draw(SpriteBatch b, ExtendedNPC npc, Vector2 position, Rectangle sourceRectangle, Color color, float alpha, Vector2 origin, float scale, SpriteEffects effects, float layerDepth)
{
}
/// <summary>A very verbose asset drawer.</summary>
public virtual void draw(SpriteBatch b, ExtendedNpc npc, Vector2 position, Rectangle sourceRectangle, Color color, float alpha, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) { }
} }
} }

View File

@ -1,54 +1,39 @@
using CustomNPCFramework.Framework.ModularNPCS.ColorCollections; using System;
using System.Collections.Generic;
using CustomNPCFramework.Framework.ModularNpcs.ColorCollections;
using CustomNPCFramework.Framework.NPCS; using CustomNPCFramework.Framework.NPCS;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using StardewValley; using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases namespace CustomNPCFramework.Framework.ModularNpcs.CharacterAnimationBases
{ {
/// <summary> /// <summary>A class used to reference the different textures used to comprise the different parts for character rendering.</summary>
/// A class used to reference the different textures used to comprise the different parts for character rendering. public class StandardCharacterAnimation : CharacterAnimationBase
/// </summary>
public class StandardCharacterAnimation :CharacterAnimationBase
{ {
/// <summary> /// <summary>Used to hold all of the information for the npc hair part.</summary>
/// Used to hold all of the information for the npc hair part.
/// </summary>
public AnimatedSpriteCollection hair; public AnimatedSpriteCollection hair;
/// <summary>
/// Used to hold all of the information for the npc body part. /// <summary>Used to hold all of the information for the npc body part.</summary>
/// </summary>
public AnimatedSpriteCollection body; public AnimatedSpriteCollection body;
/// <summary>
/// Used to hold all of the information for the npc eyes part. /// <summary>Used to hold all of the information for the npc eyes part.</summary>
/// </summary>
public AnimatedSpriteCollection eyes; public AnimatedSpriteCollection eyes;
/// <summary>
/// Used to hold all of the information for the npc shirt part. /// <summary>Used to hold all of the information for the npc shirt part.</summary>
/// </summary>
public AnimatedSpriteCollection shirt; public AnimatedSpriteCollection shirt;
/// <summary>
/// Used to hold all of the information for the npc pants part. /// <summary>Used to hold all of the information for the npc pants part.</summary>
/// </summary>
public AnimatedSpriteCollection pants; public AnimatedSpriteCollection pants;
/// <summary>
/// Used to hold all of the information for the npc shoes part. /// <summary>Used to hold all of the information for the npc shoes part.</summary>
/// </summary>
public AnimatedSpriteCollection shoes; public AnimatedSpriteCollection shoes;
/// <summary>
/// Used to hold all of the information for draw colors for the different parts. /// <summary>Used to hold all of the information for draw colors for the different parts.</summary>
/// </summary>
public StandardColorCollection drawColors; public StandardColorCollection drawColors;
public List<AnimatedSpriteCollection> accessories; public List<AnimatedSpriteCollection> accessories;
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor.
/// </summary>
/// <param name="bodyAnimation">The collection of textures to be used for the body part for the npc.</param> /// <param name="bodyAnimation">The collection of textures to be used for the body part for the npc.</param>
/// <param name="eyeAnimation">The collection of textures to be used for the eyes part for the npc.</param> /// <param name="eyeAnimation">The collection of textures to be used for the eyes part for the npc.</param>
/// <param name="hairAnimation">The collection of textures to be used for the hair part for the npc.</param> /// <param name="hairAnimation">The collection of textures to be used for the hair part for the npc.</param>
@ -57,7 +42,7 @@ namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases
/// <param name="shoesAnimation">The collection of textures to be used for the shoes part for the npc.</param> /// <param name="shoesAnimation">The collection of textures to be used for the shoes part for the npc.</param>
/// <param name="accessoriesWithAnimations">The collection of textures to be used for the accessories part for the npc.</param> /// <param name="accessoriesWithAnimations">The collection of textures to be used for the accessories part for the npc.</param>
/// <param name="DrawColors">The collection of draw colors for the different parts for the npc.</param> /// <param name="DrawColors">The collection of draw colors for the different parts for the npc.</param>
public StandardCharacterAnimation(AnimatedSpriteCollection bodyAnimation, AnimatedSpriteCollection eyeAnimation, AnimatedSpriteCollection hairAnimation, AnimatedSpriteCollection shirtAnimation, AnimatedSpriteCollection pantsAnimation, AnimatedSpriteCollection shoesAnimation,List<AnimatedSpriteCollection> accessoriesWithAnimations, StandardColorCollection DrawColors) :base() public StandardCharacterAnimation(AnimatedSpriteCollection bodyAnimation, AnimatedSpriteCollection eyeAnimation, AnimatedSpriteCollection hairAnimation, AnimatedSpriteCollection shirtAnimation, AnimatedSpriteCollection pantsAnimation, AnimatedSpriteCollection shoesAnimation, List<AnimatedSpriteCollection> accessoriesWithAnimations, StandardColorCollection DrawColors)
{ {
this.body = bodyAnimation; this.body = bodyAnimation;
this.hair = hairAnimation; this.hair = hairAnimation;
@ -69,9 +54,7 @@ namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases
this.drawColors = DrawColors; this.drawColors = DrawColors;
} }
/// <summary> /// <summary>Sets all of the different textures to face left.</summary>
/// Sets all of the different textures to face left.
/// </summary>
public override void setLeft() public override void setLeft()
{ {
this.body.setLeft(); this.body.setLeft();
@ -81,14 +64,11 @@ namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases
this.pants.setLeft(); this.pants.setLeft();
this.shoes.setLeft(); this.shoes.setLeft();
foreach(var accessory in this.accessories) foreach (var accessory in this.accessories)
{
accessory.setLeft(); accessory.setLeft();
} }
}
/// <summary> /// <summary>Sets all of the different textures to face right.</summary>
/// Sets all of the different textures to face right.
/// </summary>
public override void setRight() public override void setRight()
{ {
this.body.setRight(); this.body.setRight();
@ -99,13 +79,10 @@ namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases
this.shoes.setRight(); this.shoes.setRight();
foreach (var accessory in this.accessories) foreach (var accessory in this.accessories)
{
accessory.setRight(); accessory.setRight();
} }
}
/// <summary> /// <summary>Sets all of the different textures to face up.</summary>
/// Sets all of the different textures to face up.
/// </summary>
public override void setUp() public override void setUp()
{ {
this.body.setUp(); this.body.setUp();
@ -116,13 +93,10 @@ namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases
this.shoes.setUp(); this.shoes.setUp();
foreach (var accessory in this.accessories) foreach (var accessory in this.accessories)
{
accessory.setUp(); accessory.setUp();
} }
}
/// <summary> /// <summary>Sets all of the different textures to face down.</summary>
/// Sets all of the different textures to face down.
/// </summary>
public override void setDown() public override void setDown()
{ {
this.body.setDown(); this.body.setDown();
@ -133,14 +107,10 @@ namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases
this.shoes.setDown(); this.shoes.setDown();
foreach (var accessory in this.accessories) foreach (var accessory in this.accessories)
{
accessory.setDown(); accessory.setDown();
} }
}
/// <summary> /// <summary>Reloads all of the sprite textures.</summary>
/// Reloads all of the sprite textures.
/// </summary>
public override void reload() public override void reload()
{ {
this.body.reload(); this.body.reload();
@ -151,119 +121,77 @@ namespace CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases
this.shoes.reload(); this.shoes.reload();
} }
/// <summary> /// <summary>Animates all of the textures for this sprite.</summary>
/// Animates all of the textures for this sprite.
/// </summary>
/// <param name="animationInterval">The delay in milliseconds between animation frames.</param> /// <param name="animationInterval">The delay in milliseconds between animation frames.</param>
/// <param name="loop">Determines if the animation continuously plays over and over.</param> /// <param name="loop">Determines if the animation continuously plays over and over.</param>
public override void Animate(float animationInterval,bool loop=true) public override void Animate(float animationInterval, bool loop = true)
{ {
this.body.Animate(animationInterval,loop); this.body.Animate(animationInterval, loop);
this.hair.Animate(animationInterval,loop); this.hair.Animate(animationInterval, loop);
this.eyes.Animate(animationInterval,loop); this.eyes.Animate(animationInterval, loop);
this.shirt.Animate(animationInterval,loop); this.shirt.Animate(animationInterval, loop);
this.pants.Animate(animationInterval,loop); this.pants.Animate(animationInterval, loop);
this.shoes.Animate(animationInterval,loop); this.shoes.Animate(animationInterval, loop);
foreach(var accessory in this.accessories) foreach (var accessory in this.accessories)
{ accessory.Animate(animationInterval, loop);
accessory.Animate(animationInterval,loop);
} }
} /// <summary>Used to draw the sprite to the screen.</summary>
/// <summary>
/// Used to draw the sprite to the screen.
/// </summary>
/// <param name="b"></param>
/// <param name="screenPosition"></param>
/// <param name="layerDepth"></param>
public override void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth) public override void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth)
{ {
this.body.draw(b,screenPosition,layerDepth); this.body.draw(b, screenPosition, layerDepth);
this.hair.draw(b, screenPosition, layerDepth); this.hair.draw(b, screenPosition, layerDepth);
this.eyes.draw(b, screenPosition, layerDepth); this.eyes.draw(b, screenPosition, layerDepth);
this.shirt.draw(b, screenPosition, layerDepth); this.shirt.draw(b, screenPosition, layerDepth);
this.pants.draw(b, screenPosition, layerDepth); this.pants.draw(b, screenPosition, layerDepth);
this.shoes.draw(b, screenPosition, layerDepth); this.shoes.draw(b, screenPosition, layerDepth);
foreach (var accessory in this.accessories) foreach (var accessory in this.accessories)
{
accessory.draw(b, screenPosition, layerDepth); accessory.draw(b, screenPosition, layerDepth);
}
//b.Draw(this.currentSprite.Texture, screenPosition, new Rectangle?(this.currentSprite.sourceRect), Color.White, 0.0f, Vector2.Zero, (float)Game1.pixelZoom, this.currentSprite.currentAnimation == null || !this.currentSprite.currentAnimation[this.currentSprite.currentAnimationIndex].flip ? SpriteEffects.None : SpriteEffects.FlipHorizontally, layerDepth); //b.Draw(this.currentSprite.Texture, screenPosition, new Rectangle?(this.currentSprite.sourceRect), Color.White, 0.0f, Vector2.Zero, (float)Game1.pixelZoom, this.currentSprite.currentAnimation == null || !this.currentSprite.currentAnimation[this.currentSprite.currentAnimationIndex].flip ? SpriteEffects.None : SpriteEffects.FlipHorizontally, layerDepth);
} }
/// <summary>Used to draw the sprite to the screen.</summary>
/// <summary>
/// Used to draw the sprite to the screen.
/// </summary>
/// <param name="b"></param>
/// <param name="screenPosition"></param>
/// <param name="layerDepth"></param>
/// <param name="xOffset"></param>
/// <param name="yOffset"></param>
/// <param name="c"></param>
/// <param name="flip"></param>
/// <param name="scale"></param>
/// <param name="rotation"></param>
/// <param name="characterSourceRectOffset"></param>
public override void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth, int xOffset, int yOffset, Color c, bool flip = false, float scale = 1f, float rotation = 0.0f, bool characterSourceRectOffset = false) public override void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth, int xOffset, int yOffset, Color c, bool flip = false, float scale = 1f, float rotation = 0.0f, bool characterSourceRectOffset = false)
{ {
// b.Draw(this.currentSprite.Texture, screenPosition, new Rectangle?(new Rectangle(this.currentSprite.sourceRect.X + xOffset, this.currentSprite.sourceRect.Y + yOffset, this.currentSprite.sourceRect.Width, this.currentSprite.sourceRect.Height)), c, rotation, characterSourceRectOffset ? new Vector2((float)(this.currentSprite.spriteWidth / 2), (float)((double)this.currentSprite.spriteHeight * 3.0 / 4.0)) : Vector2.Zero, scale, flip || this.currentSprite.currentAnimation != null && this.currentSprite.currentAnimation[this.currentSprite.currentAnimationIndex].flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, layerDepth); // b.Draw(this.currentSprite.Texture, screenPosition, new Rectangle?(new Rectangle(this.currentSprite.sourceRect.X + xOffset, this.currentSprite.sourceRect.Y + yOffset, this.currentSprite.sourceRect.Width, this.currentSprite.sourceRect.Height)), c, rotation, characterSourceRectOffset ? new Vector2((float)(this.currentSprite.spriteWidth / 2), (float)((double)this.currentSprite.spriteHeight * 3.0 / 4.0)) : Vector2.Zero, scale, flip || this.currentSprite.currentAnimation != null && this.currentSprite.currentAnimation[this.currentSprite.currentAnimationIndex].flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, layerDepth);
this.body.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c,this.drawColors.bodyColor), flip, scale, rotation, characterSourceRectOffset); this.body.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.bodyColor), flip, scale, rotation, characterSourceRectOffset);
this.hair.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.hairColor), flip, scale, rotation, characterSourceRectOffset); this.hair.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.hairColor), flip, scale, rotation, characterSourceRectOffset);
this.eyes.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.eyeColor), flip, scale, rotation, characterSourceRectOffset); this.eyes.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.eyeColor), flip, scale, rotation, characterSourceRectOffset);
this.shirt.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.shirtColor), flip, scale, rotation, characterSourceRectOffset); this.shirt.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.shirtColor), flip, scale, rotation, characterSourceRectOffset);
this.pants.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.bottomsColor), flip, scale, rotation, characterSourceRectOffset); this.pants.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.bottomsColor), flip, scale, rotation, characterSourceRectOffset);
this.shoes.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.shoesColor), flip, scale, rotation, characterSourceRectOffset); this.shoes.draw(b, screenPosition, layerDepth, xOffset, yOffset, StandardColorCollection.colorMult(c, this.drawColors.shoesColor), flip, scale, rotation, characterSourceRectOffset);
foreach(var accessory in this.accessories) foreach (var accessory in this.accessories)
{
accessory.draw(b, screenPosition, layerDepth, xOffset, yOffset, c, flip, scale, rotation, characterSourceRectOffset); accessory.draw(b, screenPosition, layerDepth, xOffset, yOffset, c, flip, scale, rotation, characterSourceRectOffset);
} }
}
/// <summary> /// <summary>A very verbose asset drawer.</summary>
/// A very verbose asset drawer. public override void draw(SpriteBatch b, ExtendedNpc npc, Vector2 position, Rectangle sourceRectangle, Color color, float alpha, Vector2 origin, float scale, SpriteEffects effects, float layerDepth)
/// </summary>
/// <param name="b"></param>
/// <param name="npc"></param>
/// <param name="position"></param>
/// <param name="sourceRectangle"></param>
/// <param name="color"></param>
/// <param name="alpha"></param>
/// <param name="origin"></param>
/// <param name="scale"></param>
/// <param name="effects"></param>
/// <param name="layerDepth"></param>
public override void draw(SpriteBatch b, ExtendedNPC npc, Vector2 position, Rectangle sourceRectangle, Color color, float alpha, Vector2 origin, float scale, SpriteEffects effects, float layerDepth)
{ {
//Class1.ModMonitor.Log(sourceRectangle.ToString()); //Class1.ModMonitor.Log(sourceRectangle.ToString());
Vector2 generalOffset = new Vector2(0, 1*Game1.tileSize); //Puts the sprite at the correct positioning. Vector2 generalOffset = new Vector2(0, 1 * Game1.tileSize); //Puts the sprite at the correct positioning.
position -= new Vector2(0, 0.25f * Game1.tileSize); position -= new Vector2(0, 0.25f * Game1.tileSize);
float smallOffset = 0.001f; float smallOffset = 0.001f;
float tinyOffset = 0.0001f; float tinyOffset = 0.0001f;
//Class1.ModMonitor.Log((position - generalOffset).ToString()); //Class1.ModMonitor.Log((position - generalOffset).ToString());
float num = Math.Max(0.0f, (float)(Math.Ceiling(Math.Sin(Game1.currentGameTime.TotalGameTime.TotalMilliseconds / 600.0 + (double)npc.DefaultPosition.X * 20.0)) / 4.0)); float num = Math.Max(0.0f, (float)(Math.Ceiling(Math.Sin(Game1.currentGameTime.TotalGameTime.TotalMilliseconds / 600.0 + (double)npc.DefaultPosition.X * 20.0)) / 4.0));
this.body.draw(b, npc, position-generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.bodyColor), alpha, origin, scale*Game1.pixelZoom, effects, layerDepth + smallOffset); this.body.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.bodyColor), alpha, origin, scale * Game1.pixelZoom, effects, layerDepth + smallOffset);
this.eyes.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.eyeColor), alpha, origin, scale*Game1.pixelZoom, effects, layerDepth + smallOffset+(tinyOffset *1)); this.eyes.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.eyeColor), alpha, origin, scale * Game1.pixelZoom, effects, layerDepth + smallOffset + (tinyOffset * 1));
this.hair.draw(b, npc, position-generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.hairColor), alpha, origin, scale*Game1.pixelZoom, effects, layerDepth + smallOffset+(tinyOffset *2)); this.hair.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.hairColor), alpha, origin, scale * Game1.pixelZoom, effects, layerDepth + smallOffset + (tinyOffset * 2));
if (num > 0.0f) if (num > 0.0f)
{ {
Vector2 shirtOffset = new Vector2((1 * Game1.tileSize) / 4, (1 * Game1.tileSize) / 4); Vector2 shirtOffset = new Vector2((1 * Game1.tileSize) / 4, (1 * Game1.tileSize) / 4);
this.shirt.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.shirtColor), alpha, new Vector2(0.5f,1), scale * Game1.pixelZoom + num, effects, layerDepth + smallOffset + (tinyOffset * 3)); this.shirt.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.shirtColor), alpha, new Vector2(0.5f, 1), scale * Game1.pixelZoom + num, effects, layerDepth + smallOffset + (tinyOffset * 3));
} }
else else
{ {
this.shirt.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.shirtColor), alpha, origin, scale * Game1.pixelZoom, effects, layerDepth + smallOffset + (tinyOffset * 3)); this.shirt.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.shirtColor), alpha, origin, scale * Game1.pixelZoom, effects, layerDepth + smallOffset + (tinyOffset * 3));
} }
this.pants.draw(b, npc, position-generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.bottomsColor), alpha, origin, scale*Game1.pixelZoom, effects, layerDepth + smallOffset+(tinyOffset*4)); this.pants.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.bottomsColor), alpha, origin, scale * Game1.pixelZoom, effects, layerDepth + smallOffset + (tinyOffset * 4));
this.shoes.draw(b, npc, position-generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.shoesColor), alpha, origin, scale*Game1.pixelZoom, effects, layerDepth + smallOffset+(tinyOffset*5)); this.shoes.draw(b, npc, position - generalOffset, sourceRectangle, StandardColorCollection.colorMult(color, this.drawColors.shoesColor), alpha, origin, scale * Game1.pixelZoom, effects, layerDepth + smallOffset + (tinyOffset * 5));
foreach(var accessory in this.accessories)
{
accessory.draw(b, npc, position-generalOffset, sourceRectangle, color, alpha, origin, scale, effects, layerDepth +0.0006f);
}
}
foreach (var accessory in this.accessories)
accessory.draw(b, npc, position - generalOffset, sourceRectangle, color, alpha, origin, scale, effects, layerDepth + 0.0006f);
}
} }
} }

View File

@ -1,93 +1,72 @@
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.ModularNPCS.ColorCollections namespace CustomNPCFramework.Framework.ModularNpcs.ColorCollections
{ {
/// <summary> /// <summary>Collection of colors to be used for the StandardCharacterAnimation object.</summary>
/// Collection of colors to be used for the StandardCharacterAnimation object.
/// </summary>
public class StandardColorCollection public class StandardColorCollection
{ {
/// <summary> /// <summary>The draw color to be used for the body sprite for the npc.</summary>
/// The draw color to be used for the body sprite for the npc.
/// </summary>
public Color bodyColor; public Color bodyColor;
/// <summary>
/// The draw color to be used for the eye sprite for the npc. /// <summary>The draw color to be used for the eye sprite for the npc.</summary>
/// </summary>
public Color eyeColor; public Color eyeColor;
/// <summary>
/// The draw color to be used for the hair sprite for the npc. /// <summary>The draw color to be used for the hair sprite for the npc.</summary>
/// </summary>
public Color hairColor; public Color hairColor;
/// <summary>
/// The draw color to be used for the shirt sprite for the npc. /// <summary>The draw color to be used for the shirt sprite for the npc.</summary>
/// </summary>
public Color shirtColor; public Color shirtColor;
/// <summary>
/// The draw color to be used for the bottoms/pants sprite for the npc. /// <summary>The draw color to be used for the bottoms/pants sprite for the npc.</summary>
/// </summary>
public Color bottomsColor; public Color bottomsColor;
/// <summary>
/// The draw color to be used for the shoes sprite for the npc. /// <summary>The draw color to be used for the shoes sprite for the npc.</summary>
/// </summary>
public Color shoesColor; public Color shoesColor;
/// <summary> /// <summary>Construct an instance.</summary>
/// Default constrctor that sets all of the draw colors to white.
/// </summary>
public StandardColorCollection() public StandardColorCollection()
{ {
defaultColor(this.bodyColor); this.defaultColor(this.bodyColor);
defaultColor(this.eyeColor); this.defaultColor(this.eyeColor);
defaultColor(this.hairColor); this.defaultColor(this.hairColor);
defaultColor(this.shirtColor); this.defaultColor(this.shirtColor);
defaultColor(this.bottomsColor); this.defaultColor(this.bottomsColor);
defaultColor(this.shoesColor); this.defaultColor(this.shoesColor);
} }
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor that takes different colors as parameters. /// <param name="bodyColor">Color for the body texture.</param>
/// </summary> /// <param name="eyeColor">Color for the eyes texture.</param>
/// <param name="BodyColor">Color for the body texture.</param> /// <param name="hairColor">Color for the hair texture.</param>
/// <param name="EyeColor">Color for the eyes texture.</param> /// <param name="shirtColor">Color for the shirt texture.</param>
/// <param name="HairColor">Color for the hair texture.</param> /// <param name="bottomsColor">Color for the bottoms texture.</param>
/// <param name="ShirtColor">Color for the shirt texture.</param> /// <param name="shoesColor">Color for the shoes texture.</param>
/// <param name="BottomsColor">Color for the bottoms texture.</param> public StandardColorCollection(Color? bodyColor, Color? eyeColor, Color? hairColor, Color? shirtColor, Color? bottomsColor, Color? shoesColor)
/// <param name="ShoesColor">Color for the shoes texture.</param>
public StandardColorCollection(Color? BodyColor, Color? EyeColor, Color? HairColor, Color? ShirtColor, Color? BottomsColor, Color? ShoesColor)
{ {
this.bodyColor = (Color)BodyColor.GetValueOrDefault(Color.White); this.bodyColor = bodyColor.GetValueOrDefault(Color.White);
this.eyeColor = (Color)EyeColor.GetValueOrDefault(Color.White); this.eyeColor = eyeColor.GetValueOrDefault(Color.White);
this.hairColor = (Color)HairColor.GetValueOrDefault(Color.White); this.hairColor = hairColor.GetValueOrDefault(Color.White);
this.shirtColor = (Color)ShirtColor.GetValueOrDefault(Color.White); this.shirtColor = shirtColor.GetValueOrDefault(Color.White);
this.bottomsColor = (Color)BottomsColor.GetValueOrDefault(Color.White); this.bottomsColor = bottomsColor.GetValueOrDefault(Color.White);
this.shoesColor = (Color)ShoesColor.GetValueOrDefault(Color.White); this.shoesColor = shoesColor.GetValueOrDefault(Color.White);
defaultColor(this.bodyColor); this.defaultColor(this.bodyColor);
defaultColor(this.eyeColor); this.defaultColor(this.eyeColor);
defaultColor(this.hairColor); this.defaultColor(this.hairColor);
defaultColor(this.shirtColor); this.defaultColor(this.shirtColor);
defaultColor(this.bottomsColor); this.defaultColor(this.bottomsColor);
defaultColor(this.shoesColor); this.defaultColor(this.shoesColor);
} }
/// <summary> /// <summary>If a color is null, make it white.</summary>
/// If a color is null, make it white. /// <param name="color">The color to check.</param>
/// </summary>
/// <param name="color"></param>
public void defaultColor(Color color) public void defaultColor(Color color)
{ {
if (color == null) color = Color.White; if (color == null)
color = Color.White;
} }
/// <summary> /// <summary>Used to mix colors together.</summary>
/// Used to mix colors together.
/// </summary>
/// <param name="cBase">The base color to mix.</param> /// <param name="cBase">The base color to mix.</param>
/// <param name="cMult">The modifier color to mix.</param> /// <param name="cMult">The modifier color to mix.</param>
/// <returns>A color that is a mix between the two colors passed in.</returns> /// <returns>A color that is a mix between the two colors passed in.</returns>

View File

@ -1,31 +1,18 @@
using System; namespace CustomNPCFramework.Framework.ModularNpcs.ModularRenderers
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.ModularNPCS.ModularRenderers
{ {
/// <summary> /// <summary>A class used instead of an enum to hold keys for all of the different animations.</summary>
/// A class used instead of an enum to hold keys for all of the different animations.
/// </summary>
public class AnimationKeys public class AnimationKeys
{ {
/// <summary> /// <summary>The string that is used for the standing animation.</summary>
/// The string that is used for the standing animation.
/// </summary>
public static string standingKey = "standing"; public static string standingKey = "standing";
/// <summary>
/// The string that is used for the walking/moving animation. /// <summary>The string that is used for the walking/moving animation.</summary>
/// </summary>
public static string walkingKey = "walking"; public static string walkingKey = "walking";
/// <summary>
/// The string that is used for the sitting animation. /// <summary>The string that is used for the sitting animation.</summary>
/// </summary>
public static string sittingKey = "sitting"; public static string sittingKey = "sitting";
/// <summary>
/// The string that is used for the swimming animation. /// <summary>The string that is used for the swimming animation.</summary>
/// </summary>
public static string swimmingKey = "swimming"; public static string swimmingKey = "swimming";
} }
} }

View File

@ -1,205 +1,137 @@
using CustomNPCFramework.Framework.Enums; using System.Collections.Generic;
using CustomNPCFramework.Framework.Graphics; using CustomNPCFramework.Framework.Enums;
using CustomNPCFramework.Framework.ModularNPCS.CharacterAnimationBases; using CustomNPCFramework.Framework.ModularNpcs.CharacterAnimationBases;
using CustomNPCFramework.Framework.NPCS; using CustomNPCFramework.Framework.NPCS;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.ModularNPCS.ModularRenderers namespace CustomNPCFramework.Framework.ModularNpcs.ModularRenderers
{ {
/// <summary> /// <summary>A class used to hold all of the textures/animations/information to make modular npc rendering possible.</summary>
/// A class used to hold all of the textures/animations/information to make modular npc rendering possible.
/// </summary>
public class BasicRenderer public class BasicRenderer
{ {
/// <summary> /// <summary>Dictionary that holds key pair values of (animationName,Animation). USed to manage multiple animations. </summary>
/// Dictionary that holds key pair values of (animationName,Animation). USed to manage multiple animations.
/// </summary>
public Dictionary<string, StandardCharacterAnimation> animationList; public Dictionary<string, StandardCharacterAnimation> animationList;
/// <summary>
/// Used to keep track of what animation is currently being used. /// <summary>Used to keep track of what animation is currently being used.</summary>
/// </summary>
public StandardCharacterAnimation currentAnimation; public StandardCharacterAnimation currentAnimation;
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor.
/// </summary>
/// <param name="standingAnimation">The animation information to be used when the character is standing.</param> /// <param name="standingAnimation">The animation information to be used when the character is standing.</param>
/// <param name="walkingAnimation">The animation information to be used when the character is walking/moving.</param> /// <param name="walkingAnimation">The animation information to be used when the character is walking/moving.</param>
/// <param name="swimmingAnimation">The animation information to be used when the character is walking/moving.</param> /// <param name="swimmingAnimation">The animation information to be used when the character is walking/moving.</param>
public BasicRenderer(StandardCharacterAnimation standingAnimation,StandardCharacterAnimation walkingAnimation, StandardCharacterAnimation swimmingAnimation) public BasicRenderer(StandardCharacterAnimation standingAnimation, StandardCharacterAnimation walkingAnimation, StandardCharacterAnimation swimmingAnimation)
{ {
animationList = new Dictionary<string, StandardCharacterAnimation>(); this.animationList = new Dictionary<string, StandardCharacterAnimation>();
animationList.Add(AnimationKeys.standingKey, standingAnimation); this.animationList.Add(AnimationKeys.standingKey, standingAnimation);
animationList.Add(AnimationKeys.walkingKey, walkingAnimation); this.animationList.Add(AnimationKeys.walkingKey, walkingAnimation);
animationList.Add(AnimationKeys.swimmingKey, swimmingAnimation); this.animationList.Add(AnimationKeys.swimmingKey, swimmingAnimation);
setAnimation(AnimationKeys.standingKey); this.setAnimation(AnimationKeys.standingKey);
} }
/// <summary> /// <summary>Sets the animation associated with the key name; If it fails the npc will just default to standing.</summary>
/// Sets the animation associated with the key name; If it fails the npc will just default to standing.
/// </summary>
/// <param name="key">The name of the animation to swap the current animation to.</param> /// <param name="key">The name of the animation to swap the current animation to.</param>
public virtual void setAnimation(string key) public virtual void setAnimation(string key)
{ {
this.currentAnimation = animationList[key]; this.currentAnimation = this.animationList[key];
if (this.currentAnimation == null) if (this.currentAnimation == null)
{ {
Class1.ModMonitor.Log("ERROR SETTING AN ANIMATION: "+key); Class1.ModMonitor.Log("ERROR SETTING AN ANIMATION: " + key);
this.setAnimation(AnimationKeys.standingKey); this.setAnimation(AnimationKeys.standingKey);
} }
} }
/// <summary> /// <summary>Sets the direction of the current animated sprite respectively.</summary>
/// Sets the direction of the current animated sprite respectively.
/// </summary>
/// <param name="facingDirection">The direction to face. 0=up, 1=right, 2= down, 3=left.</param> /// <param name="facingDirection">The direction to face. 0=up, 1=right, 2= down, 3=left.</param>
public virtual void setDirection(int facingDirection) public virtual void setDirection(int facingDirection)
{ {
if (facingDirection == 0) setUp(); this.setDirection((Direction)facingDirection);
if (facingDirection == 1) setRight();
if (facingDirection == 2) setDown();
if (facingDirection == 2) setLeft();
} }
/// <summary> /// <summary>Sets the direction of the current animated sprite respectively to the direction passed in.</summary>
/// Sets the direction of the current animated sprite respectively to the direction passed in.
/// </summary>
/// <param name="direction">The direction to face.</param> /// <param name="direction">The direction to face.</param>
public virtual void setDirection(Direction direction) public virtual void setDirection(Direction direction)
{ {
if (direction == Direction.up) setUp(); switch (direction)
if (direction == Direction.right) setRight(); {
if (direction == Direction.down) setDown(); case Direction.up:
if (direction == Direction.left) setLeft(); this.setUp();
break;
case Direction.right:
this.setRight();
break;
case Direction.down:
this.setDown();
break;
case Direction.left:
this.setLeft();
break;
}
} }
/// <summary>Sets the current animated sprite to face left.</summary>
/// <summary>
/// Sets the current animated sprite to face left.
/// </summary>
public virtual void setLeft() public virtual void setLeft()
{ {
this.currentAnimation.setLeft(); this.currentAnimation.setLeft();
} }
/// <summary> /// <summary>Sets the current animated sprite to face right.</summary>
/// Sets the current animated sprite to face right.
/// </summary>
public virtual void setRight() public virtual void setRight()
{ {
this.currentAnimation.setRight(); this.currentAnimation.setRight();
} }
/// <summary> /// <summary>Sets the current animated sprite to face up.</summary>
/// Sets the current animated sprite to face up.
/// </summary>
public virtual void setUp() public virtual void setUp()
{ {
this.currentAnimation.setUp(); this.currentAnimation.setUp();
} }
/// <summary> /// <summary>Sets the current animated sprite to face down.</summary>
/// Sets the current animated sprite to face down.
/// </summary>
public virtual void setDown() public virtual void setDown()
{ {
this.currentAnimation.setDown(); this.currentAnimation.setDown();
} }
/// <summary> /// <summary>Used to reload all of the sprites pertaining to all of the animations stored in this renderer.</summary>
/// Used to reload all of the sprites pertaining to all of the animations stored in this renderer.
/// </summary>
public virtual void reloadSprites() public virtual void reloadSprites()
{ {
foreach(var v in this.animationList) foreach (var v in this.animationList)
{
v.Value.reload(); v.Value.reload();
} }
}
/// <summary> /// <summary>Used to draw the sprite to the screen.</summary>
/// Used to draw the sprite to the screen.
/// </summary>
/// <param name="b"></param>
/// <param name="screenPosition"></param>
/// <param name="layerDepth"></param>
public virtual void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth) public virtual void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth)
{ {
this.currentAnimation.draw(b, screenPosition, layerDepth); this.currentAnimation.draw(b, screenPosition, layerDepth);
} }
/// <summary> /// <summary>Used to draw the sprite to the screen.</summary>
/// Used to draw the sprite to the screen.
/// </summary>
/// <param name="b"></param>
/// <param name="screenPosition"></param>
/// <param name="layerDepth"></param>
/// <param name="xOffset"></param>
/// <param name="yOffset"></param>
/// <param name="c"></param>
/// <param name="flip"></param>
/// <param name="scale"></param>
/// <param name="rotation"></param>
/// <param name="characterSourceRectOffset"></param>
public virtual void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth, int xOffset, int yOffset, Color c, bool flip = false, float scale = 1f, float rotation = 0.0f, bool characterSourceRectOffset = false) public virtual void draw(SpriteBatch b, Vector2 screenPosition, float layerDepth, int xOffset, int yOffset, Color c, bool flip = false, float scale = 1f, float rotation = 0.0f, bool characterSourceRectOffset = false)
{ {
this.currentAnimation.draw(b, screenPosition, layerDepth, xOffset, yOffset, c, flip, scale, rotation, characterSourceRectOffset); this.currentAnimation.draw(b, screenPosition, layerDepth, xOffset, yOffset, c, flip, scale, rotation, characterSourceRectOffset);
} }
/// <summary> /// <summary>A very verbose asset drawer.</summary>
/// A very verbose asset drawer. public virtual void draw(SpriteBatch b, ExtendedNpc npc, Vector2 position, Rectangle sourceRectangle, Color color, float alpha, Vector2 origin, float scale, SpriteEffects effects, float layerDepth)
/// </summary>
/// <param name="b"></param>
/// <param name="npc"></param>
/// <param name="position"></param>
/// <param name="sourceRectangle"></param>
/// <param name="color"></param>
/// <param name="alpha"></param>
/// <param name="origin"></param>
/// <param name="scale"></param>
/// <param name="effects"></param>
/// <param name="layerDepth"></param>
public virtual void draw(SpriteBatch b, ExtendedNPC npc, Vector2 position, Rectangle sourceRectangle, Color color, float alpha, Vector2 origin, float scale, SpriteEffects effects, float layerDepth)
{ {
this.currentAnimation.draw(b, npc, position, sourceRectangle, color, alpha, origin, scale, effects, layerDepth); this.currentAnimation.draw(b, npc, position, sourceRectangle, color, alpha, origin, scale, effects, layerDepth);
} }
/// <summary> /// <summary>Animates the current animation for the current sprite.</summary>
/// Animates the current animation for the current sprite. public virtual void Animate(float interval, bool loop = true)
/// </summary>
/// <param name="interval"></param>
/// <param name="loop"></param>
public virtual void Animate(float interval, bool loop=true)
{ {
this.currentAnimation.Animate(interval,loop); this.currentAnimation.Animate(interval, loop);
} }
/// <summary>Wrapper for a draw function that accepts rectangles to be null.</summary>
/// <summary> public virtual void draw(SpriteBatch b, ExtendedNpc extendedNPC, Vector2 position, Rectangle? v1, Color white, float rotation, Vector2 origin, float scale, SpriteEffects spriteEffects, float v3)
/// Wrapper for a draw function that accepts rectangles to be null.
/// </summary>
/// <param name="b"></param>
/// <param name="extendedNPC"></param>
/// <param name="vector21"></param>
/// <param name="v1"></param>
/// <param name="white"></param>
/// <param name="rotation"></param>
/// <param name="vector22"></param>
/// <param name="v2"></param>
/// <param name="spriteEffects"></param>
/// <param name="v3"></param>
public virtual void draw(SpriteBatch b, ExtendedNPC extendedNPC, Vector2 position, Rectangle? v1, Color white, float rotation, Vector2 origin, float scale, SpriteEffects spriteEffects, float v3)
{ {
this.draw(b, extendedNPC, position, new Rectangle(0,0,16,32), white, rotation, origin, scale, spriteEffects, v3); this.draw(b, extendedNPC, position, new Rectangle(0, 0, 16, 32), white, rotation, origin, scale, spriteEffects, v3);
} }
} }
} }

View File

@ -1,49 +1,32 @@
using CustomNPCFramework.Framework.NPCS; using CustomNPCFramework.Framework.NPCS;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.ModularNPCS namespace CustomNPCFramework.Framework.ModularNpcs
{ {
/// <summary> /// <summary>Used as a wrapper for npc portraits.</summary>
/// Used as a wrapper for npc portraits.
/// </summary>
public class Portrait public class Portrait
{ {
/// <summary> /// <summary>Used to display the npc portrait.</summary>
/// Used to display the npc portrait.
/// </summary>
public Texture2D portrait; public Texture2D portrait;
/// <summary>
/// Used to hold the path to the texture to use for the npc portrait. /// <summary>Used to hold the path to the texture to use for the npc portrait.</summary>
/// </summary>
public string relativePath; public string relativePath;
/// <summary> /// <summaryConstruct an instance.</summary>
/// A class for handling portraits.
/// </summary>
/// <param name="path">The full path to the file.</param> /// <param name="path">The full path to the file.</param>
public Portrait(string path) public Portrait(string path)
{ {
this.relativePath =Class1.getRelativeDirectory(path); this.relativePath = Class1.getRelativeDirectory(path);
this.portrait=Class1.ModHelper.Content.Load<Texture2D>(path); this.portrait = Class1.ModHelper.Content.Load<Texture2D>(path);
} }
/// <summary> /// <summary>Sets the npc's portrait to be this portrait texture.</summary>
/// Sets the npc's portrait to be this portrait texture. public void setCharacterPortraitFromThis(ExtendedNpc npc)
/// </summary>
/// <param name="npc"></param>
public void setCharacterPortraitFromThis(ExtendedNPC npc)
{ {
npc.Portrait = this.portrait; npc.Portrait = this.portrait;
} }
/// <summary> /// <summary>Reloads the texture for the NPC portrait.</summary>
/// Reloads the texture for the NPC portrait.
/// </summary>
public void reload() public void reload()
{ {
this.portrait = Class1.ModHelper.Content.Load<Texture2D>(this.relativePath); this.portrait = Class1.ModHelper.Content.Load<Texture2D>(this.relativePath);

View File

@ -1,32 +1,19 @@
using CustomNPCFramework.Framework.ModularNPCS.ModularRenderers;
using CustomNPCFramework.Framework.NPCS; using CustomNPCFramework.Framework.NPCS;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using StardewValley; using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.ModularNPCS namespace CustomNPCFramework.Framework.ModularNpcs
{ {
/// <summary> /// <summary>Used as a wrapper for the npcs to hold sprite information.</summary>
/// Used as a wrapper for the npcs to hold sprite information.
/// </summary>
public class Sprite public class Sprite
{ {
/// <summary> /// <summary>The actual sprite to draw for the npc.</summary>
/// The actual sprite to draw for the npc.
/// </summary>
public AnimatedSprite sprite; public AnimatedSprite sprite;
/// <summary>
/// The path to the texture to use for the animated sprite. /// <summary>The path to the texture to use for the animated sprite.</summary>
/// </summary>
public string relativePath; public string relativePath;
/// <summary> /// <summary>Construct an instance.</summary>
/// A class for handling character sprites.
/// </summary>
/// <param name="path">The full path to the file.</param> /// <param name="path">The full path to the file.</param>
public Sprite(string path) public Sprite(string path)
{ {
@ -34,7 +21,7 @@ namespace CustomNPCFramework.Framework.ModularNPCS
{ {
this.relativePath = Class1.getShortenedDirectory(path); this.relativePath = Class1.getShortenedDirectory(path);
} }
catch(Exception err) catch
{ {
this.relativePath = path; this.relativePath = path;
} }
@ -42,11 +29,11 @@ namespace CustomNPCFramework.Framework.ModularNPCS
{ {
this.sprite = new AnimatedSprite(); this.sprite = new AnimatedSprite();
Texture2D text = Class1.ModHelper.Content.Load<Texture2D>(this.relativePath); Texture2D text = Class1.ModHelper.Content.Load<Texture2D>(this.relativePath);
var reflect=Class1.ModHelper.Reflection.GetField<Texture2D>(this.sprite, "Texture", true); var reflect = Class1.ModHelper.Reflection.GetField<Texture2D>(this.sprite, "Texture", true);
reflect.SetValue(text); reflect.SetValue(text);
} }
catch(Exception err) catch
{ {
this.sprite = new AnimatedSprite(); this.sprite = new AnimatedSprite();
Texture2D text = Class1.ModHelper.Content.Load<Texture2D>(this.relativePath); Texture2D text = Class1.ModHelper.Content.Load<Texture2D>(this.relativePath);
@ -57,9 +44,7 @@ namespace CustomNPCFramework.Framework.ModularNPCS
this.sprite.SpriteHeight = this.sprite.Texture.Height; this.sprite.SpriteHeight = this.sprite.Texture.Height;
} }
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor.
/// </summary>
/// <param name="path">Used to hold the path to the asset.</param> /// <param name="path">Used to hold the path to the asset.</param>
/// <param name="texture">Used to assign the texture to the sprite from a pre-loaded asset.</param> /// <param name="texture">Used to assign the texture to the sprite from a pre-loaded asset.</param>
public Sprite(string path, string texture) public Sprite(string path, string texture)
@ -70,75 +55,42 @@ namespace CustomNPCFramework.Framework.ModularNPCS
this.sprite.SpriteHeight = this.sprite.Texture.Height; this.sprite.SpriteHeight = this.sprite.Texture.Height;
} }
/// <summary> /// <summary>Sets the npc's portrait to be this portrait texture.</summary>
/// Sets the npc's portrait to be this portrait texture. public void setCharacterSpriteFromThis(ExtendedNpc npc)
/// </summary>
/// <param name="npc"></param>
public void setCharacterSpriteFromThis(ExtendedNPC npc)
{ {
npc.Sprite = this.sprite; npc.Sprite = this.sprite;
} }
/// <summary> /// <summary>Reloads the texture for the NPC portrait.</summary>
/// Reloads the texture for the NPC portrait.
/// </summary>
public void reload() public void reload()
{ {
var text=CustomNPCFramework.Class1.ModHelper.Reflection.GetField<Texture2D>(this.sprite.Texture, "Texture", true); var text = Class1.ModHelper.Reflection.GetField<Texture2D>(this.sprite.Texture, "Texture", true);
Texture2D loaded= Class1.ModHelper.Content.Load<Texture2D>(this.relativePath); Texture2D loaded = Class1.ModHelper.Content.Load<Texture2D>(this.relativePath);
text.SetValue(loaded); text.SetValue(loaded);
} }
/// <summary> /// <summary>Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc.</summary>
/// Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc. public void setLeft(ExtendedNpc npc)
/// </summary>
/// <param name="npc"></param>
public void setLeft(ExtendedNPC npc)
{ {
if (npc.characterRenderer == null) npc.characterRenderer?.setLeft();
{
return;
}
else npc.characterRenderer.setLeft();
} }
/// <summary> /// <summary>Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc.</summary>
/// Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc. public void setRight(ExtendedNpc npc)
/// </summary>
/// <param name="npc"></param>
public void setRight(ExtendedNPC npc)
{ {
if (npc.characterRenderer == null) npc.characterRenderer?.setRight();
{
return;
}
else npc.characterRenderer.setRight();
} }
/// <summary> /// <summary>Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc.</summary>
/// Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc. public void setDown(ExtendedNpc npc)
/// </summary>
/// <param name="npc"></param>
public void setDown(ExtendedNPC npc)
{ {
if (npc.characterRenderer == null) npc.characterRenderer?.setDown();
{
return;
}
else npc.characterRenderer.setDown();
} }
/// <summary> /// <summary>Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc.</summary>
/// Set's the npc's sprites to face left IF and only if there is a non-null modular Renderer attached to the npc. public void setUp(ExtendedNpc npc)
/// </summary>
/// <param name="npc"></param>
public void setUp(ExtendedNPC npc)
{ {
if (npc.characterRenderer == null) npc.characterRenderer?.setUp();
{
return;
}
else npc.characterRenderer.setUp();
} }
} }
} }

View File

@ -1,77 +1,59 @@
using CustomNPCFramework.Framework.Enums;
using StardewValley;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using CustomNPCFramework.Framework.Enums;
using System.Threading.Tasks; using StardewValley;
namespace CustomNPCFramework.Framework namespace CustomNPCFramework.Framework
{ {
/// <summary> /// <summary>Used as a class to hold all of the possible NPC names.</summary>
/// Used as a class to hold all of the possible npc names. public class NpcNames
/// </summary>
public class NPCNames
{ {
/// <summary> /// <summary>Holds all of the NPC male names.</summary>
/// Holds all of the npc male names. public static List<string> maleNames = new List<string>
/// </summary>
public static List<string> maleNames = new List<string>()
{ {
"Freddy", "Freddy",
"Josh", "Josh",
"Ash" "Ash"
}; };
/// <summary> /// <summary>Holds all of the NPC female names.</summary>
/// Holds all of the npc female names. public static List<string> femaleNames = new List<string>
/// </summary>
public static List<string> femaleNames = new List<string>()
{ {
"Rebecca", "Rebecca",
"Sierra", "Sierra",
"Lisa" "Lisa"
}; };
/// <summary> /// <summary>Holds all of the NPC gender non-binary names.</summary>
/// Holds all of the npc gender non-binary names. public static List<string> otherGenderNames = new List<string>
/// </summary>
public static List<string> otherGenderNames = new List<string>()
{ {
"Jayden", "Jayden",
"Ryanne", "Ryanne",
"Skylar" "Skylar"
}; };
/// <summary> /// <summary>Get a gender appropriate name from the pool of NPC names.</summary>
/// Get a gender appropriate name from the pool of npc names. public static string getRandomNpcName(Genders gender)
/// </summary> {
/// <param name="gender"></param> if (gender == Genders.female)
/// <returns></returns>
public static string getRandomNPCName(Genders gender)
{ {
if (gender == Genders.female) {
int rand = Game1.random.Next(0, femaleNames.Count - 1); int rand = Game1.random.Next(0, femaleNames.Count - 1);
return femaleNames.ElementAt(rand); return femaleNames.ElementAt(rand);
} }
if (gender == Genders.male) if (gender == Genders.male)
{ {
int rand = Game1.random.Next(0, maleNames.Count - 1); int rand = Game1.random.Next(0, maleNames.Count - 1);
return maleNames.ElementAt(rand); return maleNames.ElementAt(rand);
} }
if (gender == Genders.other) if (gender == Genders.other)
{ {
int rand = Game1.random.Next(0, otherGenderNames.Count - 1); int rand = Game1.random.Next(0, otherGenderNames.Count - 1);
return otherGenderNames.ElementAt(rand); return otherGenderNames.ElementAt(rand);
} }
return ""; return "";
} }
} }
} }

View File

@ -1,35 +1,22 @@
using CustomNPCFramework.Framework.Enums; using System;
using CustomNPCFramework.Framework.ModularNPCS; using CustomNPCFramework.Framework.Enums;
using CustomNPCFramework.Framework.ModularNPCS.ModularRenderers; using CustomNPCFramework.Framework.ModularNpcs;
using CustomNPCFramework.Framework.ModularNpcs.ModularRenderers;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using StardewValley; using StardewValley;
using StardewValley.Buildings;
using StardewValley.Characters;
using StardewValley.Locations;
using StardewValley.Menus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using xTile.Dimensions;
using xTile.ObjectModel;
using xTile.Tiles;
namespace CustomNPCFramework.Framework.NPCS namespace CustomNPCFramework.Framework.NPCS
{ {
/// <summary> // TODO:
/// TODO: Add in an resource loader for all of the character graphics and use it to populate some character graphics. // - Add in an resource loader for all of the character graphics and use it to populate some character graphics.
/// Make .json way to load in assets to the mod. // - Make .json way to load in assets to the mod.
/// Organize it all. // - Organize it all.
/// Profit??? // - Profit???
/// </summary>
public class ExtendedNPC :StardewValley.NPC public class ExtendedNpc : NPC
{ {
/// <summary> /// <summary>The custom character renderer for this npc.</summary>
/// The custom character renderer for this npc.
/// </summary>
public BasicRenderer characterRenderer; public BasicRenderer characterRenderer;
public bool hasBeenKissedToday; public bool hasBeenKissedToday;
public Point previousEndPoint; public Point previousEndPoint;
@ -37,122 +24,89 @@ namespace CustomNPCFramework.Framework.NPCS
public bool hasSaidAfternoonDialogue; public bool hasSaidAfternoonDialogue;
public int timeAfterSquare; public int timeAfterSquare;
/// <summary> /// <summary>Used to hold sprite information to be used in the case the npc renderer is null.</summary>
/// Used to hold sprite information to be used in the case the npc renderer is null.
/// </summary>
public Sprite spriteInformation; public Sprite spriteInformation;
/// <summary> /// <summary>Used to hold the portrait information for the npc and display it.</summary>
/// Used to hold the portrait information for the npc and display it.
/// </summary>
public Portrait portraitInformation; public Portrait portraitInformation;
/// <summary> /// <summary>The default location for this npc to reside in.</summary>
/// The default location for this npc to reside in.
/// </summary>
public GameLocation defaultLocation; public GameLocation defaultLocation;
/// <summary> /// <summary>Construct an instance.</summary>
/// Empty Constructor. public ExtendedNpc() { }
/// </summary>
public ExtendedNPC() :base()
{
}
/// <summary> /// <summary>Construct an instance.</summary>
/// Non modular npc Constructor.
/// </summary>
/// <param name="sprite">The sprite for the character.</param> /// <param name="sprite">The sprite for the character.</param>
/// <param name="position">The position of the npc on the map.</param> /// <param name="position">The position of the npc on the map.</param>
/// <param name="facingDirection">The direction of the npc</param> /// <param name="facingDirection">The direction of the npc</param>
/// <param name="name">The name of the npc.</param> /// <param name="name">The name of the npc.</param>
public ExtendedNPC(Sprite sprite, Vector2 position, int facingDirection, string name) : base(sprite.sprite, position, facingDirection, name, null) public ExtendedNpc(Sprite sprite, Vector2 position, int facingDirection, string name)
: base(sprite.sprite, position, facingDirection, name)
{ {
this.characterRenderer = null; this.characterRenderer = null;
this.Portrait = (Texture2D)null; this.Portrait = null;
this.portraitInformation = null; this.portraitInformation = null;
this.spriteInformation = sprite; this.spriteInformation = sprite;
if (this.spriteInformation != null) this.spriteInformation?.setCharacterSpriteFromThis(this);
{
this.spriteInformation.setCharacterSpriteFromThis(this);
}
this.swimming.Value = false; this.swimming.Value = false;
} }
/// <summary> /// <summary>Construct an instance.</summary>
/// Non modular npc Constructor.
/// </summary>
/// <param name="sprite">The sprite for the character.</param> /// <param name="sprite">The sprite for the character.</param>
/// <param name="portrait">The portrait texture for this npc.</param> /// <param name="portrait">The portrait texture for this npc.</param>
/// <param name="position">The position of the npc on the map.</param> /// <param name="position">The position of the npc on the map.</param>
/// <param name="facingDirection">The direction of the npc</param> /// <param name="facingDirection">The direction of the npc</param>
/// <param name="name">The name of the npc.</param> /// <param name="name">The name of the npc.</param>
public ExtendedNPC(Sprite sprite, Portrait portrait, Vector2 position, int facingDirection, string name) : base(sprite.sprite, position, facingDirection, name, null) public ExtendedNpc(Sprite sprite, Portrait portrait, Vector2 position, int facingDirection, string name)
: base(sprite.sprite, position, facingDirection, name)
{ {
this.characterRenderer = null; this.characterRenderer = null;
this.portraitInformation = portrait; this.portraitInformation = portrait;
if (this.portraitInformation != null) this.portraitInformation?.setCharacterPortraitFromThis(this);
{
this.portraitInformation.setCharacterPortraitFromThis(this);
}
this.spriteInformation = sprite; this.spriteInformation = sprite;
this.spriteInformation.setCharacterSpriteFromThis(this); this.spriteInformation.setCharacterSpriteFromThis(this);
this.swimming.Value = false; this.swimming.Value = false;
} }
/// <summary> /// <summary>Construct an instance.</summary>
/// Modular npc constructor.
/// </summary>
/// <param name="sprite">The sprite for the character to use incase the renderer is null.</param> /// <param name="sprite">The sprite for the character to use incase the renderer is null.</param>
/// <param name="renderer">The custom npc render. Used to draw the npcfrom a collection of assets.</param> /// <param name="renderer">The custom npc render. Used to draw the npcfrom a collection of assets.</param>
/// <param name="portrait">The portrait texture for this npc.</param>
/// <param name="position">The position of the npc on the map.</param> /// <param name="position">The position of the npc on the map.</param>
/// <param name="facingDirection">The direction of the npc</param> /// <param name="facingDirection">The direction of the npc</param>
/// <param name="name">The name of the npc.</param> /// <param name="name">The name of the npc.</param>
public ExtendedNPC(Sprite sprite,BasicRenderer renderer,Vector2 position,int facingDirection,string name): base(sprite.sprite, position, facingDirection, name, null) public ExtendedNpc(Sprite sprite, BasicRenderer renderer, Vector2 position, int facingDirection, string name)
: base(sprite.sprite, position, facingDirection, name)
{ {
this.characterRenderer = renderer; this.characterRenderer = renderer;
this.Portrait = (Texture2D)null; this.Portrait = null;
this.portraitInformation = null; this.portraitInformation = null;
this.spriteInformation = sprite; this.spriteInformation = sprite;
if (this.spriteInformation != null) this.spriteInformation?.setCharacterSpriteFromThis(this);
{
this.spriteInformation.setCharacterSpriteFromThis(this);
}
this.swimming.Value = false; this.swimming.Value = false;
} }
/// <summary> /// <summary>Construct an instance.</summary>
/// Modular constructor for the npc.
/// </summary>
/// <param name="sprite">The sprite for the npc to use incase the renderer is null.</param> /// <param name="sprite">The sprite for the npc to use incase the renderer is null.</param>
/// <param name="renderer">The custom npc renderer used to draw the npc from the collection of textures.</param> /// <param name="renderer">The custom npc renderer used to draw the npc from the collection of textures.</param>
/// <param name="portrait">The portrait texture for the npc.</param> /// <param name="portrait">The portrait texture for the npc.</param>
/// <param name="position">The positon for the npc to be.</param> /// <param name="position">The positon for the npc to be.</param>
/// <param name="facingDirection">The direction for the npc to face.</param> /// <param name="facingDirection">The direction for the npc to face.</param>
/// <param name="name">The name for the npc.</param> /// <param name="name">The name for the npc.</param>
public ExtendedNPC(Sprite sprite,BasicRenderer renderer,Portrait portrait, Vector2 position, int facingDirection, string name) : base(sprite.sprite, position, facingDirection, name, null) public ExtendedNpc(Sprite sprite, BasicRenderer renderer, Portrait portrait, Vector2 position, int facingDirection, string name)
: base(sprite.sprite, position, facingDirection, name)
{ {
this.characterRenderer = renderer; this.characterRenderer = renderer;
this.portraitInformation = portrait; this.portraitInformation = portrait;
if (this.portraitInformation != null) this.portraitInformation?.setCharacterPortraitFromThis(this);
{
this.portraitInformation.setCharacterPortraitFromThis(this);
}
this.spriteInformation = sprite; this.spriteInformation = sprite;
if (this.spriteInformation != null) this.spriteInformation?.setCharacterSpriteFromThis(this);
{
this.spriteInformation.setCharacterSpriteFromThis(this);
}
this.swimming.Value = false; this.swimming.Value = false;
} }
/// <summary> /// <summary>Used to reload the sprite for the npc.</summary>
/// Used to reload the sprite for the npc.
/// </summary>
public void reloadSprite() public void reloadSprite()
{ {
if (this.characterRenderer == null) if (this.characterRenderer == null)
{ {
this.spriteInformation.reload(); this.spriteInformation.reload();
@ -160,10 +114,9 @@ namespace CustomNPCFramework.Framework.NPCS
{ {
this.portraitInformation.reload(); this.portraitInformation.reload();
} }
catch (Exception ex) catch
{ {
ex.ToString(); this.Portrait = null;
this.Portrait = (Texture2D)null;
} }
} }
else else
@ -173,14 +126,12 @@ namespace CustomNPCFramework.Framework.NPCS
{ {
this.portraitInformation.reload(); this.portraitInformation.reload();
} }
catch (Exception ex) catch
{ {
ex.ToString(); this.Portrait = null;
this.Portrait = (Texture2D)null;
} }
} }
int num = this.IsInvisible ? 1 : 0; if (!Game1.newDay && Game1.gameMode != 6)
if (!Game1.newDay && (int)Game1.gameMode != 6)
return; return;
this.faceDirection(this.DefaultFacingDirection); this.faceDirection(this.DefaultFacingDirection);
this.scheduleTimeToTry = 9999999; this.scheduleTimeToTry = 9999999;
@ -191,161 +142,130 @@ namespace CustomNPCFramework.Framework.NPCS
if (this.isMarried()) if (this.isMarried())
this.marriageDuties(); this.marriageDuties();
bool flag = Utility.isFestivalDay(Game1.dayOfMonth, Game1.currentSeason);
try try
{ {
this.displayName = this.Name; this.displayName = this.Name;
} }
catch (Exception ex) catch { }
{
ex.ToString();
} }
} /// <summary>Functionality used when interacting with the npc.</summary>
public override bool checkAction(Farmer who, GameLocation l)
/// <summary>
/// Functionality used when interacting with the npc.
/// </summary>
/// <param name="who"></param>
/// <param name="l"></param>
/// <returns></returns>
public override bool checkAction(StardewValley.Farmer who, GameLocation l)
{ {
base.checkAction(who, l); base.checkAction(who, l);
return false; return false;
} }
/// <summary> /// <summary>Used to move the npc. Different code is used depending if the character renderer is null or not.</summary>
/// Used to move the npc. Different code is used depending if the character renderer is null or not.
/// </summary>
/// <param name="time"></param>
/// <param name="viewport"></param>
/// <param name="currentLocation"></param>
public override void MovePosition(GameTime time, xTile.Dimensions.Rectangle viewport, GameLocation currentLocation) public override void MovePosition(GameTime time, xTile.Dimensions.Rectangle viewport, GameLocation currentLocation)
{ {
if (this.characterRenderer != null) if (this.characterRenderer != null)
{ this.ModularMovement(time, viewport, currentLocation);
ModularMovement(time,viewport,currentLocation);
}
else else
{ this.NonModularMovement(time, viewport, currentLocation);
NonModularMovement(time,viewport,currentLocation);
}
return;
} }
/// <summary> /// <summary>Set's the npc to move a certain direction and then executes the movement.</summary>
/// Set's the npc to move a certain direction and then executes the movement. /// <param name="moveDirection">The direction to move the npc.</param>
/// </summary>
/// <param name="time"></param>
/// <param name="viewport"></param>
/// <param name="currentLocation"></param>
/// <param name="MoveDirection">The direction to move the npc.</param>
/// <param name="Move">Set's the npc's sprite to halt if Move=false. Else set it to true.</param> /// <param name="Move">Set's the npc's sprite to halt if Move=false. Else set it to true.</param>
public virtual void SetMovingAndMove(GameTime time, xTile.Dimensions.Rectangle viewport, GameLocation currentLocation, Direction MoveDirection, bool Move=true) public virtual void SetMovingAndMove(GameTime time, xTile.Dimensions.Rectangle viewport, GameLocation currentLocation, Direction moveDirection, bool Move = true)
{ {
if (MoveDirection == Direction.down) this.SetMovingDown(Move); switch (moveDirection)
if (MoveDirection == Direction.left) this.SetMovingLeft(Move); {
if (MoveDirection == Direction.up) this.SetMovingUp(Move); case Direction.down:
if (MoveDirection == Direction.right) this.SetMovingRight(Move); this.SetMovingDown(Move);
break;
case Direction.left:
this.SetMovingLeft(Move);
break;
case Direction.up:
this.SetMovingUp(Move);
break;
case Direction.right:
this.SetMovingRight(Move);
break;
}
this.MovePosition(time, viewport, currentLocation); this.MovePosition(time, viewport, currentLocation);
} }
/// <summary> /// <summary>USed to move the npc if the character renderer is null.</summary>
/// USed to move the npc if the character renderer is null.
/// </summary>
/// <param name="time"></param>
/// <param name="viewport"></param>
/// <param name="location"></param>
public virtual void NonModularMovement(GameTime time, xTile.Dimensions.Rectangle viewport, GameLocation location) public virtual void NonModularMovement(GameTime time, xTile.Dimensions.Rectangle viewport, GameLocation location)
{ {
base.MovePosition(time, viewport, currentLocation); base.MovePosition(time, viewport, this.currentLocation);
return;
} }
/// <summary> /// <summary>Used to determine if the npc can move past the next location.</summary>
/// Used to determine if the npc can move past the next location.
/// </summary>
/// <param name="viewport"></param>
/// <returns></returns>
public virtual bool canMovePastNextLocation(xTile.Dimensions.Rectangle viewport) public virtual bool canMovePastNextLocation(xTile.Dimensions.Rectangle viewport)
{ {
//Up //Up
if (!currentLocation.isTilePassable(this.nextPosition(0), viewport) || !this.willDestroyObjectsUnderfoot) if (!this.currentLocation.isTilePassable(this.nextPosition(0), viewport) || !this.willDestroyObjectsUnderfoot)
{
return false; return false;
}
//Right //Right
if (!currentLocation.isTilePassable(this.nextPosition(1), viewport) || !this.willDestroyObjectsUnderfoot) if (!this.currentLocation.isTilePassable(this.nextPosition(1), viewport) || !this.willDestroyObjectsUnderfoot)
{
return false; return false;
}
//Down //Down
if (!currentLocation.isTilePassable(this.nextPosition(2), viewport) || !this.willDestroyObjectsUnderfoot) if (!this.currentLocation.isTilePassable(this.nextPosition(2), viewport) || !this.willDestroyObjectsUnderfoot)
{
return false; return false;
}
//Left //Left
if (!currentLocation.isTilePassable(this.nextPosition(3), viewport) || !this.willDestroyObjectsUnderfoot) if (!this.currentLocation.isTilePassable(this.nextPosition(3), viewport) || !this.willDestroyObjectsUnderfoot)
{
return false; return false;
}
return true; return true;
} }
/// <summary> /// <summary>Used to move the npc if the character renderer is valid. Handles animating all of the sprites associated with the renderer.</summary>
/// Used to move the npc if the character renderer is valid. Handles animating all of the sprites associated with the renderer.
/// </summary>
/// <param name="time"></param>
/// <param name="viewport"></param>
/// <param name="location"></param>
/// <param name="interval"></param>
public virtual void ModularMovement(GameTime time, xTile.Dimensions.Rectangle viewport, GameLocation location, float interval = 1000f) public virtual void ModularMovement(GameTime time, xTile.Dimensions.Rectangle viewport, GameLocation location, float interval = 1000f)
{ {
this.characterRenderer.setAnimation(AnimationKeys.walkingKey); this.characterRenderer.setAnimation(AnimationKeys.walkingKey);
if (this.canMovePastNextLocation(viewport) == false) if (!this.canMovePastNextLocation(viewport))
{ {
this.Halt(); this.Halt();
return; return;
} }
if (this.GetType() == typeof(FarmAnimal)) if (this.GetType() == typeof(FarmAnimal))
this.willDestroyObjectsUnderfoot = false; this.willDestroyObjectsUnderfoot = false;
if ((double)this.xVelocity != 0.0 || (double)this.yVelocity != 0.0) if (this.xVelocity != 0.0 || this.yVelocity != 0.0)
{ {
Microsoft.Xna.Framework.Rectangle boundingBox = this.GetBoundingBox(); var boundingBox = this.GetBoundingBox();
boundingBox.X += (int)this.xVelocity; boundingBox.X += (int)this.xVelocity;
boundingBox.Y -= (int)this.yVelocity; boundingBox.Y -= (int)this.yVelocity;
if (currentLocation == null || !currentLocation.isCollidingPosition(boundingBox, viewport, false, 0, false, this)) if (this.currentLocation == null || !this.currentLocation.isCollidingPosition(boundingBox, viewport, false, 0, false, this))
{ {
this.position.X += this.xVelocity; this.position.X += this.xVelocity;
this.position.Y -= this.yVelocity; this.position.Y -= this.yVelocity;
} }
this.xVelocity = (float)(int)((double)this.xVelocity - (double)this.xVelocity / 2.0); this.xVelocity = (int)(this.xVelocity - this.xVelocity / 2.0);
this.yVelocity = (float)(int)((double)this.yVelocity - (double)this.yVelocity / 2.0); this.yVelocity = (int)(this.yVelocity - this.yVelocity / 2.0);
} }
else if (this.moveUp) else if (this.moveUp)
{ {
if (currentLocation == null || !currentLocation.isCollidingPosition(this.nextPosition(0), viewport, false, 0, false, this) || this.isCharging) if (this.currentLocation == null || !this.currentLocation.isCollidingPosition(this.nextPosition(0), viewport, false, 0, false, this) || this.isCharging)
{ {
this.position.Y -= (float)(this.speed + this.addedSpeed); this.position.Y -= this.speed + this.addedSpeed;
if (!this.ignoreMovementAnimation) if (!this.ignoreMovementAnimation)
{ {
this.spriteInformation.setUp(this); this.spriteInformation.setUp(this);
this.characterRenderer.Animate(interval,true); this.characterRenderer.Animate(interval);
//this.sprite.AnimateUp(time, (this.speed - 2 + this.addedSpeed) * -25, Utility.isOnScreen(this.getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : ""); //this.sprite.AnimateUp(time, (this.speed - 2 + this.addedSpeed) * -25, Utility.isOnScreen(this.getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : "");
this.faceDirection(0); this.faceDirection(0);
} }
} }
else if (!currentLocation.isTilePassable(this.nextPosition(0), viewport) || !this.willDestroyObjectsUnderfoot) else if (!this.currentLocation.isTilePassable(this.nextPosition(0), viewport) || !this.willDestroyObjectsUnderfoot)
this.Halt(); this.Halt();
else if (this.willDestroyObjectsUnderfoot) else if (this.willDestroyObjectsUnderfoot)
{ {
Vector2 vector2 = new Vector2((float)(this.getStandingX() / Game1.tileSize), (float)(this.getStandingY() / Game1.tileSize - 1)); Vector2 vector2 = new Vector2(this.getStandingX() / Game1.tileSize, this.getStandingY() / Game1.tileSize - 1);
if (currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(0), true)) if (this.currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(0), true))
{ {
this.doEmote(12, true); this.doEmote(12);
this.position.Y -= (float)(this.speed + this.addedSpeed); this.position.Y -= this.speed + this.addedSpeed;
} }
else else
this.blockedInterval = this.blockedInterval + time.ElapsedGameTime.Milliseconds; this.blockedInterval = this.blockedInterval + time.ElapsedGameTime.Milliseconds;
@ -353,27 +273,27 @@ namespace CustomNPCFramework.Framework.NPCS
} }
else if (this.moveRight) else if (this.moveRight)
{ {
if (currentLocation == null || !currentLocation.isCollidingPosition(this.nextPosition(1), viewport, false, 0, false, this) || this.isCharging) if (this.currentLocation == null || !this.currentLocation.isCollidingPosition(this.nextPosition(1), viewport, false, 0, false, this) || this.isCharging)
{ {
this.position.X += (float)(this.speed + this.addedSpeed); this.position.X += this.speed + this.addedSpeed;
if (!this.ignoreMovementAnimation) if (!this.ignoreMovementAnimation)
{ {
this.spriteInformation.setRight(this); this.spriteInformation.setRight(this);
this.characterRenderer.Animate(interval,true); this.characterRenderer.Animate(interval);
//this.spriteInformation.sprite.Animate(time, 0, 3, 1f); //this.spriteInformation.sprite.Animate(time, 0, 3, 1f);
//this.sprite.AnimateRight(time, (this.speed - 2 + this.addedSpeed) * -25, Utility.isOnScreen(this.getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : ""); //this.sprite.AnimateRight(time, (this.speed - 2 + this.addedSpeed) * -25, Utility.isOnScreen(this.getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : "");
this.faceDirection(1); this.faceDirection(1);
} }
} }
else if (!currentLocation.isTilePassable(this.nextPosition(1), viewport) || !this.willDestroyObjectsUnderfoot) else if (!this.currentLocation.isTilePassable(this.nextPosition(1), viewport) || !this.willDestroyObjectsUnderfoot)
this.Halt(); this.Halt();
else if (this.willDestroyObjectsUnderfoot) else if (this.willDestroyObjectsUnderfoot)
{ {
Vector2 vector2 = new Vector2((float)(this.getStandingX() / Game1.tileSize + 1), (float)(this.getStandingY() / Game1.tileSize)); Vector2 vector2 = new Vector2(this.getStandingX() / Game1.tileSize + 1, this.getStandingY() / Game1.tileSize);
if (currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(1), true)) if (this.currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(1), true))
{ {
this.doEmote(12, true); this.doEmote(12);
this.position.X += (float)(this.speed + this.addedSpeed); this.position.X += this.speed + this.addedSpeed;
} }
else else
this.blockedInterval = this.blockedInterval + time.ElapsedGameTime.Milliseconds; this.blockedInterval = this.blockedInterval + time.ElapsedGameTime.Milliseconds;
@ -381,27 +301,27 @@ namespace CustomNPCFramework.Framework.NPCS
} }
else if (this.moveDown) else if (this.moveDown)
{ {
if (currentLocation == null || !currentLocation.isCollidingPosition(this.nextPosition(2), viewport, false, 0, false, this) || this.isCharging) if (this.currentLocation == null || !this.currentLocation.isCollidingPosition(this.nextPosition(2), viewport, false, 0, false, this) || this.isCharging)
{ {
this.position.Y += (float)(this.speed + this.addedSpeed); this.position.Y += this.speed + this.addedSpeed;
if (!this.ignoreMovementAnimation) if (!this.ignoreMovementAnimation)
{ {
this.spriteInformation.setDown(this); this.spriteInformation.setDown(this);
this.characterRenderer.Animate(interval,true); this.characterRenderer.Animate(interval);
//this.spriteInformation.sprite.Animate(time, 0, 3, 1f); //this.spriteInformation.sprite.Animate(time, 0, 3, 1f);
//this.sprite.AnimateDown(time, (this.speed - 2 + this.addedSpeed) * -25, Utility.isOnScreen(this.getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : ""); //this.sprite.AnimateDown(time, (this.speed - 2 + this.addedSpeed) * -25, Utility.isOnScreen(this.getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : "");
this.faceDirection(2); this.faceDirection(2);
} }
} }
else if (!currentLocation.isTilePassable(this.nextPosition(2), viewport) || !this.willDestroyObjectsUnderfoot) else if (!this.currentLocation.isTilePassable(this.nextPosition(2), viewport) || !this.willDestroyObjectsUnderfoot)
this.Halt(); this.Halt();
else if (this.willDestroyObjectsUnderfoot) else if (this.willDestroyObjectsUnderfoot)
{ {
Vector2 vector2 = new Vector2((float)(this.getStandingX() / Game1.tileSize), (float)(this.getStandingY() / Game1.tileSize + 1)); Vector2 vector2 = new Vector2(this.getStandingX() / Game1.tileSize, this.getStandingY() / Game1.tileSize + 1);
if (currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(2), true)) if (this.currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(2), true))
{ {
this.doEmote(12, true); this.doEmote(12);
this.position.Y += (float)(this.speed + this.addedSpeed); this.position.Y += this.speed + this.addedSpeed;
} }
else else
this.blockedInterval = this.blockedInterval + time.ElapsedGameTime.Milliseconds; this.blockedInterval = this.blockedInterval + time.ElapsedGameTime.Milliseconds;
@ -409,35 +329,35 @@ namespace CustomNPCFramework.Framework.NPCS
} }
else if (this.moveLeft) else if (this.moveLeft)
{ {
if (currentLocation == null || !currentLocation.isCollidingPosition(this.nextPosition(3), viewport, false, 0, false, this) || this.isCharging) if (this.currentLocation == null || !this.currentLocation.isCollidingPosition(this.nextPosition(3), viewport, false, 0, false, this) || this.isCharging)
{ {
this.position.X -= (float)(this.speed + this.addedSpeed); this.position.X -= this.speed + this.addedSpeed;
if (!this.ignoreMovementAnimation) if (!this.ignoreMovementAnimation)
{ {
this.spriteInformation.setLeft(this); this.spriteInformation.setLeft(this);
this.characterRenderer.Animate(interval,true); this.characterRenderer.Animate(interval);
//this.spriteInformation.sprite.Animate(time, 0, 3, 1f); //this.spriteInformation.sprite.Animate(time, 0, 3, 1f);
//this.sprite.AnimateLeft(time, (this.speed - 2 + this.addedSpeed) * -25, Utility.isOnScreen(this.getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : ""); //this.sprite.AnimateLeft(time, (this.speed - 2 + this.addedSpeed) * -25, Utility.isOnScreen(this.getTileLocationPoint(), 1, currentLocation) ? "Cowboy_Footstep" : "");
this.faceDirection(3); this.faceDirection(3);
} }
} }
else if (!currentLocation.isTilePassable(this.nextPosition(3), viewport) || !this.willDestroyObjectsUnderfoot) else if (!this.currentLocation.isTilePassable(this.nextPosition(3), viewport) || !this.willDestroyObjectsUnderfoot)
this.Halt(); this.Halt();
else if (this.willDestroyObjectsUnderfoot) else if (this.willDestroyObjectsUnderfoot)
{ {
Vector2 vector2 = new Vector2((float)(this.getStandingX() / Game1.tileSize - 1), (float)(this.getStandingY() / Game1.tileSize)); Vector2 vector2 = new Vector2(this.getStandingX() / Game1.tileSize - 1, this.getStandingY() / Game1.tileSize);
if (currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(3), true)) if (this.currentLocation.characterDestroyObjectWithinRectangle(this.nextPosition(3), true))
{ {
this.doEmote(12, true); this.doEmote(12);
this.position.X -= (float)(this.speed + this.addedSpeed); this.position.X -= this.speed + this.addedSpeed;
} }
else else
this.blockedInterval = this.blockedInterval + time.ElapsedGameTime.Milliseconds; this.blockedInterval = this.blockedInterval + time.ElapsedGameTime.Milliseconds;
} }
} }
if (this.blockedInterval >= 3000 && (double)this.blockedInterval <= 3750.0 && !Game1.eventUp) if (this.blockedInterval >= 3000 && this.blockedInterval <= 3750.0 && !Game1.eventUp)
{ {
this.doEmote(Game1.random.NextDouble() < 0.5 ? 8 : 40, true); this.doEmote(Game1.random.NextDouble() < 0.5 ? 8 : 40);
this.blockedInterval = 3750; this.blockedInterval = 3750;
} }
else else
@ -450,33 +370,15 @@ namespace CustomNPCFramework.Framework.NPCS
} }
} }
/// <summary> /// <summary>Used to halt the npc sprite. Sets the npc's animation to the standing animation if the character renderer is not null.</summary>
/// Used to halt the npc sprite. Sets the npc's animation to the standing animation if the character renderer is not null.
/// </summary>
public override void Halt() public override void Halt()
{ {
if (this.characterRenderer != null) this.characterRenderer?.setAnimation(AnimationKeys.standingKey);
{
this.characterRenderer.setAnimation(AnimationKeys.standingKey);
}
base.Halt(); base.Halt();
} }
/// <summary> /// <summary>Pathfinding code.</summary>
/// Used to update npc information. public virtual void routeEndAnimationFinished(Farmer who)
/// </summary>
/// <param name="time"></param>
/// <param name="location"></param>
public override void update(GameTime time, GameLocation location)
{
base.update(time, location);
}
/// <summary>
/// Pathfinding code.
/// </summary>
/// <param name="who"></param>
public virtual void routeEndAnimationFinished(StardewValley.Farmer who)
{ {
this.doingEndOfRouteAnimation.Value = false; this.doingEndOfRouteAnimation.Value = false;
this.freezeMotion = false; this.freezeMotion = false;
@ -493,26 +395,15 @@ namespace CustomNPCFramework.Framework.NPCS
this.timeAfterSquare = Game1.timeOfDay; this.timeAfterSquare = Game1.timeOfDay;
} }
/// <summary> /// <summary>Pathfinding code.</summary>
/// Pathfinding code. public virtual void doAnimationAtEndOfScheduleRoute(Character c, GameLocation l) { }
/// </summary>
/// <param name="c"></param>
/// <param name="l"></param>
public virtual void doAnimationAtEndOfScheduleRoute(Character c, GameLocation l)
{
}
/// <summary> /// <summary>Pathfinding code.</summary>
/// Pathfinding code.
/// </summary>
/// <param name="behaviorName"></param>
public virtual void startRouteBehavior(string behaviorName) public virtual void startRouteBehavior(string behaviorName)
{ {
if (behaviorName.Length > 0 && (int)behaviorName[0] == 34) if (behaviorName.Length > 0 && (int)behaviorName[0] == 34)
{
this.endOfRouteMessage.Value = behaviorName.Replace("\"", ""); this.endOfRouteMessage.Value = behaviorName.Replace("\"", "");
}
else else
{ {
if (behaviorName.Contains("square_")) if (behaviorName.Contains("square_"))
@ -524,24 +415,20 @@ namespace CustomNPCFramework.Framework.NPCS
} }
else else
{ {
Utility.getGameLocationOfCharacter(this).temporarySprites.Add(new TemporaryAnimatedSprite("LooseSprites\\Cursors", new Microsoft.Xna.Framework.Rectangle(167, 1714, 19, 14), 100f, 3, 999999, new Vector2(2f, 3f) * (float)Game1.tileSize + new Vector2(7f, 12f) * (float)Game1.pixelZoom, false, false, 0.0002f, 0.0f, Color.White, (float)Game1.pixelZoom, 0.0f, 0.0f, 0.0f, false) Utility.getGameLocationOfCharacter(this).temporarySprites.Add(new TemporaryAnimatedSprite("LooseSprites\\Cursors", new Microsoft.Xna.Framework.Rectangle(167, 1714, 19, 14), 100f, 3, 999999, new Vector2(2f, 3f) * (float)Game1.tileSize + new Vector2(7f, 12f) * (float)Game1.pixelZoom, false, false, 0.0002f, 0.0f, Color.White, (float)Game1.pixelZoom, 0.0f, 0.0f, 0.0f)
{ {
id = 688f id = 688f
}); });
this.doEmote(52, true); this.doEmote(52);
} }
} }
} }
/// <summary> /// <summary>Occurs when the npc gets hit by the player.</summary>
/// Occurs when the npc gets hit by the player.
/// </summary>
/// <param name="who"></param>
/// <param name="location"></param>
public new void getHitByPlayer(StardewValley.Farmer who, GameLocation location) public new void getHitByPlayer(StardewValley.Farmer who, GameLocation location)
{ {
this.doEmote(12, true); this.doEmote(12);
if (who == null) if (who == null)
{ {
if (Game1.IsMultiplayer) if (Game1.IsMultiplayer)
@ -550,8 +437,7 @@ namespace CustomNPCFramework.Framework.NPCS
} }
if (who.friendshipData.ContainsKey(this.Name)) if (who.friendshipData.ContainsKey(this.Name))
{ {
Friendship f; who.friendshipData.TryGetValue(this.Name, out Friendship f);
who.friendshipData.TryGetValue(this.Name, out f);
f.Points -= 30; f.Points -= 30;
if (who.IsMainPlayer) if (who.IsMainPlayer)
{ {
@ -570,7 +456,7 @@ namespace CustomNPCFramework.Framework.NPCS
public override void dayUpdate(int dayOfMonth) public override void dayUpdate(int dayOfMonth)
{ {
if (this.currentLocation != null) if (this.currentLocation != null)
Game1.warpCharacter(this, this.DefaultMap, this.DefaultPosition / (float)Game1.tileSize); Game1.warpCharacter(this, this.DefaultMap, this.DefaultPosition / Game1.tileSize);
Game1.player.mailReceived.Remove(this.Name); Game1.player.mailReceived.Remove(this.Name);
Game1.player.mailReceived.Remove(this.Name + "Cooking"); Game1.player.mailReceived.Remove(this.Name + "Cooking");
this.doingEndOfRouteAnimation.Value = false; this.doingEndOfRouteAnimation.Value = false;
@ -582,18 +468,18 @@ namespace CustomNPCFramework.Framework.NPCS
this.hasSaidAfternoonDialogue = false; this.hasSaidAfternoonDialogue = false;
this.ignoreScheduleToday = false; this.ignoreScheduleToday = false;
this.Halt(); this.Halt();
this.controller = (PathFindController)null; this.controller = null;
this.temporaryController = (PathFindController)null; this.temporaryController = null;
this.DirectionsToNewLocation = (SchedulePathDescription)null; this.DirectionsToNewLocation = null;
this.faceDirection(this.DefaultFacingDirection); this.faceDirection(this.DefaultFacingDirection);
this.scheduleTimeToTry = 9999999; this.scheduleTimeToTry = 9999999;
this.previousEndPoint = new Point((int)this.DefaultPosition.X / Game1.tileSize, (int)this.DefaultPosition.Y / Game1.tileSize); this.previousEndPoint = new Point((int)this.DefaultPosition.X / Game1.tileSize, (int)this.DefaultPosition.Y / Game1.tileSize);
this.IsWalkingInSquare = false; this.IsWalkingInSquare = false;
this.returningToEndPoint = false; this.returningToEndPoint = false;
this.lastCrossroad = Microsoft.Xna.Framework.Rectangle.Empty; this.lastCrossroad = Rectangle.Empty;
if (this.isVillager()) if (this.isVillager())
this.Schedule = this.getSchedule(dayOfMonth); this.Schedule = this.getSchedule(dayOfMonth);
this.endOfRouteMessage.Value = (string)null; this.endOfRouteMessage.Value = null;
bool flag = Utility.isFestivalDay(dayOfMonth, Game1.currentSeason); bool flag = Utility.isFestivalDay(dayOfMonth, Game1.currentSeason);
if (!this.isMarried()) if (!this.isMarried())
return; return;
@ -602,18 +488,10 @@ namespace CustomNPCFramework.Framework.NPCS
//this.daysMarried = this.daysMarried + 1; //this.daysMarried = this.daysMarried + 1;
} }
/// <summary> /// <summary>Does effectively nothing.</summary>
/// Does effectively nothing. public new void setUpForOutdoorPatioActivity() { }
/// </summary>
public new void setUpForOutdoorPatioActivity()
{
}
/// <summary> /// <summary>Used to draw the npc with the custom renderer.</summary>
/// Used to draw the npc with the custom renderer.
/// </summary>
/// <param name="b"></param>
/// <param name="alpha"></param>
public virtual void drawModular(SpriteBatch b, float alpha = 1f) public virtual void drawModular(SpriteBatch b, float alpha = 1f)
{ {
if (this.characterRenderer == null || this.IsInvisible || !Utility.isOnScreen(this.position, 2 * Game1.tileSize)) if (this.characterRenderer == null || this.IsInvisible || !Utility.isOnScreen(this.position, 2 * Game1.tileSize))
@ -623,7 +501,7 @@ namespace CustomNPCFramework.Framework.NPCS
{ {
this.characterRenderer.setAnimation(AnimationKeys.swimmingKey); this.characterRenderer.setAnimation(AnimationKeys.swimmingKey);
this.characterRenderer.setDirection(this.facingDirection); this.characterRenderer.setDirection(this.facingDirection);
this.characterRenderer.draw(b,this,this.getLocalPosition(Game1.viewport) + new Vector2((float)(Game1.tileSize / 2), (float)(Game1.tileSize + Game1.tileSize / 4 + this.yJumpOffset * 2)) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero) - new Vector2(0.0f, this.yOffset), new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(this.Sprite.SourceRect.X, this.Sprite.SourceRect.Y, this.Sprite.SourceRect.Width, this.Sprite.SourceRect.Height / 2 - (int)((double)this.yOffset / (double)Game1.pixelZoom))), Color.White, this.rotation, new Vector2((float)(Game1.tileSize / 2), (float)(Game1.tileSize * 3 / 2)) / 4f, Math.Max(0.2f, this.Scale) * (float)Game1.pixelZoom, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, (float)this.getStandingY() / 10000f)); this.characterRenderer.draw(b, this, this.getLocalPosition(Game1.viewport) + new Vector2((float)(Game1.tileSize / 2), (float)(Game1.tileSize + Game1.tileSize / 4 + this.yJumpOffset * 2)) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero) - new Vector2(0.0f, this.yOffset), new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(this.Sprite.SourceRect.X, this.Sprite.SourceRect.Y, this.Sprite.SourceRect.Width, this.Sprite.SourceRect.Height / 2 - (int)((double)this.yOffset / (double)Game1.pixelZoom))), Color.White, this.rotation, new Vector2((float)(Game1.tileSize / 2), (float)(Game1.tileSize * 3 / 2)) / 4f, Math.Max(0.2f, this.Scale) * (float)Game1.pixelZoom, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, (float)this.getStandingY() / 10000f));
//Vector2 localPosition = this.getLocalPosition(Game1.viewport); //Vector2 localPosition = this.getLocalPosition(Game1.viewport);
//b.Draw(Game1.staminaRect, new Microsoft.Xna.Framework.Rectangle((int)localPosition.X + (int)this.yOffset + Game1.pixelZoom * 2, (int)localPosition.Y - 32 * Game1.pixelZoom + this.sprite.SourceRect.Height * Game1.pixelZoom + Game1.tileSize * 3 / 4 + this.yJumpOffset * 2 - (int)this.yOffset, this.sprite.SourceRect.Width * Game1.pixelZoom - (int)this.yOffset * 2 - Game1.pixelZoom * 4, Game1.pixelZoom), new Microsoft.Xna.Framework.Rectangle?(Game1.staminaRect.Bounds), Color.White * 0.75f, 0.0f, Vector2.Zero, SpriteEffects.None, (float)((double)this.getStandingY() / 10000.0 + 1.0 / 1000.0)); //b.Draw(Game1.staminaRect, new Microsoft.Xna.Framework.Rectangle((int)localPosition.X + (int)this.yOffset + Game1.pixelZoom * 2, (int)localPosition.Y - 32 * Game1.pixelZoom + this.sprite.SourceRect.Height * Game1.pixelZoom + Game1.tileSize * 3 / 4 + this.yJumpOffset * 2 - (int)this.yOffset, this.sprite.SourceRect.Width * Game1.pixelZoom - (int)this.yOffset * 2 - Game1.pixelZoom * 4, Game1.pixelZoom), new Microsoft.Xna.Framework.Rectangle?(Game1.staminaRect.Bounds), Color.White * 0.75f, 0.0f, Vector2.Zero, SpriteEffects.None, (float)((double)this.getStandingY() / 10000.0 + 1.0 / 1000.0));
} }
@ -655,7 +533,7 @@ namespace CustomNPCFramework.Framework.NPCS
sourceRect.Height /= 2; sourceRect.Height /= 2;
} }
//The actual character drawing to the screen? //The actual character drawing to the screen?
this.characterRenderer.draw(b, this, this.getLocalPosition(Game1.viewport) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(sourceRect), Color.White * alpha, this.rotation,Vector2.Zero, Math.Max(0.2f, this.Scale), this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, this.drawOnTop ? 0.992f : (float)((double)this.getStandingY() / 10000.0 + 1.0 / 1000.0))); this.characterRenderer.draw(b, this, this.getLocalPosition(Game1.viewport) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(sourceRect), Color.White * alpha, this.rotation, Vector2.Zero, Math.Max(0.2f, this.Scale), this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, this.drawOnTop ? 0.992f : (float)((double)this.getStandingY() / 10000.0 + 1.0 / 1000.0)));
//this.characterRenderer.draw(b,this, this.getLocalPosition(Game1.viewport) + vector2 + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(sourceRect), Color.White * alpha, this.rotation, new Vector2((float)(sourceRect.Width / 2), (float)(sourceRect.Height / 2 + 1)), Math.Max(0.2f, this.scale) * (float)Game1.pixelZoom + num, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, this.drawOnTop ? 0.992f : (float)((double)this.getStandingY() / 10000.0 + 1.0 / 1000.0))); //this.characterRenderer.draw(b,this, this.getLocalPosition(Game1.viewport) + vector2 + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(sourceRect), Color.White * alpha, this.rotation, new Vector2((float)(sourceRect.Width / 2), (float)(sourceRect.Height / 2 + 1)), Math.Max(0.2f, this.scale) * (float)Game1.pixelZoom + num, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, this.drawOnTop ? 0.992f : (float)((double)this.getStandingY() / 10000.0 + 1.0 / 1000.0)));
//this.characterRenderer.draw(b, this, this.getLocalPosition(Game1.viewport) + vector2 + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(sourceRect), Color.White * alpha, this.rotation, new Vector2((float)(sourceRect.Width / 2), (float)(sourceRect.Height / 2 + 1)), Math.Max(0.2f, this.scale) * (float)Game1.pixelZoom + num, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, .99f); //this.characterRenderer.draw(b, this, this.getLocalPosition(Game1.viewport) + vector2 + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(sourceRect), Color.White * alpha, this.rotation, new Vector2((float)(sourceRect.Width / 2), (float)(sourceRect.Height / 2 + 1)), Math.Max(0.2f, this.scale) * (float)Game1.pixelZoom + num, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, .99f);
} }
@ -667,7 +545,7 @@ namespace CustomNPCFramework.Framework.NPCS
//Checks if the npc is glowing. //Checks if the npc is glowing.
if (this.isGlowing) if (this.isGlowing)
this.characterRenderer.draw(b,this, this.getLocalPosition(Game1.viewport) + new Vector2((float)(this.Sprite.SpriteWidth * Game1.pixelZoom / 2), (float)(this.GetBoundingBox().Height / 2)) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(this.Sprite.SourceRect), this.glowingColor * this.glowingTransparency, this.rotation, new Vector2((float)(this.Sprite.SpriteWidth / 2), (float)((double)this.Sprite.SpriteHeight * 3.0 / 4.0)), Math.Max(0.2f, this.Scale) * 4f, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, this.drawOnTop ? 0.99f : (float)((double)this.getStandingY() / 10000.0 + 1.0 / 1000.0))); this.characterRenderer.draw(b, this, this.getLocalPosition(Game1.viewport) + new Vector2((float)(this.Sprite.SpriteWidth * Game1.pixelZoom / 2), (float)(this.GetBoundingBox().Height / 2)) + (this.shakeTimer > 0 ? new Vector2((float)Game1.random.Next(-1, 2), (float)Game1.random.Next(-1, 2)) : Vector2.Zero), new Microsoft.Xna.Framework.Rectangle?(this.Sprite.SourceRect), this.glowingColor * this.glowingTransparency, this.rotation, new Vector2((float)(this.Sprite.SpriteWidth / 2), (float)((double)this.Sprite.SpriteHeight * 3.0 / 4.0)), Math.Max(0.2f, this.Scale) * 4f, this.flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None, Math.Max(0.0f, this.drawOnTop ? 0.99f : (float)((double)this.getStandingY() / 10000.0 + 1.0 / 1000.0)));
//This code runs if the npc is emoting. //This code runs if the npc is emoting.
if (!this.IsEmoting || Game1.eventUp) if (!this.IsEmoting || Game1.eventUp)
@ -677,9 +555,7 @@ namespace CustomNPCFramework.Framework.NPCS
b.Draw(Game1.emoteSpriteSheet, localPosition1, new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(this.CurrentEmoteIndex * 16 % Game1.emoteSpriteSheet.Width, this.CurrentEmoteIndex * 16 / Game1.emoteSpriteSheet.Width * 16, 16, 16)), Color.White, 0.0f, Vector2.Zero, (float)Game1.pixelZoom, SpriteEffects.None, (float)this.getStandingY() / 10000f); b.Draw(Game1.emoteSpriteSheet, localPosition1, new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(this.CurrentEmoteIndex * 16 % Game1.emoteSpriteSheet.Width, this.CurrentEmoteIndex * 16 / Game1.emoteSpriteSheet.Width * 16, 16, 16)), Color.White, 0.0f, Vector2.Zero, (float)Game1.pixelZoom, SpriteEffects.None, (float)this.getStandingY() / 10000f);
} }
/// <summary> /// <summary>Used to draw the sprite without the modular npc renderer</summary>
/// Used to draw the sprite without the modular npc renderer
/// </summary>
/// <param name="b"></param> /// <param name="b"></param>
/// <param name="alpha"></param> /// <param name="alpha"></param>
public virtual void drawNonModularSprite(SpriteBatch b, float alpha = 1f) public virtual void drawNonModularSprite(SpriteBatch b, float alpha = 1f)
@ -728,9 +604,7 @@ namespace CustomNPCFramework.Framework.NPCS
} }
/// <summary> /// <summary>Basic draw functionality to checkn whether or not to draw the npc using it's default sprite or using a custom character renderer.</summary>
/// Basic draw functionality to checkn whether or not to draw the npc using it's default sprite or using a custom character renderer.
/// </summary>
/// <param name="b"></param> /// <param name="b"></param>
/// <param name="alpha"></param> /// <param name="alpha"></param>
public override void draw(SpriteBatch b, float alpha = 1f) public override void draw(SpriteBatch b, float alpha = 1f)

View File

@ -1,56 +1,41 @@
using CustomNPCFramework.Framework.ModularNPCS; using System.Collections.Generic;
using CustomNPCFramework.Framework.ModularNPCS.ModularRenderers; using CustomNPCFramework.Framework.ModularNpcs;
using CustomNPCFramework.Framework.ModularNpcs.ModularRenderers;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using StardewValley; using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.NPCS namespace CustomNPCFramework.Framework.NPCS
{ {
/// <summary> /// <summary>Extended merchant npc from ExtendedNPC.</summary>
/// Extended merchant npc from ExtendedNPC. class MerchantNpc : ExtendedNpc
/// </summary>
class MerchantNPC: ExtendedNPC
{ {
/// <summary> /// <summary>The list of items this npc has for sale.</summary>
/// Thelist of items this npc has for sale.
/// </summary>
public List<Item> stock; public List<Item> stock;
/// <summary>
/// Constructor. /// <summary>Construct an instance.</summary>
/// </summary>
/// <param name="Stock">The list of items this npc will sell.</param> /// <param name="Stock">The list of items this npc will sell.</param>
/// <param name="sprite">The sprite for the npc to use.</param> /// <param name="sprite">The sprite for the npc to use.</param>
/// <param name="renderer">The renderer for the npc to use.</param> /// <param name="renderer">The renderer for the npc to use.</param>
/// <param name="position">The position for the npc to use.</param> /// <param name="position">The position for the npc to use.</param>
/// <param name="facingDirection">The facing direction for the player to face.</param> /// <param name="facingDirection">The facing direction for the player to face.</param>
/// <param name="name">The name for the npc.</param> /// <param name="name">The name for the npc.</param>
public MerchantNPC(List<Item> Stock, Sprite sprite, BasicRenderer renderer,Vector2 position,int facingDirection,string name): base(sprite,renderer,position,facingDirection,name) public MerchantNpc(List<Item> Stock, Sprite sprite, BasicRenderer renderer, Vector2 position, int facingDirection, string name)
: base(sprite, renderer, position, facingDirection, name)
{ {
this.stock = Stock; this.stock = Stock;
} }
/// <summary>Construct an instance.</summary>
/// <summary>
/// Constructor.
/// </summary>
/// <param name="Stock">The list of items for the npc to sell.</param> /// <param name="Stock">The list of items for the npc to sell.</param>
/// <param name="npcBase">The npc base for the character to be expanded upon.</param> /// <param name="npcBase">The npc base for the character to be expanded upon.</param>
public MerchantNPC(List<Item> Stock, ExtendedNPC npcBase) : base(npcBase.spriteInformation, npcBase.characterRenderer, npcBase.portraitInformation, npcBase.position, npcBase.facingDirection, npcBase.Name) public MerchantNpc(List<Item> Stock, ExtendedNpc npcBase)
: base(npcBase.spriteInformation, npcBase.characterRenderer, npcBase.portraitInformation, npcBase.position, npcBase.facingDirection, npcBase.Name)
{ {
this.stock = Stock; this.stock = Stock;
} }
/// <summary> /// <summary>Used to interact with the npc. When interacting pulls up a shop menu for the npc with their current stock.</summary>
/// Used to interact with the npc. When interacting pulls up a shop menu for the npc with their current stock. public override bool checkAction(Farmer who, GameLocation l)
/// </summary>
/// <param name="who"></param>
/// <param name="l"></param>
/// <returns></returns>
public override bool checkAction(StardewValley.Farmer who, GameLocation l)
{ {
if (Game1.activeClickableMenu == null) if (Game1.activeClickableMenu == null)
{ {

View File

@ -1,89 +1,64 @@
using CustomNPCFramework.Framework.NPCS; using System.Collections.Generic;
using CustomNPCFramework.Framework.NPCS;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using StardewValley; using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomNPCFramework.Framework.Utilities namespace CustomNPCFramework.Framework.Utilities
{ {
/// <summary> /// <summary>Used to keep track of all of the custom npcs.</summary>
/// Used to keep track of all of the custom npcs. public class NpcTracker
/// </summary>
public class NPCTracker
{ {
/// <summary> /// <summary>A list used to keep track of the npcs.</summary>
/// A list used to keep track of the npcs. public List<ExtendedNpc> moddedNpcs;
/// </summary>
public List<ExtendedNPC> moddedNPCS;
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor. public NpcTracker()
/// </summary>
public NPCTracker()
{ {
this.moddedNPCS = new List<ExtendedNPC>(); this.moddedNpcs = new List<ExtendedNpc>();
} }
/// <summary> /// <summary>Use this to add a new npc into the game.</summary>
/// Use this to add a new npc into the game.
/// </summary>
/// <param name="loc">The game location to add the npc to.</param> /// <param name="loc">The game location to add the npc to.</param>
/// <param name="npc">The extended npc to add to the location.</param> /// <param name="npc">The extended npc to add to the location.</param>
public void addNewNPCToLocation(GameLocation loc,ExtendedNPC npc) public void addNewNpcToLocation(GameLocation loc, ExtendedNpc npc)
{ {
this.moddedNPCS.Add(npc); this.moddedNpcs.Add(npc);
npc.defaultLocation = loc; npc.defaultLocation = loc;
npc.currentLocation = loc; npc.currentLocation = loc;
loc.addCharacter(npc); loc.addCharacter(npc);
} }
/// <summary> /// <summary>Add a npc to a location.</summary>
/// Add a npc to a location.
/// </summary>
/// <param name="loc">The game location to add an npc to.</param> /// <param name="loc">The game location to add an npc to.</param>
/// <param name="npc">The extended npc to add to the location.</param> /// <param name="npc">The extended npc to add to the location.</param>
/// <param name="tilePosition">The tile position at the game location to add the mpc to.</param> /// <param name="tilePosition">The tile position at the game location to add the mpc to.</param>
public void addNewNPCToLocation(GameLocation loc, ExtendedNPC npc, Vector2 tilePosition) public void addNewNpcToLocation(GameLocation loc, ExtendedNpc npc, Vector2 tilePosition)
{ {
this.moddedNPCS.Add(npc); this.moddedNpcs.Add(npc);
npc.defaultLocation = loc; npc.defaultLocation = loc;
npc.currentLocation = loc; npc.currentLocation = loc;
npc.position.Value = tilePosition*Game1.tileSize; npc.position.Value = tilePosition * Game1.tileSize;
loc.addCharacter(npc); loc.addCharacter(npc);
} }
/// <summary> /// <summary>Use this simply to remove a single npc from a location.</summary>
/// Use this simply to remove a single npc from a location. public void removeCharacterFromLocation(GameLocation loc, ExtendedNpc npc)
/// </summary>
/// <param name="loc"></param>
/// <param name="npc"></param>
public void removeCharacterFromLocation(GameLocation loc, ExtendedNPC npc)
{ {
loc.characters.Remove(npc); loc.characters.Remove(npc);
} }
/// <summary> /// <summary>Use this to completly remove and npc from the game as it is removed from the location and is no longer tracked.</summary>
/// Use this to completly remove and npc from the game as it is removed from the location and is no longer tracked.
/// </summary>
/// <param name="npc">The npc to remove from the location.</param> /// <param name="npc">The npc to remove from the location.</param>
public void removeFromLocationAndTrackingList(ExtendedNPC npc) public void removeFromLocationAndTrackingList(ExtendedNpc npc)
{ {
if (npc.currentLocation != null) npc.currentLocation?.characters.Remove(npc);
{ this.moddedNpcs.Remove(npc);
npc.currentLocation.characters.Remove(npc);
}
this.moddedNPCS.Remove(npc);
} }
/// <summary> /// <summary>Use this to clean up all of the npcs before the game is saved.</summary>
/// Use this to clean up all of the npcs before the game is saved.
/// </summary>
public void cleanUpBeforeSave() public void cleanUpBeforeSave()
{ {
foreach(ExtendedNPC npc in this.moddedNPCS) foreach (ExtendedNpc npc in this.moddedNpcs)
{ {
//npc.currentLocation.characters.Remove(npc); //npc.currentLocation.characters.Remove(npc);
//Game1.removeThisCharacterFromAllLocations(npc); //Game1.removeThisCharacterFromAllLocations(npc);
@ -91,19 +66,13 @@ namespace CustomNPCFramework.Framework.Utilities
Class1.ModMonitor.Log("Removed an npc!"); Class1.ModMonitor.Log("Removed an npc!");
//Do some saving code here. //Do some saving code here.
} }
} }
/// <summary> /// <summary>Use this to load in all of the npcs again after saving.</summary>
/// Use this to load in all of the npcs again after saving.
/// </summary>
public void afterSave() public void afterSave()
{ {
foreach(ExtendedNPC npc in this.moddedNPCS) foreach (ExtendedNpc npc in this.moddedNpcs)
{
npc.defaultLocation.addCharacter(npc); npc.defaultLocation.addCharacter(npc);
} }
} }
}
} }

View File

@ -6,5 +6,5 @@
"UniqueID": "Omegasis.CustomNPCFramework", "UniqueID": "Omegasis.CustomNPCFramework",
"EntryDll": "CustomNPCFramework.dll", "EntryDll": "CustomNPCFramework.dll",
"MinimumApiVersion": "2.0", "MinimumApiVersion": "2.0",
"UpdateKeys": [ ] "UpdateKeys": []
} }

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Pathoschild.Stardew.ModBuildConfig" version="2.2.0" targetFramework="net45" />
</packages>

View File

@ -1,17 +1,16 @@
using Omegasis.DailyQuestAnywhere.Framework; using System;
using Omegasis.DailyQuestAnywhere.Framework;
using StardewModdingAPI; using StardewModdingAPI;
using StardewModdingAPI.Events; using StardewModdingAPI.Events;
using StardewValley; using StardewValley;
using StardewValley.Menus; using StardewValley.Menus;
using StardewValley.Quests; using StardewValley.Quests;
using System;
namespace Omegasis.DailyQuestAnywhere namespace Omegasis.DailyQuestAnywhere
{ {
/* /*
*TODO: Make quest core mod??? *TODO: Make quest core mod???
*/ */
/// <summary>The mod entry point.</summary> /// <summary>The mod entry point.</summary>
public class DailyQuestAnywhere : Mod public class DailyQuestAnywhere : Mod
{ {
@ -34,12 +33,10 @@ namespace Omegasis.DailyQuestAnywhere
this.Config = helper.ReadConfig<ModConfig>(); this.Config = helper.ReadConfig<ModConfig>();
ControlEvents.KeyPressed += this.ControlEvents_KeyPressed; ControlEvents.KeyPressed += this.ControlEvents_KeyPressed;
StardewModdingAPI.Events.SaveEvents.AfterSave += SaveEvents_AfterSave; SaveEvents.AfterSave += this.SaveEvents_AfterSave;
} }
/********* /*********
** Private methods ** Private methods
*********/ *********/
@ -49,31 +46,26 @@ namespace Omegasis.DailyQuestAnywhere
private void ControlEvents_KeyPressed(object sender, EventArgsKeyPressed e) private void ControlEvents_KeyPressed(object sender, EventArgsKeyPressed e)
{ {
if (Context.IsPlayerFree && e.KeyPressed.ToString() == this.Config.KeyBinding) if (Context.IsPlayerFree && e.KeyPressed.ToString() == this.Config.KeyBinding)
if (Game1.player.hasDailyQuest() == false ) if (!Game1.player.hasDailyQuest())
{ {
if (this.dailyQuest == null) if (this.dailyQuest == null)
{ {
this.dailyQuest = generateDailyQuest(); this.dailyQuest = this.generateDailyQuest();
} }
Game1.questOfTheDay = this.dailyQuest; Game1.questOfTheDay = this.dailyQuest;
Game1.activeClickableMenu = new Billboard(true); Game1.activeClickableMenu = new Billboard(true);
} }
} }
/// <summary> /// <summary>Makes my daily quest referene null so we can't just keep getting a new reference.</summary>
/// Makes my daily quest referene null so we can't just keep getting a new reference. /// <param name="sender">The event sender.</param>
/// </summary> /// <param name="e">The event data.</param>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveEvents_AfterSave(object sender, System.EventArgs e) private void SaveEvents_AfterSave(object sender, System.EventArgs e)
{ {
this.dailyQuest = null; //Nullify my quest reference. this.dailyQuest = null; //Nullify my quest reference.
} }
/// <summary> /// <summary>Generate a daily quest for sure.</summary>
/// Generate a daily quest for sure.
/// </summary>
/// <returns></returns>
public Quest generateDailyQuest() public Quest generateDailyQuest()
{ {
@ -82,18 +74,27 @@ namespace Omegasis.DailyQuestAnywhere
float actualChance = chance / 100; float actualChance = chance / 100;
//If we hit the chance for actually generating a daily quest do so, otherwise don't generate a daily quest. //If we hit the chance for actually generating a daily quest do so, otherwise don't generate a daily quest.
if (actualChance <= Config.chanceForDailyQuest) if (actualChance <= this.Config.chanceForDailyQuest)
{ {
Random r = new Random((int)Game1.uniqueIDForThisGame + (int)Game1.stats.DaysPlayed); Random r = new Random((int)Game1.uniqueIDForThisGame + (int)Game1.stats.DaysPlayed);
int rand = r.Next(0, 7); int rand = r.Next(0, 7);
switch (rand)
if (rand == 0) return new ItemDeliveryQuest(); {
if (rand == 1) return new FishingQuest(); case 0:
if (rand == 2) return new StardewValley.Quests.CraftingQuest(); return new ItemDeliveryQuest();
if (rand == 3) return new StardewValley.Quests.ItemDeliveryQuest(); case 1:
if (rand == 4) return new StardewValley.Quests.ItemHarvestQuest(); return new FishingQuest();
if (rand == 5) return new StardewValley.Quests.ResourceCollectionQuest(); case 2:
if (rand == 6) return new StardewValley.Quests.SlayMonsterQuest(); return new StardewValley.Quests.CraftingQuest();
case 3:
return new StardewValley.Quests.ItemDeliveryQuest();
case 4:
return new StardewValley.Quests.ItemHarvestQuest();
case 5:
return new StardewValley.Quests.ResourceCollectionQuest();
case 6:
return new StardewValley.Quests.SlayMonsterQuest();
}
} }
return null; //This should never happen. return null; //This should never happen.
} }

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -11,8 +11,6 @@
<AssemblyName>DailyQuestAnywhere</AssemblyName> <AssemblyName>DailyQuestAnywhere</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -67,6 +65,9 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Pathoschild.Stardew.ModBuildConfig" Version="2.2.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
@ -83,19 +84,8 @@
<None Include="manifest.json" /> <None Include="manifest.json" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="packages.config" />
<None Include="README.md" /> <None Include="README.md" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\analyzers\dotnet\cs\StardewModdingAPI.ModBuildConfig.Analyzer.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\deploy.targets" /> <Import Project="$(SolutionDir)\deploy.targets" />
<Import Project="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\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>
<Error Condition="!Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets'))" />
</Target>
</Project> </Project>

View File

@ -1,4 +1,4 @@
namespace Omegasis.DailyQuestAnywhere.Framework namespace Omegasis.DailyQuestAnywhere.Framework
{ {
/// <summary>The mod configuration.</summary> /// <summary>The mod configuration.</summary>
internal class ModConfig internal class ModConfig
@ -6,9 +6,7 @@
/// <summary>The key which shows the menu.</summary> /// <summary>The key which shows the menu.</summary>
public string KeyBinding { get; set; } = "H"; public string KeyBinding { get; set; } = "H";
/// <summary> /// <summary>The chance for a daily quest to actually happen.</summary>
/// The chance for a daily quest to actually happen.
/// </summary>
public float chanceForDailyQuest { get; set; } = .75f; public float chanceForDailyQuest { get; set; } = .75f;
} }
} }

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Pathoschild.Stardew.ModBuildConfig" version="2.2.0" targetFramework="net45" />
</packages>

View File

@ -1,4 +1,4 @@
using System; using System;
using StardewModdingAPI; using StardewModdingAPI;
using StardewModdingAPI.Events; using StardewModdingAPI.Events;
using StardewValley; using StardewValley;

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -11,8 +11,6 @@
<AssemblyName>Fall28SnowDay</AssemblyName> <AssemblyName>Fall28SnowDay</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -67,6 +65,9 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Pathoschild.Stardew.ModBuildConfig" Version="2.2.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
@ -82,19 +83,8 @@
<None Include="manifest.json" /> <None Include="manifest.json" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="packages.config" />
<None Include="README.md" /> <None Include="README.md" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\analyzers\dotnet\cs\StardewModdingAPI.ModBuildConfig.Analyzer.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\deploy.targets" /> <Import Project="$(SolutionDir)\deploy.targets" />
<Import Project="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\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>
<Error Condition="!Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets'))" />
</Target>
</Project> </Project>

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Pathoschild.Stardew.ModBuildConfig" version="2.2.0" targetFramework="net45" />
</packages>

View File

@ -1,17 +1,12 @@
using EventSystem.Framework.FunctionEvents; using System;
using EventSystem.Framework.FunctionEvents;
using FarmersMarketStall.Framework.MapEvents; using FarmersMarketStall.Framework.MapEvents;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using StardewModdingAPI; using StardewModdingAPI;
using StardewValley; using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FarmersMarketStall namespace FarmersMarketStall
{ {
/// <summary> /// <summary>
/// TODO: /// TODO:
/// Make a farmers market menu /// Make a farmers market menu
@ -21,21 +16,21 @@ namespace FarmersMarketStall
/// Make a selling menu /// Make a selling menu
/// Make a minigame event for bonus money to earn. /// Make a minigame event for bonus money to earn.
/// </summary> /// </summary>
/// <param name="helper"></param> public class Class1 : Mod
public class Class1 :Mod
{ {
public static IModHelper ModHelper; public static IModHelper ModHelper;
public static IMonitor ModMonitor; public static IMonitor ModMonitor;
public static FarmersMarketStall.Framework.MarketStall marketStall; public static Framework.MarketStall marketStall;
/// <summary>The mod entry point, called after the mod is first loaded.</summary>
/// <param name="helper">Provides simplified APIs for writing mods.</param>
public override void Entry(IModHelper helper) public override void Entry(IModHelper helper)
{ {
ModHelper = Helper; ModHelper = this.Helper;
ModMonitor = Monitor; ModMonitor = this.Monitor;
StardewModdingAPI.Events.SaveEvents.BeforeSave += SaveEvents_BeforeSave; StardewModdingAPI.Events.SaveEvents.BeforeSave += this.SaveEvents_BeforeSave;
StardewModdingAPI.Events.SaveEvents.AfterLoad += SaveEvents_AfterLoad; StardewModdingAPI.Events.SaveEvents.AfterLoad += this.SaveEvents_AfterLoad;
marketStall = new Framework.MarketStall(); marketStall = new Framework.MarketStall();
} }
@ -46,7 +41,8 @@ namespace FarmersMarketStall
private void SaveEvents_BeforeSave(object sender, EventArgs e) private void SaveEvents_BeforeSave(object sender, EventArgs e)
{ {
if (marketStall.stock.Count > 0) { if (marketStall.stock.Count > 0)
{
// Game1.endOfNightMenus.Push(new StardewValley.Menus.ShippingMenu(marketStall.stock)); // Game1.endOfNightMenus.Push(new StardewValley.Menus.ShippingMenu(marketStall.stock));
marketStall.sellAllItems(); marketStall.sellAllItems();
} }

View File

@ -11,8 +11,6 @@
<AssemblyName>FarmersMarketStall</AssemblyName> <AssemblyName>FarmersMarketStall</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion> <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -68,9 +66,9 @@
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="EventSystem"> <PackageReference Include="Pathoschild.Stardew.ModBuildConfig" Version="2.2.0" />
<HintPath>..\MapEvents\bin\Release\EventSystem.dll</HintPath> </ItemGroup>
</Reference> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
@ -88,17 +86,13 @@
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="packages.config" /> <ProjectReference Include="..\MapEvents\EventSystem.csproj">
<Project>{bb737337-2d82-4245-aa46-f3b82fc6f228}</Project>
<Name>EventSystem</Name>
</ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Analyzer Include="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\analyzers\dotnet\cs\StardewModdingAPI.ModBuildConfig.Analyzer.dll" /> <None Include="manifest.json" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\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>
<Error Condition="!Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets'))" />
</Target>
</Project> </Project>

View File

@ -1,18 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EventSystem;
using EventSystem.Framework.FunctionEvents; using EventSystem.Framework.FunctionEvents;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using StardewValley; using StardewValley;
namespace FarmersMarketStall.Framework.MapEvents namespace FarmersMarketStall.Framework.MapEvents
{ {
public class ShopInteractionEvent :EventSystem.Framework.MapEvent public class ShopInteractionEvent : EventSystem.Framework.MapEvent
{ {
public ShopInteractionEvent(string Name, GameLocation Location, Vector2 Position, MouseButtonEvents MouseEvents, MouseEntryLeaveEvent EntryLeave) : base(Name, Location, Position) public ShopInteractionEvent(string Name, GameLocation Location, Vector2 Position, MouseButtonEvents MouseEvents, MouseEntryLeaveEvent EntryLeave)
: base(Name, Location, Position)
{ {
this.name = Name; this.name = Name;
this.location = Location; this.location = Location;
@ -24,18 +19,17 @@ namespace FarmersMarketStall.Framework.MapEvents
this.mouseEntryLeaveEvents = EntryLeave; this.mouseEntryLeaveEvents = EntryLeave;
} }
public override bool OnLeftClick() public override bool OnLeftClick()
{ {
if (base.OnLeftClick() == false) return false; if (!base.OnLeftClick())
if (this.location.isObjectAt((int)this.tilePosition.X * Game1.tileSize, (int)this.tilePosition.Y * Game1.tileSize)) return false; return false;
if (this.location.isObjectAt((int)this.tilePosition.X * Game1.tileSize, (int)this.tilePosition.Y * Game1.tileSize))
return false;
Game1.activeClickableMenu = Menus.MarketStallMenu.openMenu(Class1.marketStall); Game1.activeClickableMenu = Menus.MarketStallMenu.openMenu(Class1.marketStall);
return true; return true;
} }
/// <summary> /// <summary>Used to update the event and check for interaction.</summary>
/// Used to update the event and check for interaction.
/// </summary>
public override void update() public override void update()
{ {
this.clickEvent(); this.clickEvent();
@ -43,6 +37,5 @@ namespace FarmersMarketStall.Framework.MapEvents
this.OnMouseEnter(); this.OnMouseEnter();
this.OnMouseLeave(); this.OnMouseLeave();
} }
} }
} }

View File

@ -1,9 +1,5 @@
using StardewValley;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using StardewValley;
using System.Text;
using System.Threading.Tasks;
namespace FarmersMarketStall.Framework namespace FarmersMarketStall.Framework
{ {
@ -11,10 +7,7 @@ namespace FarmersMarketStall.Framework
{ {
public List<Item> stock; public List<Item> stock;
public MarketStall() public MarketStall() { }
{
}
public void addItemToSell(Item item) public void addItemToSell(Item item)
{ {
@ -28,12 +21,10 @@ namespace FarmersMarketStall.Framework
public void sellAllItems() public void sellAllItems()
{ {
foreach(var item in stock) foreach (var item in this.stock)
{ Game1.player.money += (int)(item.salePrice() * 1.10f); //Replace the multiplier with some sort of level.
Game1.player.money+=(int)(item.salePrice() * 1.10f); //Replace the multiplier with some sort of level.
}
this.stock.Clear(); this.stock.Clear();
} }
} }
} }

View File

@ -1,10 +1,5 @@
using StardewValley;
using StardewValley.Menus;
using System; using System;
using System.Collections.Generic; using StardewValley.Menus;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FarmersMarketStall.Framework.Menus namespace FarmersMarketStall.Framework.Menus
{ {
@ -17,9 +12,8 @@ namespace FarmersMarketStall.Framework.Menus
public static IClickableMenu openMenu(MarketStall marketStall) public static IClickableMenu openMenu(MarketStall marketStall)
{ {
throw new NotImplementedException("This menu isn't implemented because the author is busy/lazy. Please encorage Omegasis to finish it!",null); throw new NotImplementedException("This menu isn't implemented because the author is busy/lazy. Please encorage Omegasis to finish it!", null);
//return new StardewValley.Menus.InventoryMenu((int)(Game1.viewport.Width*.25f),(int)(Game1.viewport.Height*.25f),true,marketStall.stock); //return new StardewValley.Menus.InventoryMenu((int)(Game1.viewport.Width*.25f),(int)(Game1.viewport.Height*.25f),true,marketStall.stock);
} }
} }
} }

View File

@ -6,11 +6,8 @@
"UniqueID": "SunDrop.SunDropMapEvents.FarmersMarketStall", "UniqueID": "SunDrop.SunDropMapEvents.FarmersMarketStall",
"EntryDll": "FarmersMarketStall.dll", "EntryDll": "FarmersMarketStall.dll",
"MinimumApiVersion": "2.0", "MinimumApiVersion": "2.0",
"UpdateKeys": [ ], "UpdateKeys": [],
"Dependencies": [ "Dependencies": [
{ { "UniqueID": "Omegasis.EventSystem" }
"UniqueID": "Omegasis.EventSystem", ]
"IsRequired": true
}
]
} }

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Pathoschild.Stardew.ModBuildConfig" version="2.2.0" targetFramework="net461" />
</packages>

View File

@ -1,16 +1,9 @@
using StardewValley; using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Omegasis.HappyBirthday namespace Omegasis.HappyBirthday
{ {
/// <summary> // TODO: Make all the events
/// TODO:Make all the events // Resources:https://stardewvalleywiki.com/Modding:Event_data
/// Resources:https://stardewvalleywiki.com/Modding:Event_data
/// </summary>
public class BirthdayEvents public class BirthdayEvents
{ {
public Event communityCenterJunimoEvent; public Event communityCenterJunimoEvent;
@ -21,7 +14,7 @@ namespace Omegasis.HappyBirthday
public BirthdayEvents() public BirthdayEvents()
{ {
initializeEvents(); this.initializeEvents();
} }
public void initializeEvents() public void initializeEvents()
@ -29,7 +22,5 @@ namespace Omegasis.HappyBirthday
Event e = new Event("", -1, Game1.player); Event e = new Event("", -1, Game1.player);
Game1.player.currentLocation.currentEvent = new Event(); Game1.player.currentLocation.currentEvent = new Event();
} }
} }
} }

View File

@ -1,25 +1,17 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using Newtonsoft.Json;
using System.Text;
using System.Threading.Tasks;
namespace Omegasis.HappyBirthday namespace Omegasis.HappyBirthday
{ {
public class BirthdayMessages public class BirthdayMessages
{ {
/// <summary> /// <summary>The actual birthday wishes given by an npc.</summary>
/// The actual birthday wishes given by an npc.
/// </summary>
public Dictionary<string, string> birthdayWishes; public Dictionary<string, string> birthdayWishes;
public Dictionary<string, string> spouseBirthdayWishes; public Dictionary<string, string> spouseBirthdayWishes;
/// <summary> // TODO: Make this.
/// TODO: Make this.
/// </summary>
public Dictionary<string, string> defaultSpouseBirthdayWishes = new Dictionary<string, string>() public Dictionary<string, string> defaultSpouseBirthdayWishes = new Dictionary<string, string>()
{ {
["Alex"] = "", ["Alex"] = "",
@ -36,9 +28,7 @@ namespace Omegasis.HappyBirthday
["Penny"] = "", ["Penny"] = "",
}; };
/// <summary> /// <summary>Used to contain</summary>
/// Used to contain
/// </summary>
public Dictionary<string, string> defaultBirthdayWishes = new Dictionary<string, string>() public Dictionary<string, string> defaultBirthdayWishes = new Dictionary<string, string>()
{ {
["Robin"] = "Hey @, happy birthday! I'm glad you choose this town to move here to. ", ["Robin"] = "Hey @, happy birthday! I'm glad you choose this town to move here to. ",
@ -76,12 +66,9 @@ namespace Omegasis.HappyBirthday
["Krobus"] = "I have heard that it is tradition to give a gift to others on their birthday. In that case, happy birthday @." ["Krobus"] = "I have heard that it is tradition to give a gift to others on their birthday. In that case, happy birthday @."
}; };
/// <summary> /// <summary>Used to load all of the default birthday greetings.</summary>
/// Used to load all of the default birthday greetings.
/// </summary>
public void createBirthdayGreetings() public void createBirthdayGreetings()
{ {
var serializer = JsonSerializer.Create(); var serializer = JsonSerializer.Create();
serializer.Formatting = Formatting.Indented; serializer.Formatting = Formatting.Indented;
@ -89,75 +76,64 @@ namespace Omegasis.HappyBirthday
string defaultPath = Path.Combine(HappyBirthday.ModHelper.DirectoryPath, "Content", "Dialogue", HappyBirthday.Config.translationInfo.currentTranslation); string defaultPath = Path.Combine(HappyBirthday.ModHelper.DirectoryPath, "Content", "Dialogue", HappyBirthday.Config.translationInfo.currentTranslation);
if (!Directory.Exists(defaultPath)) Directory.CreateDirectory(defaultPath); if (!Directory.Exists(defaultPath)) Directory.CreateDirectory(defaultPath);
string birthdayFileDict=HappyBirthday.Config.translationInfo.getjsonForTranslation("BirthdayWishes", HappyBirthday.Config.translationInfo.currentTranslation); string birthdayFileDict = HappyBirthday.Config.translationInfo.getjsonForTranslation("BirthdayWishes", HappyBirthday.Config.translationInfo.currentTranslation);
string path = Path.Combine( "Content", "Dialogue", HappyBirthday.Config.translationInfo.currentTranslation, birthdayFileDict); string path = Path.Combine("Content", "Dialogue", HappyBirthday.Config.translationInfo.currentTranslation, birthdayFileDict);
//Handle normal birthday wishes. //Handle normal birthday wishes.
if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath,path))) if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath, path)))
{ {
HappyBirthday.ModMonitor.Log("Creating Villager Birthday Messages", StardewModdingAPI.LogLevel.Alert); HappyBirthday.ModMonitor.Log("Creating Villager Birthday Messages", StardewModdingAPI.LogLevel.Alert);
HappyBirthday.ModHelper.Data.WriteJsonFile<Dictionary<string, string>>(path, defaultBirthdayWishes); HappyBirthday.ModHelper.Data.WriteJsonFile<Dictionary<string, string>>(path, this.defaultBirthdayWishes);
this.birthdayWishes = defaultBirthdayWishes; this.birthdayWishes = this.defaultBirthdayWishes;
} }
else else
{ this.birthdayWishes = HappyBirthday.ModHelper.Data.ReadJsonFile<Dictionary<string, string>>(path);
birthdayWishes = HappyBirthday.ModHelper.Data.ReadJsonFile<Dictionary<string, string>>(path);
}
//handle spouse birthday wishes. //handle spouse birthday wishes.
string spouseBirthdayFileDict = HappyBirthday.Config.translationInfo.getjsonForTranslation("SpouseBirthdayWishes", HappyBirthday.Config.translationInfo.currentTranslation); string spouseBirthdayFileDict = HappyBirthday.Config.translationInfo.getjsonForTranslation("SpouseBirthdayWishes", HappyBirthday.Config.translationInfo.currentTranslation);
string spousePath = Path.Combine("Content", "Dialogue", HappyBirthday.Config.translationInfo.currentTranslation, spouseBirthdayFileDict); string spousePath = Path.Combine("Content", "Dialogue", HappyBirthday.Config.translationInfo.currentTranslation, spouseBirthdayFileDict);
if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath,spousePath))) if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath, spousePath)))
{ {
HappyBirthday.ModMonitor.Log("Creating Spouse Messages", StardewModdingAPI.LogLevel.Alert); HappyBirthday.ModMonitor.Log("Creating Spouse Messages", StardewModdingAPI.LogLevel.Alert);
HappyBirthday.ModHelper.Data.WriteJsonFile<Dictionary<string, string>>(spousePath, defaultSpouseBirthdayWishes); HappyBirthday.ModHelper.Data.WriteJsonFile<Dictionary<string, string>>(spousePath, this.defaultSpouseBirthdayWishes);
this.spouseBirthdayWishes = defaultSpouseBirthdayWishes; this.spouseBirthdayWishes = this.defaultSpouseBirthdayWishes;
} }
else else
{ this.spouseBirthdayWishes = HappyBirthday.ModHelper.Data.ReadJsonFile<Dictionary<string, string>>(spousePath);
spouseBirthdayWishes = HappyBirthday.ModHelper.Data.ReadJsonFile<Dictionary<string, string>>(spousePath);
}
//Non-english logic for creating templates. //Non-english logic for creating templates.
foreach(var translation in HappyBirthday.Config.translationInfo.translationCodes) foreach (var translation in HappyBirthday.Config.translationInfo.translationCodes)
{ {
if (translation.Key == "English") continue; if (translation.Key == "English")
string basePath = Path.Combine(HappyBirthday.ModHelper.DirectoryPath,"Content", "Dialogue", translation.Key); continue;
if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);
string tempBirthdayFile =Path.Combine("Content", "Dialogue", translation.Key, HappyBirthday.Config.translationInfo.getjsonForTranslation("BirthdayWishes", translation.Key)); string basePath = Path.Combine(HappyBirthday.ModHelper.DirectoryPath, "Content", "Dialogue", translation.Key);
string tempSpouseBirthdayFile =Path.Combine("Content", "Dialogue", translation.Key, HappyBirthday.Config.translationInfo.getjsonForTranslation("SpouseBirthdayWishes", translation.Key)); if (!Directory.Exists(basePath))
Directory.CreateDirectory(basePath);
string tempBirthdayFile = Path.Combine("Content", "Dialogue", translation.Key, HappyBirthday.Config.translationInfo.getjsonForTranslation("BirthdayWishes", translation.Key));
string tempSpouseBirthdayFile = Path.Combine("Content", "Dialogue", translation.Key, HappyBirthday.Config.translationInfo.getjsonForTranslation("SpouseBirthdayWishes", translation.Key));
Dictionary<string, string> tempBirthdayDict = new Dictionary<string, string>(); Dictionary<string, string> tempBirthdayDict = new Dictionary<string, string>();
if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath, tempBirthdayFile))) if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath, tempBirthdayFile)))
{ {
foreach (var pair in this.defaultBirthdayWishes)
foreach (var pair in defaultBirthdayWishes)
{
tempBirthdayDict.Add(pair.Key, ""); tempBirthdayDict.Add(pair.Key, "");
}
HappyBirthday.ModHelper.Data.WriteJsonFile<Dictionary<string, string>>(tempBirthdayFile, tempBirthdayDict); HappyBirthday.ModHelper.Data.WriteJsonFile<Dictionary<string, string>>(tempBirthdayFile, tempBirthdayDict);
} }
else else
{
tempBirthdayDict = HappyBirthday.ModHelper.Data.ReadJsonFile<Dictionary<string, string>>(tempBirthdayFile); tempBirthdayDict = HappyBirthday.ModHelper.Data.ReadJsonFile<Dictionary<string, string>>(tempBirthdayFile);
}
Dictionary<string, string> tempSpouseBirthdayDict = new Dictionary<string, string>(); Dictionary<string, string> tempSpouseBirthdayDict = new Dictionary<string, string>();
if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath, tempSpouseBirthdayFile))) if (!File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath, tempSpouseBirthdayFile)))
{ {
foreach (var pair in this.defaultSpouseBirthdayWishes)
foreach (var pair in defaultSpouseBirthdayWishes)
{
tempSpouseBirthdayDict.Add(pair.Key, ""); tempSpouseBirthdayDict.Add(pair.Key, "");
}
HappyBirthday.ModHelper.Data.WriteJsonFile<Dictionary<string, string>>(tempSpouseBirthdayFile, tempSpouseBirthdayDict); HappyBirthday.ModHelper.Data.WriteJsonFile<Dictionary<string, string>>(tempSpouseBirthdayFile, tempSpouseBirthdayDict);
} }
else else
{
tempSpouseBirthdayDict = HappyBirthday.ModHelper.Data.ReadJsonFile<Dictionary<string, string>>(tempSpouseBirthdayFile); tempSpouseBirthdayDict = HappyBirthday.ModHelper.Data.ReadJsonFile<Dictionary<string, string>>(tempSpouseBirthdayFile);
}
//Set translated birthday info. //Set translated birthday info.
if (HappyBirthday.Config.translationInfo.currentTranslation == translation.Key) if (HappyBirthday.Config.translationInfo.currentTranslation == translation.Key)
@ -166,10 +142,7 @@ namespace Omegasis.HappyBirthday
this.spouseBirthdayWishes = tempSpouseBirthdayDict; this.spouseBirthdayWishes = tempSpouseBirthdayDict;
HappyBirthday.ModMonitor.Log("Language set to: " + translation); HappyBirthday.ModMonitor.Log("Language set to: " + translation);
} }
} }
} }
} }
} }

View File

@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
@ -51,8 +51,6 @@ namespace Omegasis.HappyBirthday.Framework
this.SetUpPositions(); this.SetUpPositions();
} }
/// <summary>The method called when the game window changes size.</summary> /// <summary>The method called when the game window changes size.</summary>
/// <param name="oldBounds">The former viewport.</param> /// <param name="oldBounds">The former viewport.</param>
/// <param name="newBounds">The new viewport.</param> /// <param name="newBounds">The new viewport.</param>

View File

@ -1,6 +1,5 @@

using StardewValley; using StardewValley;
using System.Collections.Generic;
namespace Omegasis.HappyBirthday.Framework namespace Omegasis.HappyBirthday.Framework
{ {
@ -28,8 +27,6 @@ namespace Omegasis.HappyBirthday.Framework
Game1.player.mailReceived.Add("BackpackTip"); Game1.player.mailReceived.Add("BackpackTip");
Game1.addMailForTomorrow("pierreBackpack", false, false); Game1.addMailForTomorrow("pierreBackpack", false, false);
} }
} }
} }

View File

@ -1,4 +1,4 @@
namespace Omegasis.HappyBirthday.Framework namespace Omegasis.HappyBirthday.Framework
{ {
/// <summary>The mod configuration.</summary> /// <summary>The mod configuration.</summary>
public class ModConfig public class ModConfig
@ -6,14 +6,10 @@
/// <summary>The key which shows the menu.</summary> /// <summary>The key which shows the menu.</summary>
public string KeyBinding { get; set; } = "O"; public string KeyBinding { get; set; } = "O";
/// <summary> /// <summary>The minimum amount of friendship needed to get a birthday gift.</summary>
/// The minimum amount of friendship needed to get a birthday gift.
/// </summary>
public int minNeutralFriendshipGiftLevel = 3; public int minNeutralFriendshipGiftLevel = 3;
/// <summary> /// <summary>The max amount of friendship needed to get a neutral gift from an npc.</summary>
/// The max amount of friendship needed to get a neutral gift from an npc.
/// </summary>
public int maxNeutralFriendshipGiftLevel = 4; public int maxNeutralFriendshipGiftLevel = 4;
/// <summary> /// <summary>
@ -21,34 +17,22 @@
/// </summary> /// </summary>
public int minLikeFriendshipLevel = 5; public int minLikeFriendshipLevel = 5;
/// <summary> /// <summary>The max amount of friendship needed to get a liked gift from an npc.</summary>
/// The max amount of friendship needed to get a liked gift from an npc.
/// </summary>
public int maxLikeFriendshipLevel = 6; public int maxLikeFriendshipLevel = 6;
/// <summary> /// <summary>The minimum amount of friendship needed to get a loved gift from an npc.</summary>
/// The minimum amount of friendship needed to get a loved gift from an npc.
/// </summary>
public int minLoveFriendshipLevel = 7; public int minLoveFriendshipLevel = 7;
/// <summary> /// <summary>The minimum amount of friendship needed to get a happy birthday greeting from an npc.</summary>
/// The minimum amount of friendship needed to get a happy birthday greeting from an npc. public int minimumFriendshipLevelForBirthdayWish = 2;
/// </summary>
public int minimumFriendshipLevelForBirthdayWish=2;
/// <summary> /// <summary>Handles different translations of files.</summary>
/// Handles different translations of files.
/// </summary>
public TranslationInfo translationInfo; public TranslationInfo translationInfo;
/// <summary> /// <summary>Whether or not to load from the old BirthdayGifts.xnb located in StardewValley/Data or from the new BirthdayGifts.json located in the mod directory.</summary>
/// Whether or not to load from the old BirthdayGifts.xnb located in StardewValley/Data or from the new BirthdayGifts.json located in the mod directory.
/// </summary>
public bool useLegacyBirthdayFiles; public bool useLegacyBirthdayFiles;
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor.
/// </summary>
public ModConfig() public ModConfig()
{ {
this.translationInfo = new TranslationInfo(); this.translationInfo = new TranslationInfo();

View File

@ -1,27 +1,20 @@
using StardewValley;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using StardewValley;
using System.Text;
using System.Threading.Tasks;
namespace Omegasis.HappyBirthday.Framework namespace Omegasis.HappyBirthday.Framework
{ {
public class MultiplayerSupport public class MultiplayerSupport
{ {
public static string FSTRING_SendBirthdayMessageToOthers = "Omegasis.HappyBirthday.Framework.Messages.SendBirthdayMessageToOtherPlayers"; public static string FSTRING_SendBirthdayMessageToOthers = "Omegasis.HappyBirthday.Framework.Messages.SendBirthdayMessageToOtherPlayers";
public static string FSTRING_SendBirthdayInfoToOthers = "Omegasis.HappyBirthday.Framework.Messages.SendBirthdayInfoToOtherPlayers"; public static string FSTRING_SendBirthdayInfoToOthers = "Omegasis.HappyBirthday.Framework.Messages.SendBirthdayInfoToOtherPlayers";
public static void SendBirthdayMessageToOtherPlayers() public static void SendBirthdayMessageToOtherPlayers()
{ {
HUDMessage message = new HUDMessage("It's " + Game1.player.Name + "'s birthday! Happy birthday to them!", 1); HUDMessage message = new HUDMessage("It's " + Game1.player.Name + "'s birthday! Happy birthday to them!", 1);
foreach (KeyValuePair<long, Farmer> f in Game1.otherFarmers)
foreach (KeyValuePair<long,Farmer> f in Game1.otherFarmers)
{ {
HappyBirthday.ModHelper.Multiplayer.SendMessage<string>(message.message, FSTRING_SendBirthdayMessageToOthers,new string[] { HappyBirthday.ModHelper.Multiplayer.ModID }, new long[] { f.Key }); HappyBirthday.ModHelper.Multiplayer.SendMessage<string>(message.message, FSTRING_SendBirthdayMessageToOthers, new string[] { HappyBirthday.ModHelper.Multiplayer.ModID }, new long[] { f.Key });
//ModdedUtilitiesNetworking.ModCore.multiplayer.sendMessage(FSTRING_SendBirthdayMessageToOthers, ModdedUtilitiesNetworking.Framework.Extentions.StrardewValleyExtentions.MessagesExtentions.HUDMessageIconIdentifier, message, ModdedUtilitiesNetworking.Framework.Enums.MessageTypes.messageTypes.SendToSpecific, f); //ModdedUtilitiesNetworking.ModCore.multiplayer.sendMessage(FSTRING_SendBirthdayMessageToOthers, ModdedUtilitiesNetworking.Framework.Extentions.StrardewValleyExtentions.MessagesExtentions.HUDMessageIconIdentifier, message, ModdedUtilitiesNetworking.Framework.Enums.MessageTypes.messageTypes.SendToSpecific, f);
} }
} }
@ -30,10 +23,9 @@ namespace Omegasis.HappyBirthday.Framework
{ {
foreach (KeyValuePair<long, Farmer> f in Game1.otherFarmers) foreach (KeyValuePair<long, Farmer> f in Game1.otherFarmers)
{ {
HappyBirthday.ModHelper.Multiplayer.SendMessage<KeyValuePair<long,PlayerData>>(new KeyValuePair<long, PlayerData>(Game1.player.uniqueMultiplayerID, HappyBirthday.PlayerBirthdayData), FSTRING_SendBirthdayInfoToOthers, new string[] { HappyBirthday.ModHelper.Multiplayer.ModID }, new long[] { f.Key }); HappyBirthday.ModHelper.Multiplayer.SendMessage<KeyValuePair<long, PlayerData>>(new KeyValuePair<long, PlayerData>(Game1.player.uniqueMultiplayerID, HappyBirthday.PlayerBirthdayData), FSTRING_SendBirthdayInfoToOthers, new string[] { HappyBirthday.ModHelper.Multiplayer.ModID }, new long[] { f.Key });
//ModdedUtilitiesNetworking.ModCore.multiplayer.sendMessage(FSTRING_SendBirthdayMessageToOthers, ModdedUtilitiesNetworking.Framework.Extentions.StrardewValleyExtentions.MessagesExtentions.HUDMessageIconIdentifier, message, ModdedUtilitiesNetworking.Framework.Enums.MessageTypes.messageTypes.SendToSpecific, f); //ModdedUtilitiesNetworking.ModCore.multiplayer.sendMessage(FSTRING_SendBirthdayMessageToOthers, ModdedUtilitiesNetworking.Framework.Extentions.StrardewValleyExtentions.MessagesExtentions.HUDMessageIconIdentifier, message, ModdedUtilitiesNetworking.Framework.Enums.MessageTypes.messageTypes.SendToSpecific, f);
} }
} }
public static void SendBirthdayInfoToConnectingPlayer(long id) public static void SendBirthdayInfoToConnectingPlayer(long id)
@ -42,6 +34,5 @@ namespace Omegasis.HappyBirthday.Framework
//ModdedUtilitiesNetworking.ModCore.multiplayer.sendMessage(FSTRING_SendBirthdayMessageToOthers, ModdedUtilitiesNetworking.Framework.Extentions.StrardewValleyExtentions.MessagesExtentions.HUDMessageIconIdentifier, message, ModdedUtilitiesNetworking.Framework.Enums.MessageTypes.messageTypes.SendToSpecific, f); //ModdedUtilitiesNetworking.ModCore.multiplayer.sendMessage(FSTRING_SendBirthdayMessageToOthers, ModdedUtilitiesNetworking.Framework.Extentions.StrardewValleyExtentions.MessagesExtentions.HUDMessageIconIdentifier, message, ModdedUtilitiesNetworking.Framework.Enums.MessageTypes.messageTypes.SendToSpecific, f);
} }
} }
} }

View File

@ -1,4 +1,4 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using StardewValley; using StardewValley;
using Object = StardewValley.Object; using Object = StardewValley.Object;

View File

@ -1,4 +1,4 @@
namespace Omegasis.HappyBirthday.Framework namespace Omegasis.HappyBirthday.Framework
{ {
/// <summary>The data for the current player.</summary> /// <summary>The data for the current player.</summary>
public class PlayerData public class PlayerData

View File

@ -1,70 +1,56 @@
using StardewValley;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using StardewValley;
using System.Text;
using System.Threading.Tasks;
namespace Omegasis.HappyBirthday.Framework namespace Omegasis.HappyBirthday.Framework
{ {
/// <summary> /// <summary>A class which deals with handling different translations for Vocalization should other voice teams ever wish to voice act for that language.</summary>
/// A class which deals with handling different translations for Vocalization should other voice teams ever wish to voice act for that language.
/// </summary>
public class TranslationInfo public class TranslationInfo
{ {
/// <summary> /// <summary>The list of all supported translations by this mod.</summary>
/// The list of all supported translations by this mod.
/// </summary>
public List<string> translations; public List<string> translations;
/// <summary> /// <summary>The current translation mode for the mod, so that it knows what files to load at the beginning of the game.</summary>
/// The current translation mode for the mod, so that it knows what files to load at the beginning of the game.
/// </summary>
public string currentTranslation; public string currentTranslation;
/// <summary> /// <summary>Holds the info for what translation has what file extension.</summary>
/// Holds the info for what translation has what file extension.
/// </summary>
public Dictionary<string, string> translationFileInfo; public Dictionary<string, string> translationFileInfo;
public Dictionary<string, LocalizedContentManager.LanguageCode> translationCodes; public Dictionary<string, LocalizedContentManager.LanguageCode> translationCodes;
/// <summary>
/// Default constructor. /// <summary>Construct an instance..</summary>
/// </summary>
public TranslationInfo() public TranslationInfo()
{ {
translations = new List<string>(); this.translations = new List<string>();
translationFileInfo = new Dictionary<string, string>(); this.translationFileInfo = new Dictionary<string, string>();
translationCodes = new Dictionary<string, LocalizedContentManager.LanguageCode>(); this.translationCodes = new Dictionary<string, LocalizedContentManager.LanguageCode>();
translations.Add("English"); this.translations.Add("English");
translations.Add("Spanish"); this.translations.Add("Spanish");
translations.Add("Chinese"); this.translations.Add("Chinese");
translations.Add("Japanese"); this.translations.Add("Japanese");
translations.Add("Russian"); this.translations.Add("Russian");
translations.Add("German"); this.translations.Add("German");
translations.Add("Brazillian Portuguese"); this.translations.Add("Brazillian Portuguese");
currentTranslation = "English"; this.currentTranslation = "English";
translationFileInfo.Add("English", ".json"); this.translationFileInfo.Add("English", ".json");
translationFileInfo.Add("Spanish", ".es-ES.json"); this.translationFileInfo.Add("Spanish", ".es-ES.json");
translationFileInfo.Add("Chinese", ".zh-CN.json"); this.translationFileInfo.Add("Chinese", ".zh-CN.json");
translationFileInfo.Add("Japanese", ".ja-JP.json"); this.translationFileInfo.Add("Japanese", ".ja-JP.json");
translationFileInfo.Add("Russian", ".ru-RU.json"); this.translationFileInfo.Add("Russian", ".ru-RU.json");
translationFileInfo.Add("German", ".de-DE.json"); this.translationFileInfo.Add("German", ".de-DE.json");
translationFileInfo.Add("Brazillian Portuguese", ".pt-BR.json"); this.translationFileInfo.Add("Brazillian Portuguese", ".pt-BR.json");
translationCodes.Add("English", LocalizedContentManager.LanguageCode.en); this.translationCodes.Add("English", LocalizedContentManager.LanguageCode.en);
translationCodes.Add("Spanish", LocalizedContentManager.LanguageCode.es); this.translationCodes.Add("Spanish", LocalizedContentManager.LanguageCode.es);
translationCodes.Add("Chinese", LocalizedContentManager.LanguageCode.zh); this.translationCodes.Add("Chinese", LocalizedContentManager.LanguageCode.zh);
translationCodes.Add("Japanese", LocalizedContentManager.LanguageCode.ja); this.translationCodes.Add("Japanese", LocalizedContentManager.LanguageCode.ja);
translationCodes.Add("Russian", LocalizedContentManager.LanguageCode.ru); this.translationCodes.Add("Russian", LocalizedContentManager.LanguageCode.ru);
translationCodes.Add("German", LocalizedContentManager.LanguageCode.de); this.translationCodes.Add("German", LocalizedContentManager.LanguageCode.de);
translationCodes.Add("Brazillian Portuguese", LocalizedContentManager.LanguageCode.pt); this.translationCodes.Add("Brazillian Portuguese", LocalizedContentManager.LanguageCode.pt);
} }
@ -73,12 +59,11 @@ namespace Omegasis.HappyBirthday.Framework
return Path.GetFileName(fullPath); return Path.GetFileName(fullPath);
} }
public void changeLocalizedContentManagerFromTranslation(string translation) public void changeLocalizedContentManagerFromTranslation(string translation)
{ {
string tra = getTranslationNameFromPath(translation); string tra = this.getTranslationNameFromPath(translation);
bool f = translationCodes.TryGetValue(tra, out LocalizedContentManager.LanguageCode code); bool f = this.translationCodes.TryGetValue(tra, out LocalizedContentManager.LanguageCode code);
if (f == false) LocalizedContentManager.CurrentLanguageCode = LocalizedContentManager.LanguageCode.en; if (!f) LocalizedContentManager.CurrentLanguageCode = LocalizedContentManager.LanguageCode.en;
else LocalizedContentManager.CurrentLanguageCode = code; else LocalizedContentManager.CurrentLanguageCode = code;
return; return;
} }
@ -88,24 +73,21 @@ namespace Omegasis.HappyBirthday.Framework
LocalizedContentManager.CurrentLanguageCode = LocalizedContentManager.LanguageCode.en; LocalizedContentManager.CurrentLanguageCode = LocalizedContentManager.LanguageCode.en;
} }
/// <summary> /// <summary>Gets the proper file extension for the current translation.</summary>
/// Gets the proper file extension for the current translation.
/// </summary>
/// <param name="path"></param> /// <param name="path"></param>
/// <returns></returns>
public string getFileExtentionForTranslation(string path) public string getFileExtentionForTranslation(string path)
{ {
/* /*
bool f = translationFileInfo.TryGetValue(translation, out string value); bool f = translationFileInfo.TryGetValue(translation, out string value);
if (f == false) return ".json"; if (!f) return ".json";
else return value; else return value;
*/ */
string translation = Path.GetFileName(path); string translation = Path.GetFileName(path);
try try
{ {
return translationFileInfo[translation]; return this.translationFileInfo[translation];
} }
catch (Exception err) catch
{ {
HappyBirthday.ModMonitor.Log("WTF SOMETHING IS WRONG!", StardewModdingAPI.LogLevel.Warn); HappyBirthday.ModMonitor.Log("WTF SOMETHING IS WRONG!", StardewModdingAPI.LogLevel.Warn);
//Vocalization.ModMonitor.Log(err.ToString()); //Vocalization.ModMonitor.Log(err.ToString());
@ -114,45 +96,34 @@ namespace Omegasis.HappyBirthday.Framework
} }
} }
/// <summary> /// <summary>Gets the proper json for Buildings (aka Blueprints) from the data folder.</summary>
/// Gets the proper json for Buildings (aka Blueprints) from the data folder.
/// </summary>
/// <param name="translation"></param>
/// <returns></returns>
public string getBuildingjsonForTranslation(string translation) public string getBuildingjsonForTranslation(string translation)
{ {
string buildings = "Blueprints"; string buildings = "Blueprints";
return buildings + getFileExtentionForTranslation(translation); return buildings + this.getFileExtentionForTranslation(translation);
} }
/// <summary> /// <summary>Gets the proper json file for the name passed in. Combines the file name with it's proper translation extension.</summary>
/// Gets the proper json file for the name passed in. Combines the file name with it's proper translation extension.
/// </summary>
/// <param name="jsonFileName"></param> /// <param name="jsonFileName"></param>
/// <param name="translation"></param> /// <param name="translation"></param>
/// <returns></returns>
public string getjsonForTranslation(string jsonFileName, string translation) public string getjsonForTranslation(string jsonFileName, string translation)
{ {
return jsonFileName + getFileExtentionForTranslation(translation); return jsonFileName + this.getFileExtentionForTranslation(translation);
} }
/// <summary> /// <summary>Loads an json file from StardewValley/Content</summary>
/// Loads an json file from StardewValley/Content
/// </summary>
/// <param name="jsonFileName"></param> /// <param name="jsonFileName"></param>
/// <param name="key"></param> /// <param name="key"></param>
/// <param name="translation"></param> /// <param name="translation"></param>
/// <returns></returns>
public string LoadjsonFile(string jsonFileName, string key, string translation) public string LoadjsonFile(string jsonFileName, string key, string translation)
{ {
string json = jsonFileName + getFileExtentionForTranslation(translation); string json = jsonFileName + this.getFileExtentionForTranslation(translation);
Dictionary<string, string> loadedDict = Game1.content.Load<Dictionary<string, string>>(json); Dictionary<string, string> loadedDict = Game1.content.Load<Dictionary<string, string>>(json);
string loaded; bool f = loadedDict.TryGetValue(key, out string loaded);
bool f = loadedDict.TryGetValue(key, out loaded); if (!f)
if (f == false)
{ {
//Vocalization.ModMonitor.Log("Big issue: Key not found in file:" + json + " " + key); //Vocalization.ModMonitor.Log("Big issue: Key not found in file:" + json + " " + key);
return ""; return "";
@ -160,15 +131,12 @@ namespace Omegasis.HappyBirthday.Framework
else return loaded; else return loaded;
} }
/// <summary> /// <summary>Loads a string dictionary from a json file.</summary>
/// Loads a string dictionary from a json file.
/// </summary>
/// <param name="jsonFileName"></param> /// <param name="jsonFileName"></param>
/// <param name="translation"></param> /// <param name="translation"></param>
/// <returns></returns> public Dictionary<string, string> LoadJsonFileDictionary(string jsonFileName, string translation)
public Dictionary<string,string> LoadJsonFileDictionary(string jsonFileName, string translation)
{ {
string json = jsonFileName + getFileExtentionForTranslation(translation); string json = jsonFileName + this.getFileExtentionForTranslation(translation);
Dictionary<string, string> loadedDict = Game1.content.Load<Dictionary<string, string>>(json); Dictionary<string, string> loadedDict = Game1.content.Load<Dictionary<string, string>>(json);
return loadedDict; return loadedDict;
@ -181,9 +149,7 @@ namespace Omegasis.HappyBirthday.Framework
{ {
return string.Format(format, sub1, sub2, sub3); return string.Format(format, sub1, sub2, sub3);
} }
catch (Exception ex) catch { }
{
}
return format; return format;
} }
@ -195,9 +161,7 @@ namespace Omegasis.HappyBirthday.Framework
{ {
return string.Format(format, sub1, sub2); return string.Format(format, sub1, sub2);
} }
catch (Exception ex) catch { }
{
}
return format; return format;
} }
@ -209,20 +173,15 @@ namespace Omegasis.HappyBirthday.Framework
{ {
return string.Format(format, sub1); return string.Format(format, sub1);
} }
catch (Exception ex) catch { }
{
}
return format; return format;
} }
public virtual string LoadString(string path, string translation) public virtual string LoadString(string path, string translation)
{ {
string assetName; this.parseStringPath(path, out string assetName, out string key);
string key; return this.LoadjsonFile(assetName, key, translation);
this.parseStringPath(path, out assetName, out key);
return LoadjsonFile(assetName, key, translation);
} }
public virtual string LoadString(string path, string translation, params object[] substitutions) public virtual string LoadString(string path, string translation, params object[] substitutions)
@ -234,14 +193,11 @@ namespace Omegasis.HappyBirthday.Framework
{ {
return string.Format(format, substitutions); return string.Format(format, substitutions);
} }
catch (Exception ex) catch { }
{
}
} }
return format; return format;
} }
private void parseStringPath(string path, out string assetName, out string key) private void parseStringPath(string path, out string assetName, out string key)
{ {
int length = path.IndexOf(':'); int length = path.IndexOf(':');

View File

@ -1,26 +1,20 @@
using Omegasis.HappyBirthday.Framework;
using StardewModdingAPI;
using StardewValley;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using Omegasis.HappyBirthday.Framework;
using StardewValley;
using static System.String;
using SObject = StardewValley.Object; using SObject = StardewValley.Object;
namespace Omegasis.HappyBirthday namespace Omegasis.HappyBirthday
{ {
public class GiftManager public class GiftManager
{ {
public ModConfig Config public ModConfig Config => HappyBirthday.Config;
{
get
{
return HappyBirthday.Config;
}
}
private Dictionary<string, string> defaultBirthdayGifts = new Dictionary<string, string>()
private Dictionary<string,string> defaultBirthdayGifts=new Dictionary<string, string>() { {
["Universal_Love_Gift"] = "74 1 446 1 204 1 446 5 773 1", ["Universal_Love_Gift"] = "74 1 446 1 204 1 446 5 773 1",
["Universal_Like_Gift"] = "-2 3 -7 1 -26 2 -75 5 -80 3 72 1 220 1 221 1 395 1 613 1 634 1 635 1 636 1 637 1 638 1 724 1 233 1 223 1 465 20 -79 5", ["Universal_Like_Gift"] = "-2 3 -7 1 -26 2 -75 5 -80 3 72 1 220 1 221 1 395 1 613 1 634 1 635 1 636 1 637 1 638 1 724 1 233 1 223 1 465 20 -79 5",
["Universal_Neutral_Gift"] = "194 1 262 5 -74 5 -75 3 334 5 335 1 390 20 388 20 -81 5 -79 3", ["Universal_Neutral_Gift"] = "194 1 262 5 -74 5 -75 3 334 5 335 1 390 20 388 20 -81 5 -79 3",
@ -59,7 +53,8 @@ namespace Omegasis.HappyBirthday
["Krobus"] = " Best/72 1 16 1 276 1 337 1 305 1 /Good/66 1 336 1 340 1 /Neutral// " ["Krobus"] = " Best/72 1 16 1 276 1 337 1 305 1 /Good/66 1 336 1 340 1 /Neutral// "
}; };
public Dictionary<string, string> defaultSpouseBirthdayGifts = new Dictionary<string, string>() { public Dictionary<string, string> defaultSpouseBirthdayGifts = new Dictionary<string, string>()
{
["Universal_Gifts"] = "74 1 446 1 204 1 446 5 773 1", ["Universal_Gifts"] = "74 1 446 1 204 1 446 5 773 1",
["Alex"] = "", ["Alex"] = "",
@ -74,8 +69,6 @@ namespace Omegasis.HappyBirthday
["Leah"] = "", ["Leah"] = "",
["Maru"] = "", ["Maru"] = "",
["Penny"] = "", ["Penny"] = "",
}; };
public List<Item> BirthdayGifts; public List<Item> BirthdayGifts;
@ -83,7 +76,7 @@ namespace Omegasis.HappyBirthday
/// <summary>The next birthday gift the player will receive.</summary> /// <summary>The next birthday gift the player will receive.</summary>
public Item BirthdayGiftToReceive; public Item BirthdayGiftToReceive;
/// <summary>Construct an instance.</summary>
public GiftManager() public GiftManager()
{ {
this.BirthdayGifts = new List<Item>(); this.BirthdayGifts = new List<Item>();
@ -91,30 +84,22 @@ namespace Omegasis.HappyBirthday
this.loadSpouseBirthdayGifts(); this.loadSpouseBirthdayGifts();
} }
/// <summary> /// <summary>Load birthday gift information from disk. Preferably from BirthdayGift.json in the mod's directory.</summary>
/// Load birthday gift information from disk. Preferably from BirthdayGift.json in the mod's directory.
/// </summary>
/// <returns></returns>
public void loadVillagerBirthdayGifts() public void loadVillagerBirthdayGifts()
{ {
if (HappyBirthday.Config.useLegacyBirthdayFiles == false) if (!HappyBirthday.Config.useLegacyBirthdayFiles)
{ {
string villagerGifts = Path.Combine("Content", "Gifts", "BirthdayGifts.json"); string villagerGifts = Path.Combine("Content", "Gifts", "BirthdayGifts.json");
if (File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath, villagerGifts))) if (File.Exists(Path.Combine(HappyBirthday.ModHelper.DirectoryPath, villagerGifts)))
{
this.defaultBirthdayGifts = HappyBirthday.ModHelper.Data.ReadJsonFile<Dictionary<string, string>>(villagerGifts); this.defaultBirthdayGifts = HappyBirthday.ModHelper.Data.ReadJsonFile<Dictionary<string, string>>(villagerGifts);
}
else else
{
HappyBirthday.ModHelper.Data.WriteJsonFile<Dictionary<string, string>>(villagerGifts, this.defaultBirthdayGifts); HappyBirthday.ModHelper.Data.WriteJsonFile<Dictionary<string, string>>(villagerGifts, this.defaultBirthdayGifts);
} }
}
else else
{ {
if (File.Exists(Path.Combine(Game1.content.RootDirectory, "Data", "PossibleBirthdayGifts.xnb")))
if (File.Exists(Path.Combine(Game1.content.RootDirectory, "Data", "PossibleBirthdayGifts.xnb"))){ {
HappyBirthday.ModMonitor.Log("Legacy loading detected. Attempting to load from StardewValley/Content/Data/PossibleBirthdayGifts.xnb"); HappyBirthday.ModMonitor.Log("Legacy loading detected. Attempting to load from StardewValley/Content/Data/PossibleBirthdayGifts.xnb");
this.defaultBirthdayGifts = Game1.content.Load<Dictionary<string, string>>(Path.Combine("Data", "PossibleBirthdayGifts")); this.defaultBirthdayGifts = Game1.content.Load<Dictionary<string, string>>(Path.Combine("Data", "PossibleBirthdayGifts"));
@ -122,16 +107,11 @@ namespace Omegasis.HappyBirthday
HappyBirthday.ModHelper.Data.WriteJsonFile<Dictionary<string, string>>(villagerGifts, this.defaultBirthdayGifts); HappyBirthday.ModHelper.Data.WriteJsonFile<Dictionary<string, string>>(villagerGifts, this.defaultBirthdayGifts);
} }
else else
{
HappyBirthday.ModMonitor.Log("No birthday gift information found. Loading from internal birthday list"); HappyBirthday.ModMonitor.Log("No birthday gift information found. Loading from internal birthday list");
} }
} }
}
/// <summary> /// <summary>Used to load spouse birthday gifts from disk.</summary>
/// Used to load spouse birthday gifts from disk.
/// </summary>
/// <returns></returns>
public void loadSpouseBirthdayGifts() public void loadSpouseBirthdayGifts()
{ {
string spouseGifts = Path.Combine("Content", "Gifts", "SpouseBirthdayGifts.json"); string spouseGifts = Path.Combine("Content", "Gifts", "SpouseBirthdayGifts.json");
@ -147,7 +127,6 @@ namespace Omegasis.HappyBirthday
} }
} }
/// <summary>Get the default gift items.</summary> /// <summary>Get the default gift items.</summary>
/// <param name="name">The villager's name.</param> /// <param name="name">The villager's name.</param>
private IEnumerable<SObject> GetDefaultBirthdayGifts(string name) private IEnumerable<SObject> GetDefaultBirthdayGifts(string name)
@ -156,14 +135,14 @@ namespace Omegasis.HappyBirthday
try try
{ {
// read from birthday gifts file // read from birthday gifts file
IDictionary<string, string> data = defaultBirthdayGifts; IDictionary<string, string> data = this.defaultBirthdayGifts;
data.TryGetValue(name, out string text); data.TryGetValue(name, out string text);
if (text != null) if (text != null)
{ {
string[] fields = text.Split('/'); string[] fields = text.Split('/');
// love // love
if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minLoveFriendshipLevel) if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minLoveFriendshipLevel)
{ {
string[] loveFields = fields[1].Split(' '); string[] loveFields = fields[1].Split(' ');
for (int i = 0; i < loveFields.Length; i += 2) for (int i = 0; i < loveFields.Length; i += 2)
@ -177,7 +156,7 @@ namespace Omegasis.HappyBirthday
} }
// like // like
if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minLikeFriendshipLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= Config.maxLikeFriendshipLevel) if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minLikeFriendshipLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= this.Config.maxLikeFriendshipLevel)
{ {
string[] likeFields = fields[3].Split(' '); string[] likeFields = fields[3].Split(' ');
for (int i = 0; i < likeFields.Length; i += 2) for (int i = 0; i < likeFields.Length; i += 2)
@ -191,7 +170,7 @@ namespace Omegasis.HappyBirthday
} }
// neutral // neutral
if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minNeutralFriendshipGiftLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= Config.maxNeutralFriendshipGiftLevel) if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minNeutralFriendshipGiftLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= this.Config.maxNeutralFriendshipGiftLevel)
{ {
string[] neutralFields = fields[5].Split(' '); string[] neutralFields = fields[5].Split(' ');
@ -207,27 +186,27 @@ namespace Omegasis.HappyBirthday
} }
// get NPC's preferred gifts // get NPC's preferred gifts
if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minLoveFriendshipLevel) if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minLoveFriendshipLevel)
gifts.AddRange(this.GetUniversalItems("Love", true)); gifts.AddRange(this.GetUniversalItems("Love", true));
if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minLikeFriendshipLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= Config.maxLikeFriendshipLevel) if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minLikeFriendshipLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= this.Config.maxLikeFriendshipLevel)
this.BirthdayGifts.AddRange(this.GetUniversalItems("Like", true)); this.BirthdayGifts.AddRange(this.GetUniversalItems("Like", true));
if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minNeutralFriendshipGiftLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= Config.maxNeutralFriendshipGiftLevel) if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minNeutralFriendshipGiftLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= this.Config.maxNeutralFriendshipGiftLevel)
this.BirthdayGifts.AddRange(this.GetUniversalItems("Neutral", true)); this.BirthdayGifts.AddRange(this.GetUniversalItems("Neutral", true));
} }
catch catch
{ {
// get NPC's preferred gifts // get NPC's preferred gifts
if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minLoveFriendshipLevel) if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minLoveFriendshipLevel)
{ {
this.BirthdayGifts.AddRange(this.GetUniversalItems("Love", false)); this.BirthdayGifts.AddRange(this.GetUniversalItems("Love", false));
this.BirthdayGifts.AddRange(this.GetLovedItems(name)); this.BirthdayGifts.AddRange(this.GetLovedItems(name));
} }
if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minLikeFriendshipLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= Config.maxLikeFriendshipLevel) if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minLikeFriendshipLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= this.Config.maxLikeFriendshipLevel)
{ {
this.BirthdayGifts.AddRange(this.GetLikedItems(name)); this.BirthdayGifts.AddRange(this.GetLikedItems(name));
this.BirthdayGifts.AddRange(this.GetUniversalItems("Like", false)); this.BirthdayGifts.AddRange(this.GetUniversalItems("Like", false));
} }
if (Game1.player.getFriendshipHeartLevelForNPC(name) >= Config.minNeutralFriendshipGiftLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= Config.maxNeutralFriendshipGiftLevel) if (Game1.player.getFriendshipHeartLevelForNPC(name) >= this.Config.minNeutralFriendshipGiftLevel && Game1.player.getFriendshipHeartLevelForNPC(name) <= this.Config.maxNeutralFriendshipGiftLevel)
this.BirthdayGifts.AddRange(this.GetUniversalItems("Neutral", false)); this.BirthdayGifts.AddRange(this.GetUniversalItems("Neutral", false));
} }
@ -236,25 +215,19 @@ namespace Omegasis.HappyBirthday
{ {
if (name == Game1.player.spouse) if (name == Game1.player.spouse)
{ {
this.BirthdayGifts.AddRange(getSpouseBirthdayGifts(name)); this.BirthdayGifts.AddRange(this.getSpouseBirthdayGifts(name));
this.BirthdayGifts.AddRange(getSpouseBirthdayGifts("Universal_Gifts")); this.BirthdayGifts.AddRange(this.getSpouseBirthdayGifts("Universal_Gifts"));
} }
} }
return gifts; return gifts;
} }
/// <summary>
/// Get
/// </summary>
/// <param name="group"></param>
/// <param name=""></param>
/// <returns></returns>
private IEnumerable<Item> getSpouseBirthdayGifts(string npcName) private IEnumerable<Item> getSpouseBirthdayGifts(string npcName)
{ {
Dictionary<string, string> data = this.defaultSpouseBirthdayGifts; Dictionary<string, string> data = this.defaultSpouseBirthdayGifts;
data.TryGetValue(npcName, out string text); data.TryGetValue(npcName, out string text);
if (String.IsNullOrEmpty(text)) if (IsNullOrEmpty(text))
yield break; yield break;
// parse // parse
@ -266,7 +239,6 @@ namespace Omegasis.HappyBirthday
} }
} }
/// <summary>Get the items loved by all villagers.</summary> /// <summary>Get the items loved by all villagers.</summary>
/// <param name="group">The group to get (one of <c>Like</c>, <c>Love</c>, <c>Neutral</c>).</param> /// <param name="group">The group to get (one of <c>Like</c>, <c>Love</c>, <c>Neutral</c>).</param>
/// <param name="isBirthdayGiftList">Whether to get data from <c>Data\BirthdayGifts.xnb</c> instead of the game data.</param> /// <param name="isBirthdayGiftList">Whether to get data from <c>Data\BirthdayGifts.xnb</c> instead of the game data.</param>
@ -352,8 +324,6 @@ namespace Omegasis.HappyBirthday
: new[] { new SObject(id, 1) }; : new[] { new SObject(id, 1) };
} }
/// <summary>Get the items matching the given ID.</summary> /// <summary>Get the items matching the given ID.</summary>
/// <param name="id">The category or item ID.</param> /// <param name="id">The category or item ID.</param>
/// <param name="stack">The stack size.</param> /// <param name="stack">The stack size.</param>

View File

@ -1,10 +1,9 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using Newtonsoft.Json;
using Omegasis.HappyBirthday.Framework; using Omegasis.HappyBirthday.Framework;
using StardewModdingAPI; using StardewModdingAPI;
using StardewModdingAPI.Events; using StardewModdingAPI.Events;
@ -12,7 +11,6 @@ using StardewValley;
using StardewValley.Characters; using StardewValley.Characters;
using StardewValley.Menus; using StardewValley.Menus;
using StardewValley.Monsters; using StardewValley.Monsters;
using SObject = StardewValley.Object;
namespace Omegasis.HappyBirthday namespace Omegasis.HappyBirthday
{ {
@ -34,19 +32,11 @@ namespace Omegasis.HappyBirthday
/// <summary>The data for the current player.</summary> /// <summary>The data for the current player.</summary>
public static PlayerData PlayerBirthdayData; public static PlayerData PlayerBirthdayData;
/// <summary> /// <summary>Wrapper for static field PlayerBirthdayData;</summary>
/// Wrapper for static field PlayerBirthdayData;
/// </summary>
public PlayerData PlayerData public PlayerData PlayerData
{ {
get get => PlayerBirthdayData;
{ set => PlayerBirthdayData = value;
return PlayerBirthdayData;
}
set
{
PlayerBirthdayData = value;
}
} }
/// <summary>Whether the player has chosen a birthday.</summary> /// <summary>Whether the player has chosen a birthday.</summary>
@ -55,49 +45,26 @@ namespace Omegasis.HappyBirthday
/// <summary>The queue of villagers who haven't given a gift yet.</summary> /// <summary>The queue of villagers who haven't given a gift yet.</summary>
private List<string> VillagerQueue; private List<string> VillagerQueue;
/// <summary>Whether we've already checked for and (if applicable) set up the player's birthday today.</summary> /// <summary>Whether we've already checked for and (if applicable) set up the player's birthday today.</summary>
private bool CheckedForBirthday; private bool CheckedForBirthday;
//private Dictionary<string, Dialogue> Dialogue; //private Dictionary<string, Dialogue> Dialogue;
//private bool SeenEvent; //private bool SeenEvent;
public bool CanEdit<T>(IAssetInfo asset)
{
return asset.AssetNameEquals(@"Data\mail");
}
public void Edit<T>(IAssetData asset)
{
asset
.AsDictionary<string, string>()
.Set("birthdayMom", "Dear @,^ Happy birthday sweetheart. It's been amazing watching you grow into the kind, hard working person that I've always dreamed that you would become. I hope you continue to make many more fond memories with the ones you love. ^ Love, Mom ^ P.S. Here's a little something that I made for you. %item object 221 1 %%");
asset
.AsDictionary<string, string>()
.Set("birthdayDad", "Dear @,^ Happy birthday kiddo. It's been a little quiet around here on your birthday since you aren't around, but your mother and I know that you are making both your grandpa and us proud. We both know that living on your own can be tough but we believe in you one hundred percent, just keep following your dreams.^ Love, Dad ^ P.S. Here's some spending money to help you out on the farm. Good luck! %item money 5000 5001 %%");
}
public static IModHelper ModHelper; public static IModHelper ModHelper;
public static IMonitor ModMonitor; public static IMonitor ModMonitor;
/// <summary> /// <summary>Class to handle all birthday messages for this mod.</summary>
/// Class to handle all birthday messages for this mod.
/// </summary>
public BirthdayMessages messages; public BirthdayMessages messages;
/// <summary> /// <summary>Class to handle all birthday gifts for this mod.</summary>
/// Class to handle all birthday gifts for this mod.
/// </summary>
public GiftManager giftManager; public GiftManager giftManager;
/// <summary> /// <summary>Checks if the current billboard is the daily quest screen or not.</summary>
/// Checks if the current billboard is the daily quest screen or not.
/// </summary>
bool isDailyQuestBoard; bool isDailyQuestBoard;
Dictionary<long, PlayerData> othersBirthdays;
Dictionary<long,PlayerData> othersBirthdays;
/********* /*********
** Public methods ** Public methods
@ -114,35 +81,54 @@ namespace Omegasis.HappyBirthday
SaveEvents.AfterLoad += this.SaveEvents_AfterLoad; SaveEvents.AfterLoad += this.SaveEvents_AfterLoad;
SaveEvents.BeforeSave += this.SaveEvents_BeforeSave; SaveEvents.BeforeSave += this.SaveEvents_BeforeSave;
ControlEvents.KeyPressed += this.ControlEvents_KeyPressed; ControlEvents.KeyPressed += this.ControlEvents_KeyPressed;
MenuEvents.MenuChanged += MenuEvents_MenuChanged; MenuEvents.MenuChanged += this.MenuEvents_MenuChanged;
MenuEvents.MenuClosed += MenuEvents_MenuClosed; MenuEvents.MenuClosed += this.MenuEvents_MenuClosed;
GraphicsEvents.OnPostRenderGuiEvent += this.GraphicsEvents_OnPostRenderGuiEvent;
StardewModdingAPI.Events.GraphicsEvents.OnPostRenderHudEvent += this.GraphicsEvents_OnPostRenderHudEvent;
GraphicsEvents.OnPostRenderGuiEvent += GraphicsEvents_OnPostRenderGuiEvent;
StardewModdingAPI.Events.GraphicsEvents.OnPostRenderHudEvent += GraphicsEvents_OnPostRenderHudEvent;
//MultiplayerSupport.initializeMultiplayerSupport(); //MultiplayerSupport.initializeMultiplayerSupport();
ModHelper = Helper; ModHelper = this.Helper;
ModMonitor = Monitor; ModMonitor = this.Monitor;
messages = new BirthdayMessages(); this.messages = new BirthdayMessages();
giftManager = new GiftManager(); this.giftManager = new GiftManager();
messages.createBirthdayGreetings(); this.messages.createBirthdayGreetings();
isDailyQuestBoard = false; this.isDailyQuestBoard = false;
ModHelper.Events.Multiplayer.ModMessageReceived += Multiplayer_ModMessageReceived; ModHelper.Events.Multiplayer.ModMessageReceived += this.Multiplayer_ModMessageReceived;
ModHelper.Events.Multiplayer.PeerDisconnected += Multiplayer_PeerDisconnected; ModHelper.Events.Multiplayer.PeerDisconnected += this.Multiplayer_PeerDisconnected;
this.othersBirthdays = new Dictionary<long, PlayerData>(); this.othersBirthdays = new Dictionary<long, PlayerData>();
} }
/// <summary> /// <summary>Get whether this instance can edit the given asset.</summary>
/// Used to check for player disconnections. /// <param name="asset">Basic metadata about the asset being loaded.</param>
/// </summary> public bool CanEdit<T>(IAssetInfo asset)
/// <param name="sender"></param> {
/// <param name="e"></param> return asset.AssetNameEquals(@"Data\mail");
}
/// <summary>Edit a matched asset.</summary>
/// <param name="asset">A helper which encapsulates metadata about an asset and enables changes to it.</param>
public void Edit<T>(IAssetData asset)
{
asset
.AsDictionary<string, string>()
.Set("birthdayMom", "Dear @,^ Happy birthday sweetheart. It's been amazing watching you grow into the kind, hard working person that I've always dreamed that you would become. I hope you continue to make many more fond memories with the ones you love. ^ Love, Mom ^ P.S. Here's a little something that I made for you. %item object 221 1 %%");
asset
.AsDictionary<string, string>()
.Set("birthdayDad", "Dear @,^ Happy birthday kiddo. It's been a little quiet around here on your birthday since you aren't around, but your mother and I know that you are making both your grandpa and us proud. We both know that living on your own can be tough but we believe in you one hundred percent, just keep following your dreams.^ Love, Dad ^ P.S. Here's some spending money to help you out on the farm. Good luck! %item money 5000 5001 %%");
}
/*********
** Private methods
*********/
/// <summary>Used to check for player disconnections.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event arguments.</param>
private void Multiplayer_PeerDisconnected(object sender, PeerDisconnectedEventArgs e) private void Multiplayer_PeerDisconnected(object sender, PeerDisconnectedEventArgs e)
{ {
this.othersBirthdays.Remove(e.Peer.PlayerID); this.othersBirthdays.Remove(e.Peer.PlayerID);
@ -150,60 +136,50 @@ namespace Omegasis.HappyBirthday
private void Multiplayer_ModMessageReceived(object sender, ModMessageReceivedEventArgs e) private void Multiplayer_ModMessageReceived(object sender, ModMessageReceivedEventArgs e)
{ {
if (e.FromModID == ModHelper.Multiplayer.ModID && e.Type==MultiplayerSupport.FSTRING_SendBirthdayMessageToOthers) if (e.FromModID == ModHelper.Multiplayer.ModID && e.Type == MultiplayerSupport.FSTRING_SendBirthdayMessageToOthers)
{ {
string message = e.ReadAs<string>(); string message = e.ReadAs<string>();
Game1.hudMessages.Add(new HUDMessage(message,1)); Game1.hudMessages.Add(new HUDMessage(message, 1));
} }
if (e.FromModID == ModHelper.Multiplayer.ModID && e.Type == MultiplayerSupport.FSTRING_SendBirthdayInfoToOthers) if (e.FromModID == ModHelper.Multiplayer.ModID && e.Type == MultiplayerSupport.FSTRING_SendBirthdayInfoToOthers)
{ {
KeyValuePair<long,PlayerData> message = e.ReadAs<KeyValuePair<long,PlayerData>>(); KeyValuePair<long, PlayerData> message = e.ReadAs<KeyValuePair<long, PlayerData>>();
if (!this.othersBirthdays.ContainsKey(message.Key)) if (!this.othersBirthdays.ContainsKey(message.Key))
{ {
this.othersBirthdays.Add(message.Key,message.Value); this.othersBirthdays.Add(message.Key, message.Value);
MultiplayerSupport.SendBirthdayInfoToConnectingPlayer(e.FromPlayerID); MultiplayerSupport.SendBirthdayInfoToConnectingPlayer(e.FromPlayerID);
Monitor.Log("Got other player's birthday data from: "+ Game1.getFarmer(e.FromPlayerID).name); this.Monitor.Log("Got other player's birthday data from: " + Game1.getFarmer(e.FromPlayerID).name);
} }
else else
{ {
//Brute force update birthday info if it has already been recevived but dont send birthday info again. //Brute force update birthday info if it has already been recevived but dont send birthday info again.
this.othersBirthdays.Remove(message.Key); this.othersBirthdays.Remove(message.Key);
this.othersBirthdays.Add(message.Key, message.Value); this.othersBirthdays.Add(message.Key, message.Value);
Monitor.Log("Got other player's birthday data from: " + Game1.getFarmer(e.FromPlayerID).name); this.Monitor.Log("Got other player's birthday data from: " + Game1.getFarmer(e.FromPlayerID).name);
}
}
} }
/// <summary>Used to check when a menu is closed.</summary>
/// <param name="sender">The event sender.</param>
} /// <param name="e">The event arguments.</param>
}
/// <summary>
/// Used to check when a menu is closed.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MenuEvents_MenuClosed(object sender, EventArgsClickableMenuClosed e) private void MenuEvents_MenuClosed(object sender, EventArgsClickableMenuClosed e)
{ {
this.isDailyQuestBoard = false; this.isDailyQuestBoard = false;
} }
/// <summary>Used to properly display hovertext for all events happening on a calendar day.</summary>
/// <summary> /// <param name="sender">The event sender.</param>
/// Used to properly display hovertext for all events happening on a calendar day. /// <param name="e">The event arguments.</param>
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GraphicsEvents_OnPostRenderHudEvent(object sender, EventArgs e) private void GraphicsEvents_OnPostRenderHudEvent(object sender, EventArgs e)
{ {
if (Game1.activeClickableMenu == null) return; if (Game1.activeClickableMenu == null) return;
if (PlayerData == null) return; if (this.PlayerData?.BirthdaySeason == null) return;
if (PlayerData.BirthdaySeason == null) return; if (this.PlayerData.BirthdaySeason.ToLower() != Game1.currentSeason.ToLower()) return;
if (PlayerData.BirthdaySeason.ToLower() != Game1.currentSeason.ToLower()) return;
if (Game1.activeClickableMenu is Billboard) if (Game1.activeClickableMenu is Billboard)
{ {
if (isDailyQuestBoard) return; if (this.isDailyQuestBoard) return;
if ((Game1.activeClickableMenu as Billboard).calendarDays == null) return; if ((Game1.activeClickableMenu as Billboard).calendarDays == null) return;
//Game1.player.FarmerRenderer.drawMiniPortrat(Game1.spriteBatch, new Vector2(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 230 + (index - 1) / 7 * 32 * 4), 1f, 4f, 2, Game1.player); //Game1.player.FarmerRenderer.drawMiniPortrat(Game1.spriteBatch, new Vector2(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 230 + (index - 1) / 7 * 32 * 4), 1f, 4f, 2, Game1.player);
@ -211,115 +187,96 @@ namespace Omegasis.HappyBirthday
string hoverText = ""; string hoverText = "";
List<string> texts = new List<string>(); List<string> texts = new List<string>();
foreach (var clicky in (Game1.activeClickableMenu as Billboard).calendarDays) foreach (var clicky in ((Billboard)Game1.activeClickableMenu).calendarDays)
{ {
if (clicky.containsPoint(Game1.getMouseX(), Game1.getMouseY())) if (clicky.containsPoint(Game1.getMouseX(), Game1.getMouseY()))
{ {
if (!String.IsNullOrEmpty(clicky.hoverText)) if (!string.IsNullOrEmpty(clicky.hoverText))
{
texts.Add(clicky.hoverText); //catches npc birhday names. texts.Add(clicky.hoverText); //catches npc birhday names.
} else if (!string.IsNullOrEmpty(clicky.name))
else if (!String.IsNullOrEmpty(clicky.name))
{
texts.Add(clicky.name); //catches festival dates. texts.Add(clicky.name); //catches festival dates.
} }
} }
}
for(int i = 0; i< texts.Count; i++) for (int i = 0; i < texts.Count; i++)
{ {
hoverText += texts[i]; //Append text. hoverText += texts[i]; //Append text.
if (i == texts.Count - 1) continue; if (i != texts.Count - 1)
else
{
hoverText += Environment.NewLine; //Append new line. hoverText += Environment.NewLine; //Append new line.
} }
}
if (!String.IsNullOrEmpty(hoverText)) if (!string.IsNullOrEmpty(hoverText))
{ {
var oldText = Helper.Reflection.GetField<string>(Game1.activeClickableMenu, "hoverText", true); var oldText = this.Helper.Reflection.GetField<string>(Game1.activeClickableMenu, "hoverText");
oldText.SetValue(hoverText); oldText.SetValue(hoverText);
} }
} }
} }
/// <summary> /// <summary>Used to show the farmer's portrait on the billboard menu.</summary>
/// Used to show the farmer's portrait on the billboard menu. /// <param name="sender">The event sender.</param>
/// </summary> /// <param name="e">The event arguments.</param>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GraphicsEvents_OnPostRenderGuiEvent(object sender, EventArgs e) private void GraphicsEvents_OnPostRenderGuiEvent(object sender, EventArgs e)
{ {
if (Game1.activeClickableMenu == null) return; if (Game1.activeClickableMenu == null || this.isDailyQuestBoard)
return;
//Don't do anything if birthday has not been chosen yet. //Don't do anything if birthday has not been chosen yet.
if (PlayerData == null) return; if (this.PlayerData == null)
return;
if (Game1.activeClickableMenu is Billboard) if (Game1.activeClickableMenu is Billboard)
{ {
if (isDailyQuestBoard) return; if (!string.IsNullOrEmpty(this.PlayerData.BirthdaySeason))
if (!String.IsNullOrEmpty(PlayerData.BirthdaySeason))
{ {
if (PlayerData.BirthdaySeason.ToLower() == Game1.currentSeason.ToLower()) if (this.PlayerData.BirthdaySeason.ToLower() == Game1.currentSeason.ToLower())
{ {
int index = PlayerData.BirthdayDay; int index = this.PlayerData.BirthdayDay;
Game1.player.FarmerRenderer.drawMiniPortrat(Game1.spriteBatch, new Vector2(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 230 + (index - 1) / 7 * 32 * 4), 0.5f, 4f, 2, Game1.player); Game1.player.FarmerRenderer.drawMiniPortrat(Game1.spriteBatch, new Vector2(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 230 + (index - 1) / 7 * 32 * 4), 0.5f, 4f, 2, Game1.player);
} }
} }
foreach(var pair in this.othersBirthdays) foreach (var pair in this.othersBirthdays)
{ {
int index = pair.Value.BirthdayDay; int index = pair.Value.BirthdayDay;
if (pair.Value.BirthdaySeason != Game1.currentSeason.ToLower()) continue; //Hide out of season birthdays. if (pair.Value.BirthdaySeason != Game1.currentSeason.ToLower()) continue; //Hide out of season birthdays.
index = pair.Value.BirthdayDay; index = pair.Value.BirthdayDay;
Game1.player.FarmerRenderer.drawMiniPortrat(Game1.spriteBatch, new Vector2(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 230 + (index - 1) / 7 * 32 * 4), 0.5f, 4f, 2, Game1.getFarmer(pair.Key)); Game1.player.FarmerRenderer.drawMiniPortrat(Game1.spriteBatch, new Vector2(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 230 + (index - 1) / 7 * 32 * 4), 0.5f, 4f, 2, Game1.getFarmer(pair.Key));
} }
} }
} }
/// <summary> /// <summary>Functionality to display the player's birthday on the billboard.</summary>
/// Functionality to display the player's birthday on the billboard. /// <param name="sender">The event sender.</param>
/// </summary> /// <param name="e">The event arguments.</param>
/// <param name="sender"></param> private void MenuEvents_MenuChanged(object sender, EventArgsClickableMenuChanged e)
/// <param name="e"></param>
public void MenuEvents_MenuChanged(object sender, EventArgsClickableMenuChanged e)
{ {
if (Game1.activeClickableMenu == null) if (Game1.activeClickableMenu == null)
{ {
isDailyQuestBoard = false; this.isDailyQuestBoard = false;
return; return;
} }
if(Game1.activeClickableMenu is Billboard) if (Game1.activeClickableMenu is Billboard)
{ {
isDailyQuestBoard = ModHelper.Reflection.GetField<bool>((Game1.activeClickableMenu as Billboard), "dailyQuestBoard", true).GetValue(); this.isDailyQuestBoard = ModHelper.Reflection.GetField<bool>((Game1.activeClickableMenu as Billboard), "dailyQuestBoard", true).GetValue();
if (isDailyQuestBoard) return; if (this.isDailyQuestBoard) return;
Texture2D text = new Texture2D(Game1.graphics.GraphicsDevice, 1, 1);
Texture2D text = new Texture2D(Game1.graphics.GraphicsDevice,1,1);
Color[] col = new Color[1]; Color[] col = new Color[1];
col[0] = new Color(0, 0, 0, 1); col[0] = new Color(0, 0, 0, 1);
text.SetData<Color>(col); text.SetData<Color>(col);
//players birthdy position rect=new .... //players birthday position rect=new ....
if (!String.IsNullOrEmpty(PlayerData.BirthdaySeason)) if (!string.IsNullOrEmpty(this.PlayerData.BirthdaySeason))
{ {
if (PlayerData.BirthdaySeason.ToLower() == Game1.currentSeason.ToLower()) if (this.PlayerData.BirthdaySeason.ToLower() == Game1.currentSeason.ToLower())
{ {
int index = PlayerData.BirthdayDay; int index = this.PlayerData.BirthdayDay;
Rectangle birthdayRect = new Rectangle(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 200 + (index - 1) / 7 * 32 * 4, 124, 124); Rectangle birthdayRect = new Rectangle(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 200 + (index - 1) / 7 * 32 * 4, 124, 124);
(Game1.activeClickableMenu as Billboard).calendarDays.Add(new ClickableTextureComponent("", birthdayRect, "", Game1.player.name + "'s Birthday", text, new Rectangle(0, 0, 124, 124), 1f, false)); (Game1.activeClickableMenu as Billboard).calendarDays.Add(new ClickableTextureComponent("", birthdayRect, "", Game1.player.name + "'s Birthday", text, new Rectangle(0, 0, 124, 124), 1f, false));
} }
} }
foreach (var pair in this.othersBirthdays) foreach (var pair in this.othersBirthdays)
{ {
if (pair.Value.BirthdaySeason != Game1.currentSeason.ToLower()) continue; if (pair.Value.BirthdaySeason != Game1.currentSeason.ToLower()) continue;
@ -327,14 +284,9 @@ namespace Omegasis.HappyBirthday
Rectangle otherBirthdayRect = new Rectangle(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 200 + (index - 1) / 7 * 32 * 4, 124, 124); Rectangle otherBirthdayRect = new Rectangle(Game1.activeClickableMenu.xPositionOnScreen + 152 + (index - 1) % 7 * 32 * 4, Game1.activeClickableMenu.yPositionOnScreen + 200 + (index - 1) / 7 * 32 * 4, 124, 124);
(Game1.activeClickableMenu as Billboard).calendarDays.Add(new ClickableTextureComponent("", otherBirthdayRect, "", Game1.getFarmer(pair.Key).name + "'s Birthday", text, new Rectangle(0, 0, 124, 124), 1f, false)); (Game1.activeClickableMenu as Billboard).calendarDays.Add(new ClickableTextureComponent("", otherBirthdayRect, "", Game1.getFarmer(pair.Key).name + "'s Birthday", text, new Rectangle(0, 0, 124, 124), 1f, false));
} }
} }
} }
/*********
** Private methods
*********/
/// <summary>The method invoked after a new day starts.</summary> /// <summary>The method invoked after a new day starts.</summary>
/// <param name="sender">The event sender.</param> /// <param name="sender">The event sender.</param>
/// <param name="e">The event data.</param> /// <param name="e">The event data.</param>
@ -359,7 +311,7 @@ namespace Omegasis.HappyBirthday
/// <param name="e">The event data.</param> /// <param name="e">The event data.</param>
private void SaveEvents_AfterLoad(object sender, EventArgs e) private void SaveEvents_AfterLoad(object sender, EventArgs e)
{ {
this.DataFilePath = Path.Combine("data", Game1.player.Name + "_" + Game1.player.UniqueMultiplayerID+".json"); this.DataFilePath = Path.Combine("data", Game1.player.Name + "_" + Game1.player.UniqueMultiplayerID + ".json");
// reset state // reset state
this.VillagerQueue = new List<string>(); this.VillagerQueue = new List<string>();
@ -396,13 +348,13 @@ namespace Omegasis.HappyBirthday
{ {
if (!Context.IsWorldReady || Game1.eventUp || Game1.isFestival()) if (!Context.IsWorldReady || Game1.eventUp || Game1.isFestival())
return; return;
if (!this.HasChosenBirthday && Game1.activeClickableMenu == null && Game1.player.Name.ToLower()!="unnamed farmhand") if (!this.HasChosenBirthday && Game1.activeClickableMenu == null && Game1.player.Name.ToLower() != "unnamed farmhand")
{ {
Game1.activeClickableMenu = new BirthdayMenu(this.PlayerData.BirthdaySeason, this.PlayerData.BirthdayDay, this.SetBirthday); Game1.activeClickableMenu = new BirthdayMenu(this.PlayerData.BirthdaySeason, this.PlayerData.BirthdayDay, this.SetBirthday);
this.CheckedForBirthday = false; this.CheckedForBirthday = false;
} }
if (!this.CheckedForBirthday && Game1.activeClickableMenu==null) if (!this.CheckedForBirthday && Game1.activeClickableMenu == null)
{ {
this.CheckedForBirthday = true; this.CheckedForBirthday = true;
@ -440,28 +392,26 @@ namespace Omegasis.HappyBirthday
{ {
bool spouseMessage = false; //Used to determine if there is a valid spouse message for the player. If false load in the generic birthday wish. bool spouseMessage = false; //Used to determine if there is a valid spouse message for the player. If false load in the generic birthday wish.
//Check if npc name is spouse's name. If no spouse then add in generic dialogue. //Check if npc name is spouse's name. If no spouse then add in generic dialogue.
if (messages.spouseBirthdayWishes.ContainsKey(npc.Name) && Game1.player.isMarried()) if (this.messages.spouseBirthdayWishes.ContainsKey(npc.Name) && Game1.player.isMarried())
{ {
Monitor.Log("Spouse Checks out"); this.Monitor.Log("Spouse Checks out");
//Check to see if spouse message exists. //Check to see if spouse message exists.
if (!String.IsNullOrEmpty(messages.spouseBirthdayWishes[npc.Name])) if (!string.IsNullOrEmpty(this.messages.spouseBirthdayWishes[npc.Name]))
{ {
spouseMessage = true; spouseMessage = true;
Dialogue d = new Dialogue(messages.spouseBirthdayWishes[npc.Name], npc); Dialogue d = new Dialogue(this.messages.spouseBirthdayWishes[npc.Name], npc);
npc.CurrentDialogue.Push(d); npc.CurrentDialogue.Push(d);
if (npc.CurrentDialogue.ElementAt(0) != d) npc.setNewDialogue(messages.spouseBirthdayWishes[npc.Name]); if (npc.CurrentDialogue.ElementAt(0) != d) npc.setNewDialogue(this.messages.spouseBirthdayWishes[npc.Name]);
} }
else else
{ this.Monitor.Log("No spouse message???", LogLevel.Warn);
Monitor.Log("No spouse message???", LogLevel.Warn);
} }
} if (!spouseMessage)
if (spouseMessage == false)
{ {
//Load in //Load in
Dialogue d = new Dialogue(messages.birthdayWishes[npc.Name], npc); Dialogue d = new Dialogue(this.messages.birthdayWishes[npc.Name], npc);
npc.CurrentDialogue.Push(d); npc.CurrentDialogue.Push(d);
if (npc.CurrentDialogue.ElementAt(0) != d) npc.setNewDialogue(messages.birthdayWishes[npc.Name]); if (npc.CurrentDialogue.ElementAt(0) != d) npc.setNewDialogue(this.messages.birthdayWishes[npc.Name]);
} }
} }
} }
@ -480,12 +430,11 @@ namespace Omegasis.HappyBirthday
} }
//Don't constantly set the birthday menu. //Don't constantly set the birthday menu.
if (Game1.activeClickableMenu != null) if (Game1.activeClickableMenu?.GetType() == typeof(BirthdayMenu))
{ return;
if (Game1.activeClickableMenu.GetType() == typeof(BirthdayMenu)) return;
}
// ask for birthday date // ask for birthday date
if (!this.HasChosenBirthday && Game1.activeClickableMenu==null) if (!this.HasChosenBirthday && Game1.activeClickableMenu == null)
{ {
Game1.activeClickableMenu = new BirthdayMenu(this.PlayerData.BirthdaySeason, this.PlayerData.BirthdayDay, this.SetBirthday); Game1.activeClickableMenu = new BirthdayMenu(this.PlayerData.BirthdaySeason, this.PlayerData.BirthdayDay, this.SetBirthday);
this.CheckedForBirthday = false; this.CheckedForBirthday = false;
@ -501,7 +450,7 @@ namespace Omegasis.HappyBirthday
{ {
try try
{ {
giftManager.SetNextBirthdayGift(Game1.currentSpeaker.Name); this.giftManager.SetNextBirthdayGift(Game1.currentSpeaker.Name);
this.VillagerQueue.Remove(Game1.currentSpeaker.Name); this.VillagerQueue.Remove(Game1.currentSpeaker.Name);
} }
catch (Exception ex) catch (Exception ex)
@ -511,15 +460,14 @@ namespace Omegasis.HappyBirthday
} }
//Validate the gift and give it to the player. //Validate the gift and give it to the player.
if (giftManager.BirthdayGiftToReceive != null) if (this.giftManager.BirthdayGiftToReceive != null)
{ {
while (giftManager.BirthdayGiftToReceive.Name == "Error Item" || giftManager.BirthdayGiftToReceive.Name == "Rock" || giftManager.BirthdayGiftToReceive.Name == "???") while (this.giftManager.BirthdayGiftToReceive.Name == "Error Item" || this.giftManager.BirthdayGiftToReceive.Name == "Rock" || this.giftManager.BirthdayGiftToReceive.Name == "???")
giftManager.SetNextBirthdayGift(Game1.currentSpeaker.Name); this.giftManager.SetNextBirthdayGift(Game1.currentSpeaker.Name);
Game1.player.addItemByMenuIfNecessaryElseHoldUp(giftManager.BirthdayGiftToReceive); Game1.player.addItemByMenuIfNecessaryElseHoldUp(this.giftManager.BirthdayGiftToReceive);
giftManager.BirthdayGiftToReceive = null; this.giftManager.BirthdayGiftToReceive = null;
} }
} }
} }
/// <summary>Set the player's birthday/</summary> /// <summary>Set the player's birthday/</summary>
@ -564,12 +512,13 @@ namespace Omegasis.HappyBirthday
try try
{ {
if (!File.Exists(this.LegacyDataFilePath) || File.Exists(this.DataFilePath)) if (!File.Exists(this.LegacyDataFilePath) || File.Exists(this.DataFilePath))
if (this.PlayerData == null) this.PlayerData = new PlayerData();
return;
}
catch(Exception err)
{ {
err.ToString(); if (this.PlayerData == null)
this.PlayerData = new PlayerData();
}
}
catch
{
// migrate to new file // migrate to new file
try try
{ {
@ -590,10 +539,6 @@ namespace Omegasis.HappyBirthday
this.Monitor.Log($"Error migrating data from the legacy 'Player_Birthdays' folder for the current player. Technical details:\n {ex}", LogLevel.Error); this.Monitor.Log($"Error migrating data from the legacy 'Player_Birthdays' folder for the current player. Technical details:\n {ex}", LogLevel.Error);
} }
} }
} }
} }
} }

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -11,8 +11,6 @@
<AssemblyName>HappyBirthday</AssemblyName> <AssemblyName>HappyBirthday</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -71,9 +69,10 @@
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL"> <PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
<HintPath>..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll</HintPath> <PackageReference Include="Pathoschild.Stardew.ModBuildConfig" Version="2.2.0" />
</Reference> </ItemGroup>
<ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
@ -98,22 +97,11 @@
<None Include="manifest.json" /> <None Include="manifest.json" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="packages.config" />
<None Include="README.md" /> <None Include="README.md" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Content Include="Changelog.txt" /> <Content Include="Changelog.txt" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\analyzers\dotnet\cs\StardewModdingAPI.ModBuildConfig.Analyzer.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\deploy.targets" /> <Import Project="$(SolutionDir)\deploy.targets" />
<Import Project="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\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>
<Error Condition="!Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets'))" />
</Target>
</Project> </Project>

View File

@ -2,7 +2,6 @@
"Name": "Happy Birthday", "Name": "Happy Birthday",
"Author": "Alpha_Omegasis", "Author": "Alpha_Omegasis",
"Version": "1.8.2", "Version": "1.8.2",
"MinimumApiVersion": "1.15",
"Description": "Adds the farmer's birthday to the game.", "Description": "Adds the farmer's birthday to the game.",
"UniqueID": "Omegasis.HappyBirthday", "UniqueID": "Omegasis.HappyBirthday",
"EntryDll": "HappyBirthday.dll", "EntryDll": "HappyBirthday.dll",

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="11.0.2" targetFramework="net45" />
<package id="Pathoschild.Stardew.ModBuildConfig" version="2.2.0" targetFramework="net45" />
</packages>

View File

@ -1,31 +1,25 @@
using EventSystem.Framework;
using StardewModdingAPI;
using System; using System;
using System.Collections.Generic; using EventSystem.Framework;
using System.Linq; using StardewModdingAPI;
using System.Text;
using System.Threading.Tasks;
namespace EventSystem namespace EventSystem
{ {
/* // TODO: Make Bed/Sleep Event.
*TODO: Make Bed/Sleep Event. public class EventSystem : Mod
*
*
*/
public class EventSystem: Mod
{ {
public static IModHelper ModHelper; public static IModHelper ModHelper;
public static IMonitor ModMonitor; public static IMonitor ModMonitor;
public static EventManager eventManager; public static EventManager eventManager;
/// <summary>The mod entry point, called after the mod is first loaded.</summary>
/// <param name="helper">Provides simplified APIs for writing mods.</param>
public override void Entry(IModHelper helper) public override void Entry(IModHelper helper)
{ {
ModHelper = this.Helper; ModHelper = this.Helper;
ModMonitor = this.Monitor; ModMonitor = this.Monitor;
StardewModdingAPI.Events.GameEvents.UpdateTick += GameEvents_UpdateTick; StardewModdingAPI.Events.GameEvents.UpdateTick += this.GameEvents_UpdateTick;
StardewModdingAPI.Events.SaveEvents.AfterLoad += SaveEvents_AfterLoad; StardewModdingAPI.Events.SaveEvents.AfterLoad += this.SaveEvents_AfterLoad;
} }
private void SaveEvents_AfterLoad(object sender, EventArgs e) private void SaveEvents_AfterLoad(object sender, EventArgs e)
@ -35,8 +29,7 @@ namespace EventSystem
private void GameEvents_UpdateTick(object sender, EventArgs e) private void GameEvents_UpdateTick(object sender, EventArgs e)
{ {
if (eventManager == null) return; eventManager?.update();
eventManager.update();
} }
} }
} }

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -11,8 +11,6 @@
<AssemblyName>EventSystem</AssemblyName> <AssemblyName>EventSystem</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -67,6 +65,9 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Pathoschild.Stardew.ModBuildConfig" Version="2.2.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
@ -92,24 +93,7 @@
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="packages.config" /> <None Include="manifest.json" />
</ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\analyzers\dotnet\cs\StardewModdingAPI.ModBuildConfig.Analyzer.dll" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\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>
<Error Condition="!Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets'))" />
</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>
-->
</Project> </Project>

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventSystem.Framework namespace EventSystem.Framework
{ {

View File

@ -1,9 +1,5 @@
using StardewValley;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using StardewValley;
using System.Text;
using System.Threading.Tasks;
namespace EventSystem.Framework namespace EventSystem.Framework
{ {
@ -11,112 +7,81 @@ namespace EventSystem.Framework
{ {
public Dictionary<GameLocation, List<MapEvent>> mapEvents; public Dictionary<GameLocation, List<MapEvent>> mapEvents;
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor.
/// </summary>
public EventManager() public EventManager()
{ {
this.mapEvents = new Dictionary<GameLocation, List<MapEvent>>(); this.mapEvents = new Dictionary<GameLocation, List<MapEvent>>();
foreach(var v in Game1.locations) foreach (var v in Game1.locations)
{ this.addLocation(v.Name, false);
addLocation(v.Name, false);
}
} }
/// <summary> /// <summary>Adds an event to the map given the name of the map.</summary>
/// Adds an event to the map given the name of the map. public virtual void addEvent(string mapName, MapEvent mapEvent)
/// </summary>
/// <param name="mapName"></param>
/// <param name="mapEvent"></param>
public virtual void addEvent(string mapName,MapEvent mapEvent)
{
foreach(var pair in this.mapEvents)
{
if (pair.Key.Name == mapName)
{
pair.Value.Add(mapEvent);
}
}
}
/// <summary>
/// Adds an event to a map.
/// </summary>
/// <param name="Location"></param>
/// <param name="mapEvent"></param>
public virtual void addEvent(GameLocation Location, MapEvent mapEvent)
{ {
foreach (var pair in this.mapEvents) foreach (var pair in this.mapEvents)
{ {
if (pair.Key == Location) if (pair.Key.Name == mapName)
{
pair.Value.Add(mapEvent); pair.Value.Add(mapEvent);
} }
} }
}
/// <summary> /// <summary>Adds an event to a map.</summary>
/// Adds a location to have events handled. public virtual void addEvent(GameLocation location, MapEvent mapEvent)
/// </summary>
/// <param name="Location">The location to handle events.</param>
public virtual void addLocation(GameLocation Location)
{ {
EventSystem.ModMonitor.Log("Adding event processing for location: " + Location.Name); foreach (var pair in this.mapEvents)
this.mapEvents.Add(Location, new List<MapEvent>());
}
/// <summary>
/// Adds a location to have events handled.
/// </summary>
/// <param name="Location"></param>
/// <param name="Events"></param>
public virtual void addLocation(GameLocation Location,List<MapEvent> Events)
{ {
EventSystem.ModMonitor.Log("Adding event processing for location: " + Location.Name); if (pair.Key == location)
this.mapEvents.Add(Location, Events); pair.Value.Add(mapEvent);
}
} }
/// <summary> /// <summary>Adds a location to have events handled.</summary>
/// Adds a location to handle events. /// <param name="location">The location to handle events.</param>
/// </summary> public virtual void addLocation(GameLocation location)
/// <param name="Location">The name of the location. Can include farm buildings.</param> {
EventSystem.ModMonitor.Log($"Adding event processing for location: {location.Name}");
this.mapEvents.Add(location, new List<MapEvent>());
}
/// <summary>Adds a location to have events handled.</summary>
public virtual void addLocation(GameLocation location, List<MapEvent> events)
{
EventSystem.ModMonitor.Log($"Adding event processing for location: {location.Name}");
this.mapEvents.Add(location, events);
}
/// <summary>Adds a location to handle events.</summary>
/// <param name="location">The name of the location. Can include farm buildings.</param>
/// <param name="isStructure">Used if the building is a stucture. True=building.</param> /// <param name="isStructure">Used if the building is a stucture. True=building.</param>
public virtual void addLocation(string Location,bool isStructure) public virtual void addLocation(string location, bool isStructure)
{ {
EventSystem.ModMonitor.Log("Adding event processing for location: " + Location); EventSystem.ModMonitor.Log($"Adding event processing for location: {location}");
this.mapEvents.Add(Game1.getLocationFromName(Location,isStructure), new List<MapEvent>()); this.mapEvents.Add(Game1.getLocationFromName(location, isStructure), new List<MapEvent>());
} }
/// <summary> /// <summary>Adds a location to have events handled.</summary>
/// Adds a location to have events handled. /// <param name="location">The name of the location. Can include farm buildings.</param>
/// </summary>
/// <param name="Location">The name of the location. Can include farm buildings.</param>
/// <param name="isStructure">Used if the building is a stucture. True=building.</param> /// <param name="isStructure">Used if the building is a stucture. True=building.</param>
/// <param name="Events">A list of pre-initialized events.</param> /// <param name="events">A list of pre-initialized events.</param>
public virtual void addLocation(string Location, bool isStructure, List<MapEvent> Events) public virtual void addLocation(string location, bool isStructure, List<MapEvent> events)
{ {
EventSystem.ModMonitor.Log("Adding event processing for location: " + Location); EventSystem.ModMonitor.Log($"Adding event processing for location: {location}");
this.mapEvents.Add(Game1.getLocationFromName(Location,isStructure), Events); this.mapEvents.Add(Game1.getLocationFromName(location, isStructure), events);
} }
/// <summary> /// <summary>Updates all events associated with the event manager.</summary>
/// Updates all events associated with the event manager.
/// </summary>
public virtual void update() public virtual void update()
{ {
List<MapEvent> events = new List<MapEvent>(); if (Game1.player == null)
if (Game1.player == null) return; return;
if (Game1.hasLoadedGame == false) return; if (!Game1.hasLoadedGame)
bool ok=this.mapEvents.TryGetValue(Game1.player.currentLocation, out events); return;
if (ok == false) return;
else if (this.mapEvents.TryGetValue(Game1.player.currentLocation, out List<MapEvent> events))
{
foreach(var v in events)
{ {
foreach (var v in events)
v.update(); v.update();
} }
} }
} }
}
} }

View File

@ -1,19 +1,15 @@
using EventSystem.Framework.FunctionEvents; using EventSystem.Framework.FunctionEvents;
using EventSystem.Framework.Information;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using StardewValley; using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventSystem.Framework.Events namespace EventSystem.Framework.Events
{ {
public class DialogueDisplayEvent :MapEvent public class DialogueDisplayEvent : MapEvent
{ {
string dialogue; private readonly string dialogue;
public DialogueDisplayEvent(string Name, GameLocation Location, Vector2 Position, MouseButtonEvents MouseEvents,MouseEntryLeaveEvent EntryLeave, string Dialogue) : base(Name, Location, Position)
public DialogueDisplayEvent(string Name, GameLocation Location, Vector2 Position, MouseButtonEvents MouseEvents, MouseEntryLeaveEvent EntryLeave, string Dialogue)
: base(Name, Location, Position)
{ {
this.name = Name; this.name = Name;
this.location = Location; this.location = Location;
@ -26,18 +22,15 @@ namespace EventSystem.Framework.Events
this.mouseEntryLeaveEvents = EntryLeave; this.mouseEntryLeaveEvents = EntryLeave;
} }
public override bool OnLeftClick() public override bool OnLeftClick()
{ {
if (base.OnLeftClick() == false) return false; if (!base.OnLeftClick()) return false;
if (this.location.isObjectAt((int)this.tilePosition.X*Game1.tileSize, (int)this.tilePosition.Y*Game1.tileSize)) return false; if (this.location.isObjectAt((int)this.tilePosition.X * Game1.tileSize, (int)this.tilePosition.Y * Game1.tileSize)) return false;
Game1.activeClickableMenu = new StardewValley.Menus.DialogueBox(this.dialogue); Game1.activeClickableMenu = new StardewValley.Menus.DialogueBox(this.dialogue);
return true; return true;
} }
/// <summary> /// <summary>Used to update the event and check for interaction.</summary>
/// Used to update the event and check for interaction.
/// </summary>
public override void update() public override void update()
{ {
this.clickEvent(); this.clickEvent();
@ -45,6 +38,5 @@ namespace EventSystem.Framework.Events
this.OnMouseEnter(); this.OnMouseEnter();
this.OnMouseLeave(); this.OnMouseLeave();
} }
} }
} }

View File

@ -1,31 +1,23 @@
using EventSystem.Framework.FunctionEvents; using EventSystem.Framework.FunctionEvents;
using EventSystem.Framework.Information; using EventSystem.Framework.Information;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using StardewValley; using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventSystem.Framework.Events namespace EventSystem.Framework.Events
{ {
/// <summary> /// <summary>Used to handle warp events on the map.</summary>
/// Used to handle warp events on the map. public class WarpEvent : MapEvent
/// </summary>
public class WarpEvent :MapEvent
{ {
WarpInformation warpInfo; private readonly WarpInformation warpInfo;
/// <summary> /// <summary>Constructor for handling warp events.</summary>
/// Constructor for handling warp events.
/// </summary>
/// <param name="Name">The name of the event.</param> /// <param name="Name">The name of the event.</param>
/// <param name="Location">The game location that this event is located at.</param> /// <param name="Location">The game location that this event is located at.</param>
/// <param name="Position">The x,y tile position of the event.</param> /// <param name="Position">The x,y tile position of the event.</param>
/// <param name="playerEvents">The events to occur when the player enters the warp tile before the warp.</param> /// <param name="playerEvents">The events to occur when the player enters the warp tile before the warp.</param>
/// <param name="WarpInfo">The information for warping the farmer.</param> /// <param name="WarpInfo">The information for warping the farmer.</param>
public WarpEvent(string Name, GameLocation Location, Vector2 Position, PlayerEvents playerEvents,WarpInformation WarpInfo) : base(Name, Location, Position, playerEvents) public WarpEvent(string Name, GameLocation Location, Vector2 Position, PlayerEvents playerEvents, WarpInformation WarpInfo)
: base(Name, Location, Position, playerEvents)
{ {
this.name = Name; this.name = Name;
this.location = Location; this.location = Location;
@ -36,38 +28,28 @@ namespace EventSystem.Framework.Events
this.doesInteractionNeedToRun = true; this.doesInteractionNeedToRun = true;
} }
/// <summary> /// <summary>Occurs when the player enters the warp tile event position.</summary>
/// Occurs when the player enters the warp tile event position.
/// </summary>
public override bool OnPlayerEnter() public override bool OnPlayerEnter()
{ {
if (base.OnPlayerEnter() == false) return false; if (!base.OnPlayerEnter())
else return false;
{
Game1.warpFarmer(this.warpInfo.targetMapName, this.warpInfo.targetX, this.warpInfo.targetY, this.warpInfo.facingDirection, this.warpInfo.isStructure); Game1.warpFarmer(this.warpInfo.targetMapName, this.warpInfo.targetX, this.warpInfo.targetY, this.warpInfo.facingDirection, this.warpInfo.isStructure);
return true; return true;
} }
}
/// <summary> /// <summary>Runs when the player is not on the tile and resets player interaction.</summary>
/// Runs when the player is not on the tile and resets player interaction.
/// </summary>
public override bool OnPlayerLeave() public override bool OnPlayerLeave()
{ {
if (base.OnPlayerLeave() == false) return false; if (!base.OnPlayerLeave()) return false;
return true; return true;
} }
/// <summary> /// <summary>Used to update the event and check for interaction.</summary>
/// Used to update the event and check for interaction.
/// </summary>
public override void update() public override void update()
{ {
this.OnPlayerEnter(); this.OnPlayerEnter();
this.OnPlayerLeave(); this.OnPlayerLeave();
} }
} }
} }

View File

@ -1,43 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventSystem.Framework.FunctionEvents namespace EventSystem.Framework.FunctionEvents
{ {
/// <summary> /// <summary>Used to handle mouse interactions with button clicks and scrolling the mouse wheel.</summary>
/// Used to handle mouse interactions with button clicks and scrolling the mouse wheel.
/// </summary>
public class MouseButtonEvents public class MouseButtonEvents
{ {
/// <summary> /// <summary>Function that runs when the user left clicks.</summary>
/// Function that runs when the user left clicks.
/// </summary>
public functionEvent onLeftClick; public functionEvent onLeftClick;
/// <summary>
/// Function that runs when the user right clicks. /// <summary>Function that runs when the user right clicks.</summary>
/// </summary>
public functionEvent onRightClick; public functionEvent onRightClick;
/// <summary>
/// Function that runs when the user scrolls the mouse wheel. /// <summary>Function that runs when the user scrolls the mouse wheel.</summary>
/// </summary>
public functionEvent onMouseScroll; public functionEvent onMouseScroll;
/// <summary> /// <summary>A constructor used to set a single function to a mouse button.</summary>
/// A constructor used to set a single function to a mouse button.
/// </summary>
/// <param name="clickFunction"></param> /// <param name="clickFunction"></param>
/// <param name="leftClick">If true the function is set to the left click. If false the function is set to the right click.</param> /// <param name="leftClick">If true the function is set to the left click. If false the function is set to the right click.</param>
public MouseButtonEvents(functionEvent clickFunction, bool leftClick) public MouseButtonEvents(functionEvent clickFunction, bool leftClick)
{ {
if (leftClick == true) this.onLeftClick = clickFunction; if (leftClick) this.onLeftClick = clickFunction;
else this.onRightClick = clickFunction; else this.onRightClick = clickFunction;
} }
/// <summary> /// <summary>A constructor used to map functions to mouse clicks.</summary>
/// A constructor used to map functions to mouse clicks.
/// </summary>
/// <param name="OnLeftClick">A function to be ran when the mouse left clicks this position.</param> /// <param name="OnLeftClick">A function to be ran when the mouse left clicks this position.</param>
/// <param name="OnRightClick">A function to be ran when the mouse right clicks this position.</param> /// <param name="OnRightClick">A function to be ran when the mouse right clicks this position.</param>
public MouseButtonEvents(functionEvent OnLeftClick, functionEvent OnRightClick) public MouseButtonEvents(functionEvent OnLeftClick, functionEvent OnRightClick)
@ -46,13 +30,11 @@ namespace EventSystem.Framework.FunctionEvents
this.onRightClick = OnRightClick; this.onRightClick = OnRightClick;
} }
/// <summary> /// <summary>A constructor used to map functions to mouse clicks and scrolling the mouse wheel.</summary>
/// A constructor used to map functions to mouse clicks and scrolling the mouse wheel.
/// </summary>
/// <param name="OnLeftClick">A function to be ran when the mouse left clicks this position.</param> /// <param name="OnLeftClick">A function to be ran when the mouse left clicks this position.</param>
/// <param name="OnRightClick">A function to be ran when the mouse right clicks this position.</param> /// <param name="OnRightClick">A function to be ran when the mouse right clicks this position.</param>
/// <param name="OnMouseScroll">A function to be ran when the user scrolls the mouse</param> /// <param name="OnMouseScroll">A function to be ran when the user scrolls the mouse</param>
public MouseButtonEvents(functionEvent OnLeftClick,functionEvent OnRightClick, functionEvent OnMouseScroll) public MouseButtonEvents(functionEvent OnLeftClick, functionEvent OnRightClick, functionEvent OnMouseScroll)
{ {
this.onLeftClick = OnLeftClick; this.onLeftClick = OnLeftClick;
this.onRightClick = OnRightClick; this.onRightClick = OnRightClick;

View File

@ -1,28 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventSystem.Framework.FunctionEvents namespace EventSystem.Framework.FunctionEvents
{ {
/// <summary> /// <summary>Used to handle events that happens when a mouse enters/leaves a specified position.</summary>
/// Used to handle events that happens when a mouse enters/leaves a specified position.
/// </summary>
public class MouseEntryLeaveEvent public class MouseEntryLeaveEvent
{ {
/// <summary> /// <summary>A function that is called when a mouse enters a certain position.</summary>
/// A function that is called when a mouse enters a certain position.
/// </summary>
public functionEvent onMouseEnter; public functionEvent onMouseEnter;
/// <summary>
/// A function that is called when a mouse leaves a certain position. /// <summary>A function that is called when a mouse leaves a certain position.</summary>
/// </summary>
public functionEvent onMouseLeave; public functionEvent onMouseLeave;
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor.
/// </summary>
/// <param name="OnMouseEnter">The function that occurs when the mouse enters a certain position.</param> /// <param name="OnMouseEnter">The function that occurs when the mouse enters a certain position.</param>
/// <param name="OnMouseLeave">The function that occurs when the mouse leaves a certain position.</param> /// <param name="OnMouseLeave">The function that occurs when the mouse leaves a certain position.</param>
public MouseEntryLeaveEvent(functionEvent OnMouseEnter, functionEvent OnMouseLeave) public MouseEntryLeaveEvent(functionEvent OnMouseEnter, functionEvent OnMouseLeave)

View File

@ -1,30 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventSystem.Framework.FunctionEvents namespace EventSystem.Framework.FunctionEvents
{ {
/// <summary> /// <summary>Used to handle various functions that occur on player interaction.</summary>
/// Used to handle various functions that occur on player interaction.
/// </summary>
public class PlayerEvents public class PlayerEvents
{ {
/// <summary> /// <summary>Occurs when the player enters the same tile as this event.</summary>
/// Occurs when the player enters the same tile as this event.
/// </summary>
public functionEvent onPlayerEnter; public functionEvent onPlayerEnter;
/// <summary>
/// Occurs when the player leaves the same tile as this event. /// <summary>Occurs when the player leaves the same tile as this event.</summary>
/// </summary>
public functionEvent onPlayerLeave; public functionEvent onPlayerLeave;
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor. /// <param name="OnPlayerEnter">Occurs when the player enters the same tile as this event.</param>
/// </summary> /// <param name="OnPlayerLeave">Occurs when the player leaves the same tile as this event.</param>
/// <param name="OnPlayerEnter"></param>
/// <param name="OnPlayerLeave"></param>
public PlayerEvents(functionEvent OnPlayerEnter, functionEvent OnPlayerLeave) public PlayerEvents(functionEvent OnPlayerEnter, functionEvent OnPlayerLeave)
{ {
this.onPlayerEnter = OnPlayerEnter; this.onPlayerEnter = OnPlayerEnter;

View File

@ -1,23 +1,15 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static EventSystem.Framework.Delegates; using static EventSystem.Framework.Delegates;
namespace EventSystem.Framework namespace EventSystem.Framework
{ {
/// <summary> /// <summary>Used to pair a function and a parameter list using the super object class to run virtually any function for map events.</summary>
/// Used to pair a function and a parameter list using the super object class to run virtually any function for map events.
/// </summary>
public class functionEvent public class functionEvent
{ {
public paramFunction function; public paramFunction function;
public List<object> parameters; public List<object> parameters;
/// <summary> /// <summary>Construct an instance.</summary>
/// Constructor.
/// </summary>
/// <param name="Function">The function to be called when running an event.</param> /// <param name="Function">The function to be called when running an event.</param>
/// <param name="Parameters">The list of system.objects to be used in the function. Can include objects,strings, ints, etc. Anything can be passed in as a parameter or can be passed in as empty. Passing in null will just create an empty list.</param> /// <param name="Parameters">The list of system.objects to be used in the function. Can include objects,strings, ints, etc. Anything can be passed in as a parameter or can be passed in as empty. Passing in null will just create an empty list.</param>
public functionEvent(paramFunction Function, List<object> Parameters) public functionEvent(paramFunction Function, List<object> Parameters)
@ -27,17 +19,13 @@ namespace EventSystem.Framework
this.parameters = Parameters; this.parameters = Parameters;
} }
/// <summary> /// <summary>Runs the function with the passed in parameters.</summary>
/// Runs the function with the passed in parameters.
/// </summary>
public void run() public void run()
{ {
this.function.Invoke(this.parameters); this.function.Invoke(this.parameters);
} }
/// <summary> /// <summary>Simply swaps out the old parameters list for a new one.</summary>
/// Simply swaps out the old parameters list for a new one.
/// </summary>
/// <param name="newParameters"></param> /// <param name="newParameters"></param>
public void updateParameters(List<object> newParameters) public void updateParameters(List<object> newParameters)
{ {

View File

@ -1,14 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventSystem.Framework.Information namespace EventSystem.Framework.Information
{ {
/// <summary> /// <summary>Used to store all of the information necessary to warp the farmer.</summary>
/// Used to store all of the information necessary to warp the farmer.
/// </summary>
public class WarpInformation public class WarpInformation
{ {
public string targetMapName; public string targetMapName;
@ -17,15 +9,13 @@ namespace EventSystem.Framework.Information
public int facingDirection; public int facingDirection;
public bool isStructure; public bool isStructure;
/// <summary> /// <summary>Constructor used to bundle together necessary information to warp the player character.</summary>
/// Constructor used to bundle together necessary information to warp the player character.
/// </summary>
/// <param name="MapName">The target map name to warp the farmer to.</param> /// <param name="MapName">The target map name to warp the farmer to.</param>
/// <param name="TargetX">The target X location on the map to warp the farmer to.</param> /// <param name="TargetX">The target X location on the map to warp the farmer to.</param>
/// <param name="TargetY">The target Y location on the map to warp the farmer to.</param> /// <param name="TargetY">The target Y location on the map to warp the farmer to.</param>
/// <param name="FacingDirection">The facing direction for the farmer to be facing after the warp.</param> /// <param name="FacingDirection">The facing direction for the farmer to be facing after the warp.</param>
/// <param name="IsStructure">Used to determine the position to be warped to when leaving a structure.</param> /// <param name="IsStructure">Used to determine the position to be warped to when leaving a structure.</param>
public WarpInformation(string MapName, int TargetX,int TargetY, int FacingDirection, bool IsStructure) public WarpInformation(string MapName, int TargetX, int TargetY, int FacingDirection, bool IsStructure)
{ {
this.targetMapName = MapName; this.targetMapName = MapName;
this.targetX = TargetX; this.targetX = TargetX;

View File

@ -1,25 +1,15 @@
using EventSystem.Framework.FunctionEvents; using EventSystem.Framework.FunctionEvents;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input;
using StardewValley; using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventSystem.Framework namespace EventSystem.Framework
{ {
/// <summary> /// <summary>Base class used to handle map tile events.</summary>
/// Base class used to handle map tile events.
/// </summary>
public class MapEvent public class MapEvent
{ {
/// <summary> /// <summary>//MAKE NAME FOR EVENTS</summary>
/// //MAKE NAME FOR EVENTS
/// </summary>
public string name; public string name;
public Vector2 tilePosition; public Vector2 tilePosition;
@ -41,84 +31,64 @@ namespace EventSystem.Framework
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/ */
#region #region
/// <summary>Empty Constructor.</summary>
public MapEvent() { }
/// <summary>A simple map event that doesn't do anything.</summary>
/// <summary> public MapEvent(string name, GameLocation location, Vector2 position)
/// Empty Constructor
/// </summary>
public MapEvent()
{
}
/// <summary>
/// A simple map event that doesn't do anything.
/// </summary>
/// <param name="Location"></param>
/// <param name="Position"></param>
public MapEvent(string name,GameLocation Location,Vector2 Position)
{ {
this.name = name; this.name = name;
this.location = Location; this.location = location;
this.tilePosition = Position;
}
/// <summary>
/// A simple map function that runs when the player enters and leaves a tile. Set values to null for nothing to happen.
/// </summary>
/// <param name="Location">The game location where the event is. I.E Farm, Town, Mine etc.</param>
/// <param name="position">The x,y position on the map the event is.</param>
/// <param name="PlayerEvents">Handles various events that runs when the player enters/leaves a tile, etc.</param>
public MapEvent(string name,GameLocation Location,Vector2 position, PlayerEvents PlayerEvents)
{
this.name = name;
this.location = Location;
this.tilePosition = position; this.tilePosition = position;
this.playerEvents = PlayerEvents;
} }
/// <summary> /// <summary>A simple map function that runs when the player enters and leaves a tile. Set values to null for nothing to happen.</summary>
/// A constructor that handles when the mouse leaves and enters a tile. /// <param name="location">The game location where the event is. I.E Farm, Town, Mine etc.</param>
/// </summary> /// <param name="position">The x,y position on the map the event is.</param>
/// <param name="Location">The game location where the event is.</param> /// <param name="playerEvents">Handles various events that runs when the player enters/leaves a tile, etc.</param>
/// <param name="Position">The x,y position of the tile at the game location.</param> public MapEvent(string name, GameLocation location, Vector2 position, PlayerEvents playerEvents)
/// <param name="mouseEvents">A class used to handle mouse entry/leave events.</param>
public MapEvent(string name,GameLocation Location, Vector2 Position, MouseEntryLeaveEvent mouseEvents)
{ {
this.name = name; this.name = name;
this.location = Location; this.location = location;
this.tilePosition = Position; this.tilePosition = position;
this.playerEvents = playerEvents;
}
/// <summary>A constructor that handles when the mouse leaves and enters a tile.</summary>
/// <param name="location">The game location where the event is.</param>
/// <param name="position">The x,y position of the tile at the game location.</param>
/// <param name="mouseEvents">A class used to handle mouse entry/leave events.</param>
public MapEvent(string name, GameLocation location, Vector2 position, MouseEntryLeaveEvent mouseEvents)
{
this.name = name;
this.location = location;
this.tilePosition = position;
this.mouseEntryLeaveEvents = mouseEvents; this.mouseEntryLeaveEvents = mouseEvents;
} }
/// <summary> /// <summary>A constructor that handles when the mouse leaves and enters a tile.</summary>
/// A constructor that handles when the mouse leaves and enters a tile. /// <param name="location">The game location where the event is.</param>
/// </summary> /// <param name="position">The x,y position of the tile at the game location.</param>
/// <param name="Location">The game location where the event is.</param>
/// <param name="Position">The x,y position of the tile at the game location.</param>
/// <param name="mouseEvents">A class used to handle mouse click/scroll events.</param> /// <param name="mouseEvents">A class used to handle mouse click/scroll events.</param>
public MapEvent(string name,GameLocation Location, Vector2 Position, MouseButtonEvents mouseEvents) public MapEvent(string name, GameLocation location, Vector2 position, MouseButtonEvents mouseEvents)
{ {
this.name = name; this.name = name;
this.location = Location; this.location = location;
this.tilePosition = Position; this.tilePosition = position;
this.mouseButtonEvents = mouseEvents; this.mouseButtonEvents = mouseEvents;
} }
/// <summary> /// <summary>A constructor encapsulating player, mouse button, and mouse entry events.</summary>
/// A constructor encapsulating player, mouse button, and mouse entry events. /// <param name="location">The game location for which the event is located. I.E Town, Farm, etc.</param>
/// </summary> /// <param name="position">The x,y cordinates for this event to be located at.</param>
/// <param name="Location">The game location for which the event is located. I.E Town, Farm, etc.</param>
/// <param name="Position">The x,y cordinates for this event to be located at.</param>
/// <param name="playerEvents">The events that occur associated with the player. I.E player entry, etc.</param> /// <param name="playerEvents">The events that occur associated with the player. I.E player entry, etc.</param>
/// <param name="mouseButtonEvents">The events associated with clicking a mouse button while on this tile.</param> /// <param name="mouseButtonEvents">The events associated with clicking a mouse button while on this tile.</param>
/// <param name="mouseEntryLeaveEvents">The events that occur when the mouse enters or leaves the same tile position as this event.</param> /// <param name="mouseEntryLeaveEvents">The events that occur when the mouse enters or leaves the same tile position as this event.</param>
public MapEvent(string name,GameLocation Location, Vector2 Position, PlayerEvents playerEvents, MouseButtonEvents mouseButtonEvents, MouseEntryLeaveEvent mouseEntryLeaveEvents) public MapEvent(string name, GameLocation location, Vector2 position, PlayerEvents playerEvents, MouseButtonEvents mouseButtonEvents, MouseEntryLeaveEvent mouseEntryLeaveEvents)
{ {
this.name = name; this.name = name;
this.location = Location; this.location = location;
this.tilePosition = Position; this.tilePosition = position;
this.playerEvents = playerEvents; this.playerEvents = playerEvents;
this.mouseButtonEvents = mouseButtonEvents; this.mouseButtonEvents = mouseButtonEvents;
this.mouseEntryLeaveEvents = mouseEntryLeaveEvents; this.mouseEntryLeaveEvents = mouseEntryLeaveEvents;
@ -132,45 +102,40 @@ namespace EventSystem.Framework
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/ */
#region #region
/// <summary> /// <summary>Occurs when the player enters the same tile as this event. The function associated with this event is then ran.</summary>
/// Occurs when the player enters the same tile as this event. The function associated with this event is then ran.
/// </summary>
public virtual bool OnPlayerEnter() public virtual bool OnPlayerEnter()
{ {
if (this.playerEvents == null) return false; if (this.playerEvents == null) return false;
if (isPlayerOnTile() == true && this.doesInteractionNeedToRun==true) if (this.isPlayerOnTile() && this.doesInteractionNeedToRun)
{ {
this.playerOnTile = true; this.playerOnTile = true;
this.doesInteractionNeedToRun = false; this.doesInteractionNeedToRun = false;
if (this.playerEvents.onPlayerEnter != null) this.playerEvents.onPlayerEnter.run(); this.playerEvents.onPlayerEnter?.run();
return true; return true;
} }
return false; return false;
} }
/// <summary> /// <summary>Occurs when the player leaves the same tile that this event is on. The function associated with thie event is then ran.</summary>
/// Occurs when the player leaves the same tile that this event is on. The function associated with thie event is then ran.
/// </summary>
public virtual bool OnPlayerLeave() public virtual bool OnPlayerLeave()
{ {
if (this.playerEvents == null) return false; if (this.playerEvents == null) return false;
if (isPlayerOnTile() == false && this.playerOnTile==true){ if (!this.isPlayerOnTile() && this.playerOnTile)
{
this.playerOnTile = false; this.playerOnTile = false;
this.doesInteractionNeedToRun = true; this.doesInteractionNeedToRun = true;
if (this.playerEvents.onPlayerLeave != null) this.playerEvents.onPlayerLeave.run(); this.playerEvents.onPlayerLeave?.run();
return true; return true;
} }
return false; return false;
} }
/// <summary> /// <summary>Checks if the player is on the same tile as this event.</summary>
/// Checks if the player is on the same tile as this event.
/// </summary>
/// <returns></returns>
public virtual bool isPlayerOnTile() public virtual bool isPlayerOnTile()
{ {
if (Game1.player.getTileX() == this.tilePosition.X && Game1.player.getTileY() == this.tilePosition.Y) return true; return
else return false; Game1.player.getTileX() == this.tilePosition.X
&& Game1.player.getTileY() == this.tilePosition.Y;
} }
#endregion #endregion
@ -180,75 +145,60 @@ namespace EventSystem.Framework
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/ */
#region #region
/// <summary> /// <summary>Occurs when the player left clicks the same tile that this event is on.</summary>
/// Occurs when the player left clicks the same tile that this event is on.
/// </summary>
public virtual bool OnLeftClick() public virtual bool OnLeftClick()
{ {
if (this.mouseOnTile==false) return false; if (!this.mouseOnTile) return false;
if (this.mouseButtonEvents == null) return false; if (this.mouseButtonEvents == null) return false;
if (this.mouseButtonEvents.onLeftClick != null) this.mouseButtonEvents.onLeftClick.run(); this.mouseButtonEvents.onLeftClick?.run();
return true; return true;
} }
/// <summary> /// <summary>Occurs when the player right clicks the same tile that this event is on.</summary>
/// Occurs when the player right clicks the same tile that this event is on.
/// </summary>
public virtual bool OnRightClick() public virtual bool OnRightClick()
{ {
if (this.mouseOnTile == false) return false; if (!this.mouseOnTile) return false;
if (this.mouseButtonEvents == null) return false; if (this.mouseButtonEvents == null) return false;
if (this.mouseButtonEvents.onRightClick != null) this.mouseButtonEvents.onRightClick.run(); this.mouseButtonEvents.onRightClick?.run();
return true; return true;
} }
/// <summary> /// <summary>Occurs when the mouse tile position is the same as this event's x,y position.</summary>
/// Occurs when the mouse tile position is the same as this event's x,y position.
/// </summary>
public virtual bool OnMouseEnter() public virtual bool OnMouseEnter()
{ {
if (this.mouseEntryLeaveEvents == null) return false; if (this.mouseEntryLeaveEvents == null) return false;
if (isMouseOnTile()) if (this.isMouseOnTile())
{ {
this.mouseOnTile = true; this.mouseOnTile = true;
if (this.mouseEntryLeaveEvents.onMouseEnter != null) this.mouseEntryLeaveEvents.onMouseEnter.run(); this.mouseEntryLeaveEvents.onMouseEnter?.run();
return true; return true;
} }
return false; return false;
} }
/// <summary> /// <summary>Occurs when the mouse tile position leaves the the same x,y position as this event.</summary>
/// Occurs when the mouse tile position leaves the the same x,y position as this event.
/// </summary>
public virtual bool OnMouseLeave() public virtual bool OnMouseLeave()
{ {
if (this.mouseEntryLeaveEvents == null) return false; if (this.mouseEntryLeaveEvents == null) return false;
if (isMouseOnTile() == false && this.mouseOnTile == true) if (!this.isMouseOnTile() && this.mouseOnTile)
{ {
this.mouseOnTile = false; this.mouseOnTile = false;
if (this.mouseEntryLeaveEvents.onMouseLeave != null) this.mouseEntryLeaveEvents.onMouseLeave.run(); this.mouseEntryLeaveEvents.onMouseLeave?.run();
return true; return true;
} }
return false; return false;
} }
/// <summary> /// <summary>UNUSED!!!! Occurs when the mouse is on the same position as the tile AND the user scrolls the mouse wheel.</summary>
/// UNUSED!!!!
/// Occurs when the mouse is on the same position as the tile AND the user scrolls the mouse wheel.
/// </summary>
public virtual bool OnMouseScroll() public virtual bool OnMouseScroll()
{ {
if (!this.isMouseOnTile()) return false;
if (isMouseOnTile() == false) return false; this.mouseButtonEvents.onMouseScroll?.run();
if (this.mouseButtonEvents.onMouseScroll != null) this.mouseButtonEvents.onMouseScroll.run();
return true; return true;
} }
/// <summary> /// <summary>Checks if the mouse is on the tile.</summary>
/// Checks if the mouse is on the tile.
/// </summary>
/// <returns></returns>
public virtual bool isMouseOnTile() public virtual bool isMouseOnTile()
{ {
Vector2 mousePosition = Game1.currentCursorTile; Vector2 mousePosition = Game1.currentCursorTile;
@ -256,30 +206,27 @@ namespace EventSystem.Framework
return false; return false;
} }
/// <summary> /// <summary>Occurs when the tile is clicked. Runs the appropriate event.</summary>
/// Occurs when the tile is clicked. Runs the appropriate event.
/// </summary>
public virtual void clickEvent() public virtual void clickEvent()
{ {
if (this.mouseOnTile == false) return; if (!this.mouseOnTile) return;
var mouseState=Mouse.GetState(); var mouseState = Mouse.GetState();
if (mouseState.LeftButton == ButtonState.Pressed) OnLeftClick(); if (mouseState.LeftButton == ButtonState.Pressed)
if (mouseState.RightButton == ButtonState.Pressed) OnRightClick(); this.OnLeftClick();
if (mouseState.RightButton == ButtonState.Pressed)
this.OnRightClick();
} }
#endregion #endregion
/// <summary>Used to check if any sort of events need to run on this tile right now.</summary>
/// <summary>
/// Used to check if any sort of events need to run on this tile right now.
/// </summary>
public virtual void update() public virtual void update()
{ {
if (Game1.activeClickableMenu != null) return; if (Game1.activeClickableMenu != null) return;
clickEvent(); //click events this.clickEvent(); //click events
OnPlayerEnter(); //player enter events this.OnPlayerEnter(); //player enter events
OnPlayerLeave(); //player leave events this.OnPlayerLeave(); //player leave events
OnMouseEnter(); //on mouse enter events this.OnMouseEnter(); //on mouse enter events
OnMouseLeave(); //on mouse leave events. this.OnMouseLeave(); //on mouse leave events.
} }
} }
} }

View File

@ -6,5 +6,5 @@
"UniqueID": "Omegasis.EventSystem", "UniqueID": "Omegasis.EventSystem",
"EntryDll": "EventSystem.dll", "EntryDll": "EventSystem.dll",
"MinimumApiVersion": "2.0", "MinimumApiVersion": "2.0",
"UpdateKeys": [ ] "UpdateKeys": []
} }

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Pathoschild.Stardew.ModBuildConfig" version="2.2.0" targetFramework="net45" />
</packages>

View File

@ -1,4 +1,4 @@
namespace Omegasis.MoreRain.Framework namespace Omegasis.MoreRain.Framework
{ {
/// <summary>The mod configuration.</summary> /// <summary>The mod configuration.</summary>
internal class ModConfig internal class ModConfig

View File

@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Omegasis.MoreRain.Framework; using Omegasis.MoreRain.Framework;
using StardewModdingAPI; using StardewModdingAPI;
@ -88,7 +88,6 @@ namespace Omegasis.MoreRain
this.VerboseLog("It will be stormy tomorrow."); this.VerboseLog("It will be stormy tomorrow.");
return; return;
} }
break; break;
case "summer": case "summer":
@ -143,7 +142,7 @@ namespace Omegasis.MoreRain
} }
} }
/// <summary>Log a message if <see cref="SuppressLog"/> is <c>false</c>.</summary> /// <summary>Log a message if <see cref="ModConfig.SuppressLog"/> is <c>false</c>.</summary>
/// <param name="message">The message to log.</param> /// <param name="message">The message to log.</param>
private void VerboseLog(string message) private void VerboseLog(string message)
{ {

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.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')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -11,8 +11,6 @@
<AssemblyName>MoreRain</AssemblyName> <AssemblyName>MoreRain</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -67,6 +65,9 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Pathoschild.Stardew.ModBuildConfig" Version="2.2.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
@ -81,19 +82,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="manifest.json" /> <None Include="manifest.json" />
<None Include="packages.config" />
<None Include="README.md" /> <None Include="README.md" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\analyzers\dotnet\cs\StardewModdingAPI.ModBuildConfig.Analyzer.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\deploy.targets" /> <Import Project="$(SolutionDir)\deploy.targets" />
<Import Project="..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets" Condition="Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\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>
<Error Condition="!Exists('..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Pathoschild.Stardew.ModBuildConfig.2.2.0\build\Pathoschild.Stardew.ModBuildConfig.targets'))" />
</Target>
</Project> </Project>

Some files were not shown because too many files have changed in this diff Show More