├── Engine ├── Images │ ├── Monsters │ │ ├── Rat.png │ │ ├── Snake.png │ │ └── GiantSpider.png │ └── Locations │ │ ├── Home.png │ │ ├── TownGate.png │ │ ├── Trader.png │ │ ├── FarmFields.png │ │ ├── Farmhouse.png │ │ ├── TownSquare.png │ │ ├── HerbalistsHut.png │ │ ├── SpiderForest.png │ │ └── HerbalistsGarden.png ├── EventArgs │ ├── CombatVictoryEventArgs.cs │ └── GameMessageEventArgs.cs ├── Actions │ ├── IAction.cs │ ├── BaseAction.cs │ ├── Heal.cs │ └── AttackWithWeapon.cs ├── Models │ ├── Trader.cs │ ├── ItemPercentage.cs │ ├── MonsterEncounter.cs │ ├── ItemQuantity.cs │ ├── QuestStatus.cs │ ├── World.cs │ ├── GroupedInventoryItem.cs │ ├── GameItem.cs │ ├── Recipe.cs │ ├── Quest.cs │ ├── Monster.cs │ ├── Player.cs │ ├── Inventory.cs │ ├── Location.cs │ ├── Battle.cs │ └── LivingEntity.cs ├── GameData │ ├── Recipes.xml │ ├── Quests.xml │ ├── Traders.xml │ ├── Monsters.xml │ ├── GameItems.xml │ └── Locations.xml ├── BaseNotificationClass.cs ├── Shared │ └── ExtensionMethods.cs ├── Services │ ├── MessageBroker.cs │ ├── LoggingService.cs │ └── InventoryService.cs ├── Properties │ ├── AssemblyInfo.cs │ └── Annotations.cs ├── RandomNumberGenerator.cs ├── Factories │ ├── RecipeFactory.cs │ ├── TraderFactory.cs │ ├── QuestFactory.cs │ ├── MonsterFactory.cs │ ├── ItemFactory.cs │ └── WorldFactory.cs ├── Engine.csproj └── ViewModels │ └── GameSession.cs ├── WPFUI ├── App.config ├── Properties │ ├── Settings.settings │ ├── Settings.Designer.cs │ ├── AssemblyInfo.cs │ ├── Resources.Designer.cs │ └── Resources.resx ├── App.xaml ├── App.xaml.cs ├── CustomConverters │ └── FileToBitmapConverter.cs ├── TradeScreen.xaml.cs ├── MainWindow.xaml.cs ├── TradeScreen.xaml ├── WPFUI.csproj └── MainWindow.xaml ├── TestEngine ├── packages.config ├── Properties │ └── AssemblyInfo.cs ├── ViewModels │ └── TestGameSession.cs ├── Actions │ └── TestAttackWithWeapon.cs ├── TestEngine.csproj └── Models │ └── TestInventory.cs ├── README.md ├── SOSCSRPG.sln.DotSettings ├── LICENSE ├── SOSCSRPG.sln ├── .gitattributes └── .gitignore /Engine/Images/Monsters/Rat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/SOSCSRPG/HEAD/Engine/Images/Monsters/Rat.png -------------------------------------------------------------------------------- /Engine/Images/Locations/Home.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/SOSCSRPG/HEAD/Engine/Images/Locations/Home.png -------------------------------------------------------------------------------- /Engine/Images/Monsters/Snake.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/SOSCSRPG/HEAD/Engine/Images/Monsters/Snake.png -------------------------------------------------------------------------------- /Engine/Images/Locations/TownGate.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/SOSCSRPG/HEAD/Engine/Images/Locations/TownGate.png -------------------------------------------------------------------------------- /Engine/Images/Locations/Trader.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/SOSCSRPG/HEAD/Engine/Images/Locations/Trader.png -------------------------------------------------------------------------------- /Engine/Images/Locations/FarmFields.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/SOSCSRPG/HEAD/Engine/Images/Locations/FarmFields.png -------------------------------------------------------------------------------- /Engine/Images/Locations/Farmhouse.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/SOSCSRPG/HEAD/Engine/Images/Locations/Farmhouse.png -------------------------------------------------------------------------------- /Engine/Images/Locations/TownSquare.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/SOSCSRPG/HEAD/Engine/Images/Locations/TownSquare.png -------------------------------------------------------------------------------- /Engine/Images/Monsters/GiantSpider.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/SOSCSRPG/HEAD/Engine/Images/Monsters/GiantSpider.png -------------------------------------------------------------------------------- /Engine/Images/Locations/HerbalistsHut.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/SOSCSRPG/HEAD/Engine/Images/Locations/HerbalistsHut.png -------------------------------------------------------------------------------- /Engine/Images/Locations/SpiderForest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/SOSCSRPG/HEAD/Engine/Images/Locations/SpiderForest.png -------------------------------------------------------------------------------- /Engine/Images/Locations/HerbalistsGarden.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nirzaf/SOSCSRPG/HEAD/Engine/Images/Locations/HerbalistsGarden.png -------------------------------------------------------------------------------- /Engine/EventArgs/CombatVictoryEventArgs.cs: -------------------------------------------------------------------------------- 1 | namespace Engine.EventArgs 2 | { 3 | public class CombatVictoryEventArgs : System.EventArgs 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /WPFUI/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /WPFUI/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /TestEngine/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /Engine/Actions/IAction.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Engine.Models; 3 | 4 | namespace Engine.Actions 5 | { 6 | public interface IAction 7 | { 8 | event EventHandler OnActionPerformed; 9 | void Execute(LivingEntity actor, LivingEntity target); 10 | } 11 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SOSCSRPG - Scott's Open Source C# RPG 2 | 3 | This is a simple role-playing game, written in C#, using WPF. 4 | 5 | 6 | More details available at: https://scottlilly.com/build-a-cwpf-rpg/ 7 | -------------------------------------------------------------------------------- /Engine/Models/Trader.cs: -------------------------------------------------------------------------------- 1 | namespace Engine.Models 2 | { 3 | public class Trader : LivingEntity 4 | { 5 | public int ID { get; } 6 | 7 | public Trader(int id, string name) : base(name, 9999, 9999, 9999) 8 | { 9 | ID = id; 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Engine/EventArgs/GameMessageEventArgs.cs: -------------------------------------------------------------------------------- 1 | namespace Engine.EventArgs 2 | { 3 | public class GameMessageEventArgs : System.EventArgs 4 | { 5 | public string Message { get; private set; } 6 | 7 | public GameMessageEventArgs(string message) 8 | { 9 | Message = message; 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Engine/Models/ItemPercentage.cs: -------------------------------------------------------------------------------- 1 | namespace Engine.Models 2 | { 3 | public class ItemPercentage 4 | { 5 | public int ID { get; } 6 | public int Percentage { get; } 7 | 8 | public ItemPercentage(int id, int percentage) 9 | { 10 | ID = id; 11 | Percentage = percentage; 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Engine/GameData/Recipes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Engine/Models/MonsterEncounter.cs: -------------------------------------------------------------------------------- 1 | namespace Engine.Models 2 | { 3 | public class MonsterEncounter 4 | { 5 | public int MonsterID { get; } 6 | public int ChanceOfEncountering { get; set; } 7 | 8 | public MonsterEncounter(int monsterID, int chanceOfEncountering) 9 | { 10 | MonsterID = monsterID; 11 | ChanceOfEncountering = chanceOfEncountering; 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Engine/GameData/Quests.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Engine/Models/ItemQuantity.cs: -------------------------------------------------------------------------------- 1 | using Engine.Factories; 2 | 3 | namespace Engine.Models 4 | { 5 | public class ItemQuantity 6 | { 7 | public int ItemID { get; } 8 | public int Quantity { get; } 9 | 10 | public string QuantityItemDescription => 11 | $"{Quantity} {ItemFactory.ItemName(ItemID)}"; 12 | 13 | public ItemQuantity(int itemID, int quantity) 14 | { 15 | ItemID = itemID; 16 | Quantity = quantity; 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Engine/BaseNotificationClass.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Runtime.CompilerServices; 3 | 4 | namespace Engine 5 | { 6 | public class BaseNotificationClass : INotifyPropertyChanged 7 | { 8 | public event PropertyChangedEventHandler PropertyChanged; 9 | 10 | protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "") 11 | { 12 | PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Engine/Actions/BaseAction.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Engine.Models; 3 | 4 | namespace Engine.Actions 5 | { 6 | public abstract class BaseAction 7 | { 8 | protected readonly GameItem _itemInUse; 9 | 10 | public event EventHandler OnActionPerformed; 11 | 12 | protected BaseAction(GameItem itemInUse) 13 | { 14 | _itemInUse = itemInUse; 15 | } 16 | 17 | protected void ReportResult(string result) 18 | { 19 | OnActionPerformed?.Invoke(this, result); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /WPFUI/App.xaml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Engine/GameData/Traders.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Engine/Models/QuestStatus.cs: -------------------------------------------------------------------------------- 1 | namespace Engine.Models 2 | { 3 | public class QuestStatus : BaseNotificationClass 4 | { 5 | private bool _isCompleted; 6 | 7 | public Quest PlayerQuest { get; } 8 | public bool IsCompleted 9 | { 10 | get { return _isCompleted;} 11 | set 12 | { 13 | _isCompleted = value; 14 | OnPropertyChanged(); 15 | } 16 | } 17 | 18 | public QuestStatus(Quest quest) 19 | { 20 | PlayerQuest = quest; 21 | IsCompleted = false; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /SOSCSRPG.sln.DotSettings: -------------------------------------------------------------------------------- 1 | 2 | True 3 | True 4 | True -------------------------------------------------------------------------------- /TestEngine/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("TestEngine")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("")] 9 | [assembly: AssemblyProduct("TestEngine")] 10 | [assembly: AssemblyCopyright("Copyright © 2018")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("e4073809-b6f2-4230-84d4-3dfeabe7e41f")] 17 | 18 | // [assembly: AssemblyVersion("1.0.*")] 19 | [assembly: AssemblyVersion("1.0.0.0")] 20 | [assembly: AssemblyFileVersion("1.0.0.0")] 21 | -------------------------------------------------------------------------------- /WPFUI/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | using System.Windows.Threading; 3 | using Engine.Services; 4 | 5 | namespace WPFUI 6 | { 7 | public partial class App : Application 8 | { 9 | private void App_OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) 10 | { 11 | string exceptionMessageText = 12 | $"An exception occurred: {e.Exception.Message}\r\n\r\nat: {e.Exception.StackTrace}"; 13 | 14 | LoggingService.Log(e.Exception); 15 | 16 | // TODO: Create a Window to display the exception information. 17 | MessageBox.Show(exceptionMessageText, "Unhandled Exception", MessageBoxButton.OK); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Engine/Models/World.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Engine.Models 4 | { 5 | public class World 6 | { 7 | private readonly List _locations = new List(); 8 | 9 | internal void AddLocation(Location location) 10 | { 11 | _locations.Add(location); 12 | } 13 | 14 | public Location LocationAt(int xCoordinate, int yCoordinate) 15 | { 16 | foreach(Location loc in _locations) 17 | { 18 | if(loc.XCoordinate == xCoordinate && loc.YCoordinate == yCoordinate) 19 | { 20 | return loc; 21 | } 22 | } 23 | 24 | return null; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /Engine/Shared/ExtensionMethods.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Xml; 3 | 4 | namespace Engine.Shared 5 | { 6 | public static class ExtensionMethods 7 | { 8 | public static int AttributeAsInt(this XmlNode node, string attributeName) 9 | { 10 | return Convert.ToInt32(node.AttributeAsString(attributeName)); 11 | } 12 | 13 | public static string AttributeAsString(this XmlNode node, string attributeName) 14 | { 15 | XmlAttribute attribute = node.Attributes?[attributeName]; 16 | 17 | if(attribute == null) 18 | { 19 | throw new ArgumentException($"The attribute '{attributeName}' does not exist"); 20 | } 21 | 22 | return attribute.Value; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Engine/Services/MessageBroker.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Engine.EventArgs; 3 | 4 | namespace Engine.Services 5 | { 6 | public class MessageBroker 7 | { 8 | // Use the Singleton design pattern for this class, 9 | // to ensure everything in the game sends messages through this one object. 10 | private static readonly MessageBroker s_messageBroker = 11 | new MessageBroker(); 12 | 13 | private MessageBroker() 14 | { 15 | } 16 | 17 | public event EventHandler OnMessageRaised; 18 | 19 | public static MessageBroker GetInstance() 20 | { 21 | return s_messageBroker; 22 | } 23 | 24 | internal void RaiseMessage(string message) 25 | { 26 | OnMessageRaised?.Invoke(this, new GameMessageEventArgs(message)); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Engine/Models/GroupedInventoryItem.cs: -------------------------------------------------------------------------------- 1 | namespace Engine.Models 2 | { 3 | public class GroupedInventoryItem : BaseNotificationClass 4 | { 5 | private GameItem _item; 6 | private int _quantity; 7 | 8 | public GameItem Item 9 | { 10 | get { return _item; } 11 | set 12 | { 13 | _item = value; 14 | OnPropertyChanged(nameof(Item)); 15 | } 16 | } 17 | 18 | public int Quantity 19 | { 20 | get { return _quantity; } 21 | set 22 | { 23 | _quantity = value; 24 | OnPropertyChanged(nameof(Quantity)); 25 | } 26 | } 27 | 28 | public GroupedInventoryItem(GameItem item, int quantity) 29 | { 30 | Item = item; 31 | Quantity = quantity; 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Engine/GameData/Monsters.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /TestEngine/ViewModels/TestGameSession.cs: -------------------------------------------------------------------------------- 1 | using Engine.ViewModels; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | namespace TestEngine.ViewModels 5 | { 6 | [TestClass] 7 | public class TestGameSession 8 | { 9 | [TestMethod] 10 | public void TestCreateGameSession() 11 | { 12 | GameSession gameSession = new GameSession(); 13 | 14 | Assert.IsNotNull(gameSession.CurrentPlayer); 15 | Assert.AreEqual("Town Square", gameSession.CurrentLocation.Name); 16 | } 17 | 18 | [TestMethod] 19 | public void TestPlayerMovesHomeAndIsCompletelyHealedOnKilled() 20 | { 21 | GameSession gameSession = new GameSession(); 22 | 23 | gameSession.CurrentPlayer.TakeDamage(999); 24 | 25 | Assert.AreEqual("Home", gameSession.CurrentLocation.Name); 26 | Assert.AreEqual(gameSession.CurrentPlayer.Level * 10, gameSession.CurrentPlayer.CurrentHitPoints); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Engine/Actions/Heal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Engine.Models; 3 | 4 | namespace Engine.Actions 5 | { 6 | public class Heal : BaseAction, IAction 7 | { 8 | private readonly int _hitPointsToHeal; 9 | 10 | public Heal(GameItem itemInUse, int hitPointsToHeal) 11 | : base(itemInUse) 12 | { 13 | if (itemInUse.Category != GameItem.ItemCategory.Consumable) 14 | { 15 | throw new ArgumentException($"{itemInUse.Name} is not consumable"); 16 | } 17 | 18 | _hitPointsToHeal = hitPointsToHeal; 19 | } 20 | 21 | public void Execute(LivingEntity actor, LivingEntity target) 22 | { 23 | string actorName = (actor is Player) ? "You" : $"The {actor.Name.ToLower()}"; 24 | string targetName = (target is Player) ? "yourself" : $"the {target.Name.ToLower()}"; 25 | 26 | ReportResult($"{actorName} heal {targetName} for {_hitPointsToHeal} point{(_hitPointsToHeal > 1 ? "s" : "")}."); 27 | target.Heal(_hitPointsToHeal); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Scott Lilly 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /WPFUI/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace WPFUI.Properties 12 | { 13 | 14 | 15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] 17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase 18 | { 19 | 20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 21 | 22 | public static Settings Default 23 | { 24 | get 25 | { 26 | return defaultInstance; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /WPFUI/CustomConverters/FileToBitmapConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Globalization; 4 | using System.Windows.Data; 5 | using System.Windows.Media.Imaging; 6 | 7 | namespace WPFUI.CustomConverters 8 | { 9 | public class FileToBitmapConverter : IValueConverter 10 | { 11 | private static readonly Dictionary _locations = 12 | new Dictionary(); 13 | 14 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 15 | { 16 | if(!(value is string filename)) 17 | { 18 | return null; 19 | } 20 | 21 | if(!_locations.ContainsKey(filename)) 22 | { 23 | _locations.Add(filename, 24 | new BitmapImage(new Uri($"{AppDomain.CurrentDomain.BaseDirectory}{filename}", 25 | UriKind.Absolute))); 26 | } 27 | 28 | return _locations[filename]; 29 | } 30 | 31 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 32 | { 33 | return null; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Engine/Models/GameItem.cs: -------------------------------------------------------------------------------- 1 | using Engine.Actions; 2 | 3 | namespace Engine.Models 4 | { 5 | public class GameItem 6 | { 7 | public enum ItemCategory 8 | { 9 | Miscellaneous, 10 | Weapon, 11 | Consumable 12 | } 13 | 14 | public ItemCategory Category { get; } 15 | public int ItemTypeID { get; } 16 | public string Name { get; } 17 | public int Price { get; } 18 | public bool IsUnique { get; } 19 | public IAction Action { get; set; } 20 | 21 | public GameItem(ItemCategory category, int itemTypeID, string name, int price, 22 | bool isUnique = false, IAction action = null) 23 | { 24 | Category = category; 25 | ItemTypeID = itemTypeID; 26 | Name = name; 27 | Price = price; 28 | IsUnique = isUnique; 29 | Action = action; 30 | } 31 | 32 | public void PerformAction(LivingEntity actor, LivingEntity target) 33 | { 34 | Action?.Execute(actor, target); 35 | } 36 | 37 | public GameItem Clone() 38 | { 39 | return new GameItem(Category, ItemTypeID, Name, Price, IsUnique, Action); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /Engine/GameData/GameItems.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Engine/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Engine")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Engine")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("d6199432-81ae-49a5-9ab3-2784d8600450")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Engine/Models/Recipe.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace Engine.Models 6 | { 7 | public class Recipe 8 | { 9 | public int ID { get; } 10 | public string Name { get; } 11 | public List Ingredients { get; } = new List(); 12 | public List OutputItems { get; } = new List(); 13 | 14 | public string ToolTipContents => 15 | "Ingredients" + Environment.NewLine + 16 | "===========" + Environment.NewLine + 17 | string.Join(Environment.NewLine, Ingredients.Select(i => i.QuantityItemDescription)) + 18 | Environment.NewLine + Environment.NewLine + 19 | "Creates" + Environment.NewLine + 20 | "===========" + Environment.NewLine + 21 | string.Join(Environment.NewLine, OutputItems.Select(i => i.QuantityItemDescription)); 22 | 23 | public Recipe(int id, string name) 24 | { 25 | ID = id; 26 | Name = name; 27 | } 28 | 29 | public void AddIngredient(int itemID, int quantity) 30 | { 31 | if(!Ingredients.Any(x => x.ItemID == itemID)) 32 | { 33 | Ingredients.Add(new ItemQuantity(itemID, quantity)); 34 | } 35 | } 36 | 37 | public void AddOutputItem(int itemID, int quantity) 38 | { 39 | if(!OutputItems.Any(x => x.ItemID == itemID)) 40 | { 41 | OutputItems.Add(new ItemQuantity(itemID, quantity)); 42 | } 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /Engine/Services/LoggingService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | 4 | namespace Engine.Services 5 | { 6 | public static class LoggingService 7 | { 8 | private const string LOG_FILE_DIRECTORY = "Logs"; 9 | 10 | static LoggingService() 11 | { 12 | string logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LOG_FILE_DIRECTORY); 13 | 14 | if(!Directory.Exists(logDirectory)) 15 | { 16 | Directory.CreateDirectory(logDirectory); 17 | } 18 | } 19 | 20 | public static void Log(Exception exception, bool isInnerException = false) 21 | { 22 | using(StreamWriter sw = new StreamWriter(LogFileName(), true)) 23 | { 24 | sw.WriteLine(isInnerException ? "INNER EXCEPTION" : $"EXCEPTION: {DateTime.Now}"); 25 | sw.WriteLine(new string(isInnerException ? '-' : '=', 40)); 26 | sw.WriteLine($"{exception.Message}"); 27 | sw.WriteLine($"{exception.StackTrace}"); 28 | 29 | sw.WriteLine(); // Blank line, to make the log file easier to read 30 | } 31 | 32 | if(exception.InnerException != null) 33 | { 34 | Log(exception.InnerException, true); 35 | } 36 | } 37 | 38 | private static string LogFileName() 39 | { 40 | // This will create a separate log file for each day. 41 | // Not that we're hoping to have many days of errors. 42 | return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LOG_FILE_DIRECTORY, 43 | $"SOSCSRPG_{DateTime.Now:yyyyMMdd}.log"); 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /Engine/Actions/AttackWithWeapon.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Engine.Models; 3 | 4 | namespace Engine.Actions 5 | { 6 | public class AttackWithWeapon : BaseAction, IAction 7 | { 8 | private readonly int _maximumDamage; 9 | private readonly int _minimumDamage; 10 | 11 | public AttackWithWeapon(GameItem itemInUse, int minimumDamage, int maximumDamage) 12 | : base(itemInUse) 13 | { 14 | if(itemInUse.Category != GameItem.ItemCategory.Weapon) 15 | { 16 | throw new ArgumentException($"{itemInUse.Name} is not a weapon"); 17 | } 18 | 19 | if(minimumDamage < 0) 20 | { 21 | throw new ArgumentException("minimumDamage must be 0 or larger"); 22 | } 23 | 24 | if(maximumDamage < minimumDamage) 25 | { 26 | throw new ArgumentException("maximumDamage must be >= minimumDamage"); 27 | } 28 | 29 | _minimumDamage = minimumDamage; 30 | _maximumDamage = maximumDamage; 31 | } 32 | 33 | public void Execute(LivingEntity actor, LivingEntity target) 34 | { 35 | int damage = RandomNumberGenerator.NumberBetween(_minimumDamage, _maximumDamage); 36 | 37 | string actorName = (actor is Player) ? "You" : $"The {actor.Name.ToLower()}"; 38 | string targetName = (target is Player) ? "you" : $"the {target.Name.ToLower()}"; 39 | 40 | if(damage == 0) 41 | { 42 | ReportResult($"{actorName} missed {targetName}."); 43 | } 44 | else 45 | { 46 | ReportResult($"{actorName} hit {targetName} for {damage} point{(damage > 1 ? "s" : "")}."); 47 | 48 | target.TakeDamage(damage); 49 | } 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /Engine/Models/Quest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Engine.Factories; 5 | 6 | namespace Engine.Models 7 | { 8 | public class Quest 9 | { 10 | public int ID { get; } 11 | public string Name { get; } 12 | public string Description { get; } 13 | 14 | public List ItemsToComplete { get; } 15 | 16 | public int RewardExperiencePoints { get; } 17 | public int RewardGold { get; } 18 | public List RewardItems { get; } 19 | 20 | public string ToolTipContents => 21 | Description + Environment.NewLine + Environment.NewLine + 22 | "Items to complete the quest" + Environment.NewLine + 23 | "===========================" + Environment.NewLine + 24 | string.Join(Environment.NewLine, ItemsToComplete.Select(i => i.QuantityItemDescription)) + 25 | Environment.NewLine + Environment.NewLine + 26 | "Rewards\r\n" + 27 | "===========================" + Environment.NewLine + 28 | $"{RewardExperiencePoints} experience points" + Environment.NewLine + 29 | $"{RewardGold} gold pieces" + Environment.NewLine + 30 | string.Join(Environment.NewLine, RewardItems.Select(i => i.QuantityItemDescription)); 31 | 32 | public Quest(int id, string name, string description, List itemsToComplete, 33 | int rewardExperiencePoints, int rewardGold, List rewardItems) 34 | { 35 | ID = id; 36 | Name = name; 37 | Description = description; 38 | ItemsToComplete = itemsToComplete; 39 | RewardExperiencePoints = rewardExperiencePoints; 40 | RewardGold = rewardGold; 41 | RewardItems = rewardItems; 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /Engine/RandomNumberGenerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Security.Cryptography; 3 | 4 | namespace Engine 5 | { 6 | // This is the more complex version 7 | public static class RandomNumberGenerator 8 | { 9 | private static readonly RNGCryptoServiceProvider _generator = new RNGCryptoServiceProvider(); 10 | 11 | public static int NumberBetween(int minimumValue, int maximumValue) 12 | { 13 | byte[] randomNumber = new byte[1]; 14 | 15 | _generator.GetBytes(randomNumber); 16 | 17 | double asciiValueOfRandomCharacter = Convert.ToDouble(randomNumber[0]); 18 | 19 | // We are using Math.Max, and substracting 0.00000000001, 20 | // to ensure "multiplier" will always be between 0.0 and .99999999999 21 | // Otherwise, it's possible for it to be "1", which causes problems in our rounding. 22 | double multiplier = Math.Max(0, (asciiValueOfRandomCharacter / 255d) - 0.00000000001d); 23 | 24 | // We need to add one to the range, to allow for the rounding done with Math.Floor 25 | int range = maximumValue - minimumValue + 1; 26 | 27 | double randomValueInRange = Math.Floor(multiplier * range); 28 | 29 | return (int)(minimumValue + randomValueInRange); 30 | } 31 | 32 | // Simple version, with less randomness. 33 | // 34 | // If you want to use this version, 35 | // you can delete (or comment out) the NumberBetween function above, 36 | // and rename this from SimpleNumberBetween to NumberBetween 37 | private static readonly Random _simpleGenerator = new Random(); 38 | 39 | public static int SimpleNumberBetween(int minimumValue, int maximumValue) 40 | { 41 | return _simpleGenerator.Next(minimumValue, maximumValue + 1); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /TestEngine/Actions/TestAttackWithWeapon.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Engine.Actions; 3 | using Engine.Factories; 4 | using Engine.Models; 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | 7 | namespace TestEngine.Actions 8 | { 9 | [TestClass] 10 | public class TestAttackWithWeapon 11 | { 12 | [TestMethod] 13 | public void Test_Constructor_GoodParameters() 14 | { 15 | GameItem pointyStick = ItemFactory.CreateGameItem(1001); 16 | 17 | AttackWithWeapon attackWithWeapon = new AttackWithWeapon(pointyStick, 1, 5); 18 | 19 | Assert.IsNotNull(attackWithWeapon); 20 | } 21 | 22 | [TestMethod] 23 | [ExpectedException(typeof(ArgumentException))] 24 | public void Test_Constructor_ItemIsNotAWeapon() 25 | { 26 | GameItem granolaBar = ItemFactory.CreateGameItem(2001); 27 | 28 | // A granola bar is not a weapon. 29 | // So, the constructor should throw an exception. 30 | AttackWithWeapon attackWithWeapon = new AttackWithWeapon(granolaBar, 1, 5); 31 | } 32 | 33 | [TestMethod] 34 | [ExpectedException(typeof(ArgumentException))] 35 | public void Test_Constructor_MinimumDamageLessThanZero() 36 | { 37 | GameItem pointyStick = ItemFactory.CreateGameItem(1001); 38 | 39 | // This minimum damage value is less than 0. 40 | // So, the constructor should throw an exception. 41 | AttackWithWeapon attackWithWeapon = new AttackWithWeapon(pointyStick, -1, 5); 42 | } 43 | 44 | [TestMethod] 45 | [ExpectedException(typeof(ArgumentException))] 46 | public void Test_Constructor_MaximumDamageLessThanMinimumDamage() 47 | { 48 | GameItem pointyStick = ItemFactory.CreateGameItem(1001); 49 | 50 | // This maximum damage is less than the minimum damage. 51 | // So, the constructor should throw an exception. 52 | AttackWithWeapon attackWithWeapon = new AttackWithWeapon(pointyStick, 2, 1); 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /WPFUI/TradeScreen.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | using Engine.Models; 3 | using Engine.ViewModels; 4 | 5 | namespace WPFUI 6 | { 7 | /// 8 | /// Interaction logic for TradeScreen.xaml 9 | /// 10 | public partial class TradeScreen : Window 11 | { 12 | public GameSession Session => DataContext as GameSession; 13 | 14 | public TradeScreen() 15 | { 16 | InitializeComponent(); 17 | } 18 | 19 | private void OnClick_Sell(object sender, RoutedEventArgs e) 20 | { 21 | GroupedInventoryItem groupedInventoryItem = 22 | ((FrameworkElement)sender).DataContext as GroupedInventoryItem; 23 | 24 | if(groupedInventoryItem != null) 25 | { 26 | Session.CurrentPlayer.ReceiveGold(groupedInventoryItem.Item.Price); 27 | Session.CurrentTrader.AddItemToInventory(groupedInventoryItem.Item); 28 | Session.CurrentPlayer.RemoveItemFromInventory(groupedInventoryItem.Item); 29 | } 30 | } 31 | 32 | private void OnClick_Buy(object sender, RoutedEventArgs e) 33 | { 34 | GroupedInventoryItem groupedInventoryItem = 35 | ((FrameworkElement)sender).DataContext as GroupedInventoryItem; 36 | 37 | if(groupedInventoryItem != null) 38 | { 39 | if(Session.CurrentPlayer.Gold >= groupedInventoryItem.Item.Price) 40 | { 41 | Session.CurrentPlayer.SpendGold(groupedInventoryItem.Item.Price); 42 | Session.CurrentTrader.RemoveItemFromInventory(groupedInventoryItem.Item); 43 | Session.CurrentPlayer.AddItemToInventory(groupedInventoryItem.Item); 44 | } 45 | else 46 | { 47 | MessageBox.Show("You do not have enough gold"); 48 | } 49 | } 50 | } 51 | 52 | private void OnClick_Close(object sender, RoutedEventArgs e) 53 | { 54 | Close(); 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /Engine/Factories/RecipeFactory.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Xml; 5 | using Engine.Models; 6 | using Engine.Shared; 7 | 8 | namespace Engine.Factories 9 | { 10 | public static class RecipeFactory 11 | { 12 | private const string GAME_DATA_FILENAME = ".\\GameData\\Recipes.xml"; 13 | 14 | private static readonly List _recipes = new List(); 15 | 16 | static RecipeFactory() 17 | { 18 | if(File.Exists(GAME_DATA_FILENAME)) 19 | { 20 | XmlDocument data = new XmlDocument(); 21 | data.LoadXml(File.ReadAllText(GAME_DATA_FILENAME)); 22 | 23 | LoadRecipesFromNodes(data.SelectNodes("/Recipes/Recipe")); 24 | } 25 | else 26 | { 27 | throw new FileNotFoundException($"Missing data file: {GAME_DATA_FILENAME}"); 28 | } 29 | } 30 | 31 | private static void LoadRecipesFromNodes(XmlNodeList nodes) 32 | { 33 | foreach(XmlNode node in nodes) 34 | { 35 | Recipe recipe = 36 | new Recipe(node.AttributeAsInt("ID"), 37 | node.SelectSingleNode("./Name")?.InnerText ?? ""); 38 | 39 | foreach(XmlNode childNode in node.SelectNodes("./Ingredients/Item")) 40 | { 41 | recipe.AddIngredient(childNode.AttributeAsInt("ID"), 42 | childNode.AttributeAsInt("Quantity")); 43 | } 44 | 45 | foreach(XmlNode childNode in node.SelectNodes("./OutputItems/Item")) 46 | { 47 | recipe.AddOutputItem(childNode.AttributeAsInt("ID"), 48 | childNode.AttributeAsInt("Quantity")); 49 | } 50 | 51 | _recipes.Add(recipe); 52 | } 53 | } 54 | 55 | public static Recipe RecipeByID(int id) 56 | { 57 | return _recipes.FirstOrDefault(x => x.ID == id); 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /Engine/Factories/TraderFactory.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Xml; 5 | using Engine.Models; 6 | using Engine.Shared; 7 | 8 | namespace Engine.Factories 9 | { 10 | public static class TraderFactory 11 | { 12 | private const string GAME_DATA_FILENAME = ".\\GameData\\Traders.xml"; 13 | 14 | private static readonly List _traders = new List(); 15 | 16 | static TraderFactory() 17 | { 18 | if(File.Exists(GAME_DATA_FILENAME)) 19 | { 20 | XmlDocument data = new XmlDocument(); 21 | data.LoadXml(File.ReadAllText(GAME_DATA_FILENAME)); 22 | 23 | LoadTradersFromNodes(data.SelectNodes("/Traders/Trader")); 24 | } 25 | else 26 | { 27 | throw new FileNotFoundException($"Missing data file: {GAME_DATA_FILENAME}"); 28 | } 29 | } 30 | 31 | private static void LoadTradersFromNodes(XmlNodeList nodes) 32 | { 33 | foreach(XmlNode node in nodes) 34 | { 35 | Trader trader = 36 | new Trader(node.AttributeAsInt("ID"), 37 | node.SelectSingleNode("./Name")?.InnerText ?? ""); 38 | 39 | foreach(XmlNode childNode in node.SelectNodes("./InventoryItems/Item")) 40 | { 41 | int quantity = childNode.AttributeAsInt("Quantity"); 42 | 43 | // Create a new GameItem object for each item we add. 44 | // This is to allow for unique items, like swords with enchantments. 45 | for(int i = 0; i < quantity; i++) 46 | { 47 | trader.AddItemToInventory(ItemFactory.CreateGameItem(childNode.AttributeAsInt("ID"))); 48 | } 49 | } 50 | 51 | _traders.Add(trader); 52 | } 53 | } 54 | 55 | public static Trader GetTraderByID(int id) 56 | { 57 | return _traders.FirstOrDefault(t => t.ID == id); 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /Engine/GameData/Locations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /SOSCSRPG.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27130.2027 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WPFUI", "WPFUI\WPFUI.csproj", "{EBD9099E-9C53-4750-A01F-3442309B2FE2}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Engine", "Engine\Engine.csproj", "{D6199432-81AE-49A5-9AB3-2784D8600450}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestEngine", "TestEngine\TestEngine.csproj", "{E4073809-B6F2-4230-84D4-3DFEABE7E41F}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {EBD9099E-9C53-4750-A01F-3442309B2FE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {EBD9099E-9C53-4750-A01F-3442309B2FE2}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {EBD9099E-9C53-4750-A01F-3442309B2FE2}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {EBD9099E-9C53-4750-A01F-3442309B2FE2}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {D6199432-81AE-49A5-9AB3-2784D8600450}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {D6199432-81AE-49A5-9AB3-2784D8600450}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {D6199432-81AE-49A5-9AB3-2784D8600450}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {D6199432-81AE-49A5-9AB3-2784D8600450}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {E4073809-B6F2-4230-84D4-3DFEABE7E41F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {E4073809-B6F2-4230-84D4-3DFEABE7E41F}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {E4073809-B6F2-4230-84D4-3DFEABE7E41F}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {E4073809-B6F2-4230-84D4-3DFEABE7E41F}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {1C014A0D-A629-47AC-9E44-69F5DCC74182} 36 | VisualSVNWorkingCopyRoot = . 37 | EndGlobalSection 38 | EndGlobal 39 | -------------------------------------------------------------------------------- /Engine/Models/Monster.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Engine.Factories; 3 | 4 | namespace Engine.Models 5 | { 6 | public class Monster : LivingEntity 7 | { 8 | private readonly List _lootTable = 9 | new List(); 10 | 11 | public int ID { get; } 12 | public string ImageName { get; } 13 | public int RewardExperiencePoints { get; } 14 | 15 | public Monster(int id, string name, string imageName, 16 | int maximumHitPoints, 17 | GameItem currentWeapon, 18 | int rewardExperiencePoints, int gold) : 19 | base(name, maximumHitPoints, maximumHitPoints, gold) 20 | { 21 | ID = id; 22 | ImageName = imageName; 23 | CurrentWeapon = currentWeapon; 24 | RewardExperiencePoints = rewardExperiencePoints; 25 | } 26 | 27 | public void AddItemToLootTable(int id, int percentage) 28 | { 29 | // Remove the entry from the loot table, 30 | // if it already contains an entry with this ID 31 | _lootTable.RemoveAll(ip => ip.ID == id); 32 | 33 | _lootTable.Add(new ItemPercentage(id, percentage)); 34 | } 35 | 36 | public Monster GetNewInstance() 37 | { 38 | // "Clone" this monster to a new Monster object 39 | Monster newMonster = 40 | new Monster(ID, Name, ImageName, MaximumHitPoints, CurrentWeapon, 41 | RewardExperiencePoints, Gold); 42 | 43 | foreach(ItemPercentage itemPercentage in _lootTable) 44 | { 45 | // Clone the loot table - even though we probably won't need it 46 | newMonster.AddItemToLootTable(itemPercentage.ID, itemPercentage.Percentage); 47 | 48 | // Populate the new monster's inventory, using the loot table 49 | if(RandomNumberGenerator.NumberBetween(1, 100) <= itemPercentage.Percentage) 50 | { 51 | newMonster.AddItemToInventory(ItemFactory.CreateGameItem(itemPercentage.ID)); 52 | } 53 | } 54 | 55 | return newMonster; 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /Engine/Models/Player.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.ObjectModel; 3 | using System.Linq; 4 | 5 | namespace Engine.Models 6 | { 7 | public class Player : LivingEntity 8 | { 9 | #region Properties 10 | 11 | private string _characterClass; 12 | private int _experiencePoints; 13 | 14 | public string CharacterClass 15 | { 16 | get { return _characterClass; } 17 | set 18 | { 19 | _characterClass = value; 20 | OnPropertyChanged(); 21 | } 22 | } 23 | 24 | public int ExperiencePoints 25 | { 26 | get { return _experiencePoints; } 27 | private set 28 | { 29 | _experiencePoints = value; 30 | 31 | OnPropertyChanged(); 32 | 33 | SetLevelAndMaximumHitPoints(); 34 | } 35 | } 36 | 37 | public ObservableCollection Quests { get; } 38 | 39 | public ObservableCollection Recipes { get; } 40 | 41 | #endregion 42 | 43 | public event EventHandler OnLeveledUp; 44 | 45 | public Player(string name, string characterClass, int experiencePoints, 46 | int maximumHitPoints, int currentHitPoints, int gold) : 47 | base(name, maximumHitPoints, currentHitPoints, gold) 48 | { 49 | CharacterClass = characterClass; 50 | ExperiencePoints = experiencePoints; 51 | 52 | Quests = new ObservableCollection(); 53 | Recipes = new ObservableCollection(); 54 | } 55 | 56 | public void AddExperience(int experiencePoints) 57 | { 58 | ExperiencePoints += experiencePoints; 59 | } 60 | 61 | public void LearnRecipe(Recipe recipe) 62 | { 63 | if(!Recipes.Any(r => r.ID == recipe.ID)) 64 | { 65 | Recipes.Add(recipe); 66 | } 67 | } 68 | 69 | private void SetLevelAndMaximumHitPoints() 70 | { 71 | int originalLevel = Level; 72 | 73 | Level = (ExperiencePoints / 100) + 1; 74 | 75 | if (Level != originalLevel) 76 | { 77 | MaximumHitPoints = Level * 10; 78 | 79 | OnLeveledUp?.Invoke(this, System.EventArgs.Empty); 80 | } 81 | } 82 | } 83 | } -------------------------------------------------------------------------------- /WPFUI/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Resources; 3 | using System.Runtime.CompilerServices; 4 | using System.Runtime.InteropServices; 5 | using System.Windows; 6 | 7 | // General Information about an assembly is controlled through the following 8 | // set of attributes. Change these attribute values to modify the information 9 | // associated with an assembly. 10 | [assembly: AssemblyTitle("WPFUI")] 11 | [assembly: AssemblyDescription("")] 12 | [assembly: AssemblyConfiguration("")] 13 | [assembly: AssemblyCompany("")] 14 | [assembly: AssemblyProduct("WPFUI")] 15 | [assembly: AssemblyCopyright("Copyright © 2016")] 16 | [assembly: AssemblyTrademark("")] 17 | [assembly: AssemblyCulture("")] 18 | 19 | // Setting ComVisible to false makes the types in this assembly not visible 20 | // to COM components. If you need to access a type in this assembly from 21 | // COM, set the ComVisible attribute to true on that type. 22 | [assembly: ComVisible(false)] 23 | 24 | //In order to begin building localizable applications, set 25 | //CultureYouAreCodingWith in your .csproj file 26 | //inside a . For example, if you are using US english 27 | //in your source files, set the to en-US. Then uncomment 28 | //the NeutralResourceLanguage attribute below. Update the "en-US" in 29 | //the line below to match the UICulture setting in the project file. 30 | 31 | //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] 32 | 33 | 34 | [assembly: ThemeInfo( 35 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located 36 | //(used if a resource is not found in the page, 37 | // or application resource dictionaries) 38 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located 39 | //(used if a resource is not found in the page, 40 | // app, or any theme specific resource dictionaries) 41 | )] 42 | 43 | 44 | // Version information for an assembly consists of the following four values: 45 | // 46 | // Major Version 47 | // Minor Version 48 | // Build Number 49 | // Revision 50 | // 51 | // You can specify all the values or you can default the Build and Revision Numbers 52 | // by using the '*' as shown below: 53 | // [assembly: AssemblyVersion("1.0.*")] 54 | [assembly: AssemblyVersion("1.0.0.0")] 55 | [assembly: AssemblyFileVersion("1.0.0.0")] 56 | -------------------------------------------------------------------------------- /Engine/Models/Inventory.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Engine.Services; 4 | 5 | namespace Engine.Models 6 | { 7 | public class Inventory 8 | { 9 | #region Backing variables 10 | 11 | private readonly List _backingInventory = 12 | new List(); 13 | 14 | private readonly List _backingGroupedInventoryItems = 15 | new List(); 16 | 17 | #endregion 18 | 19 | #region Properties 20 | 21 | public IReadOnlyList Items => _backingInventory.AsReadOnly(); 22 | 23 | public IReadOnlyList GroupedInventory => 24 | _backingGroupedInventoryItems.AsReadOnly(); 25 | 26 | public IReadOnlyList Weapons => 27 | _backingInventory.ItemsThatAre(GameItem.ItemCategory.Weapon).AsReadOnly(); 28 | 29 | public IReadOnlyList Consumables => 30 | _backingInventory.ItemsThatAre(GameItem.ItemCategory.Consumable).AsReadOnly(); 31 | 32 | public bool HasConsumable => Consumables.Any(); 33 | 34 | #endregion 35 | 36 | #region Constructors 37 | 38 | public Inventory(IEnumerable items = null) 39 | { 40 | if(items == null) 41 | { 42 | return; 43 | } 44 | 45 | foreach(GameItem item in items) 46 | { 47 | _backingInventory.Add(item); 48 | 49 | AddItemToGroupedInventory(item); 50 | } 51 | } 52 | 53 | #endregion 54 | 55 | #region Public functions 56 | 57 | public bool HasAllTheseItems(IEnumerable items) 58 | { 59 | return items.All(item => Items.Count(i => i.ItemTypeID == item.ItemID) >= item.Quantity); 60 | } 61 | 62 | #endregion 63 | 64 | #region Private functions 65 | 66 | // REFACTOR: Look for a better way to do this (extension method?) 67 | private void AddItemToGroupedInventory(GameItem item) 68 | { 69 | if(item.IsUnique) 70 | { 71 | _backingGroupedInventoryItems.Add(new GroupedInventoryItem(item, 1)); 72 | } 73 | else 74 | { 75 | if(_backingGroupedInventoryItems.All(gi => gi.Item.ItemTypeID != item.ItemTypeID)) 76 | { 77 | _backingGroupedInventoryItems.Add(new GroupedInventoryItem(item, 0)); 78 | } 79 | 80 | _backingGroupedInventoryItems.First(gi => gi.Item.ItemTypeID == item.ItemTypeID).Quantity++; 81 | } 82 | } 83 | 84 | #endregion 85 | } 86 | } -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /Engine/Factories/QuestFactory.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Xml; 5 | using Engine.Models; 6 | using Engine.Shared; 7 | 8 | namespace Engine.Factories 9 | { 10 | internal static class QuestFactory 11 | { 12 | private const string GAME_DATA_FILENAME = ".\\GameData\\Quests.xml"; 13 | 14 | private static readonly List _quests = new List(); 15 | 16 | static QuestFactory() 17 | { 18 | if(File.Exists(GAME_DATA_FILENAME)) 19 | { 20 | XmlDocument data = new XmlDocument(); 21 | data.LoadXml(File.ReadAllText(GAME_DATA_FILENAME)); 22 | 23 | LoadQuestsFromNodes(data.SelectNodes("/Quests/Quest")); 24 | } 25 | else 26 | { 27 | throw new FileNotFoundException($"Missing data file: {GAME_DATA_FILENAME}"); 28 | } 29 | } 30 | 31 | private static void LoadQuestsFromNodes(XmlNodeList nodes) 32 | { 33 | foreach(XmlNode node in nodes) 34 | { 35 | // Declare the items need to complete the quest, and its reward items 36 | List itemsToComplete = new List(); 37 | List rewardItems = new List(); 38 | 39 | foreach(XmlNode childNode in node.SelectNodes("./ItemsToComplete/Item")) 40 | { 41 | itemsToComplete.Add(new ItemQuantity(childNode.AttributeAsInt("ID"), 42 | childNode.AttributeAsInt("Quantity"))); 43 | } 44 | 45 | foreach(XmlNode childNode in node.SelectNodes("./RewardItems/Item")) 46 | { 47 | rewardItems.Add(new ItemQuantity(childNode.AttributeAsInt("ID"), 48 | childNode.AttributeAsInt("Quantity"))); 49 | } 50 | 51 | _quests.Add(new Quest(node.AttributeAsInt("ID"), 52 | node.SelectSingleNode("./Name")?.InnerText ?? "", 53 | node.SelectSingleNode("./Description")?.InnerText ?? "", 54 | itemsToComplete, 55 | node.AttributeAsInt("RewardExperiencePoints"), 56 | node.AttributeAsInt("RewardGold"), 57 | rewardItems)); 58 | } 59 | } 60 | 61 | internal static Quest GetQuestByID(int id) 62 | { 63 | return _quests.FirstOrDefault(quest => quest.ID == id); 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /Engine/Factories/MonsterFactory.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Xml; 5 | using Engine.Models; 6 | using Engine.Shared; 7 | 8 | namespace Engine.Factories 9 | { 10 | public static class MonsterFactory 11 | { 12 | private const string GAME_DATA_FILENAME = ".\\GameData\\Monsters.xml"; 13 | 14 | private static readonly List _baseMonsters = new List(); 15 | 16 | static MonsterFactory() 17 | { 18 | if(File.Exists(GAME_DATA_FILENAME)) 19 | { 20 | XmlDocument data = new XmlDocument(); 21 | data.LoadXml(File.ReadAllText(GAME_DATA_FILENAME)); 22 | 23 | string rootImagePath = 24 | data.SelectSingleNode("/Monsters") 25 | .AttributeAsString("RootImagePath"); 26 | 27 | LoadMonstersFromNodes(data.SelectNodes("/Monsters/Monster"), rootImagePath); 28 | } 29 | else 30 | { 31 | throw new FileNotFoundException($"Missing data file: {GAME_DATA_FILENAME}"); 32 | } 33 | } 34 | 35 | private static void LoadMonstersFromNodes(XmlNodeList nodes, string rootImagePath) 36 | { 37 | if(nodes == null) 38 | { 39 | return; 40 | } 41 | 42 | foreach(XmlNode node in nodes) 43 | { 44 | Monster monster = 45 | new Monster(node.AttributeAsInt("ID"), 46 | node.AttributeAsString("Name"), 47 | $".{rootImagePath}{node.AttributeAsString("ImageName")}", 48 | node.AttributeAsInt("MaximumHitPoints"), 49 | ItemFactory.CreateGameItem(node.AttributeAsInt("WeaponID")), 50 | node.AttributeAsInt("RewardXP"), 51 | node.AttributeAsInt("Gold")); 52 | 53 | XmlNodeList lootItemNodes = node.SelectNodes("./LootItems/LootItem"); 54 | if(lootItemNodes != null) 55 | { 56 | foreach(XmlNode lootItemNode in lootItemNodes) 57 | { 58 | monster.AddItemToLootTable(lootItemNode.AttributeAsInt("ID"), 59 | lootItemNode.AttributeAsInt("Percentage")); 60 | } 61 | } 62 | 63 | _baseMonsters.Add(monster); 64 | } 65 | } 66 | 67 | public static Monster GetMonster(int id) 68 | { 69 | return _baseMonsters.FirstOrDefault(m => m.ID == id)?.GetNewInstance(); 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /WPFUI/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace WPFUI.Properties 12 | { 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources 26 | { 27 | 28 | private static global::System.Resources.ResourceManager resourceMan; 29 | 30 | private static global::System.Globalization.CultureInfo resourceCulture; 31 | 32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 33 | internal Resources() 34 | { 35 | } 36 | 37 | /// 38 | /// Returns the cached ResourceManager instance used by this class. 39 | /// 40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 41 | internal static global::System.Resources.ResourceManager ResourceManager 42 | { 43 | get 44 | { 45 | if((resourceMan == null)) 46 | { 47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WPFUI.Properties.Resources", typeof(Resources).Assembly); 48 | resourceMan = temp; 49 | } 50 | return resourceMan; 51 | } 52 | } 53 | 54 | /// 55 | /// Overrides the current thread's CurrentUICulture property for all 56 | /// resource lookups using this strongly typed resource class. 57 | /// 58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 59 | internal static global::System.Globalization.CultureInfo Culture 60 | { 61 | get 62 | { 63 | return resourceCulture; 64 | } 65 | set 66 | { 67 | resourceCulture = value; 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Engine/Models/Location.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Engine.Factories; 4 | 5 | namespace Engine.Models 6 | { 7 | public class Location 8 | { 9 | public int XCoordinate { get; } 10 | public int YCoordinate { get; } 11 | public string Name { get; } 12 | public string Description { get; } 13 | public string ImageName { get; } 14 | 15 | public List QuestsAvailableHere { get; } = new List(); 16 | 17 | public List MonstersHere { get; } = 18 | new List(); 19 | 20 | public Trader TraderHere { get; set; } 21 | 22 | public Location(int xCoordinate, int yCoordinate, string name, string description, string imageName) 23 | { 24 | XCoordinate = xCoordinate; 25 | YCoordinate = yCoordinate; 26 | Name = name; 27 | Description = description; 28 | ImageName = imageName; 29 | } 30 | 31 | public void AddMonster(int monsterID, int chanceOfEncountering) 32 | { 33 | if(MonstersHere.Exists(m => m.MonsterID == monsterID)) 34 | { 35 | // This monster has already been added to this location. 36 | // So, overwrite the ChanceOfEncountering with the new number. 37 | MonstersHere.First(m => m.MonsterID == monsterID) 38 | .ChanceOfEncountering = chanceOfEncountering; 39 | } 40 | else 41 | { 42 | // This monster is not already at this location, so add it. 43 | MonstersHere.Add(new MonsterEncounter(monsterID, chanceOfEncountering)); 44 | } 45 | } 46 | 47 | public Monster GetMonster() 48 | { 49 | if(!MonstersHere.Any()) 50 | { 51 | return null; 52 | } 53 | 54 | // Total the percentages of all monsters at this location. 55 | int totalChances = MonstersHere.Sum(m => m.ChanceOfEncountering); 56 | 57 | // Select a random number between 1 and the total (in case the total chances is not 100). 58 | int randomNumber = RandomNumberGenerator.NumberBetween(1, totalChances); 59 | 60 | // Loop through the monster list, 61 | // adding the monster's percentage chance of appearing to the runningTotal variable. 62 | // When the random number is lower than the runningTotal, 63 | // that is the monster to return. 64 | int runningTotal = 0; 65 | 66 | foreach(MonsterEncounter monsterEncounter in MonstersHere) 67 | { 68 | runningTotal += monsterEncounter.ChanceOfEncountering; 69 | 70 | if(randomNumber <= runningTotal) 71 | { 72 | return MonsterFactory.GetMonster(monsterEncounter.MonsterID); 73 | } 74 | } 75 | 76 | // If there was a problem, return the last monster in the list. 77 | return MonsterFactory.GetMonster(MonstersHere.Last().MonsterID); 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /Engine/Models/Battle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Engine.EventArgs; 3 | using Engine.Services; 4 | 5 | namespace Engine.Models 6 | { 7 | public class Battle : IDisposable 8 | { 9 | private readonly MessageBroker _messageBroker = MessageBroker.GetInstance(); 10 | private readonly Player _player; 11 | private readonly Monster _opponent; 12 | 13 | private enum Combatant 14 | { 15 | Player, 16 | Opponent 17 | } 18 | 19 | private static Combatant FirstAttacker => 20 | RandomNumberGenerator.NumberBetween(1, 2) == 1 ? 21 | Combatant.Player : 22 | Combatant.Opponent; 23 | 24 | public event EventHandler OnCombatVictory; 25 | 26 | public Battle(Player player, Monster opponent) 27 | { 28 | _player = player; 29 | _opponent = opponent; 30 | 31 | _player.OnActionPerformed += OnCombatantActionPerformed; 32 | _opponent.OnActionPerformed += OnCombatantActionPerformed; 33 | _opponent.OnKilled += OnOpponentKilled; 34 | 35 | _messageBroker.RaiseMessage(""); 36 | _messageBroker.RaiseMessage($"You see a {_opponent.Name} here!"); 37 | 38 | if(FirstAttacker == Combatant.Opponent) 39 | { 40 | AttackPlayer(); 41 | } 42 | } 43 | 44 | public void AttackOpponent() 45 | { 46 | if(_player.CurrentWeapon == null) 47 | { 48 | _messageBroker.RaiseMessage("You must select a weapon, to attack."); 49 | return; 50 | } 51 | 52 | _player.UseCurrentWeaponOn(_opponent); 53 | 54 | if(_opponent.IsAlive) 55 | { 56 | AttackPlayer(); 57 | } 58 | } 59 | 60 | public void Dispose() 61 | { 62 | _player.OnActionPerformed -= OnCombatantActionPerformed; 63 | _opponent.OnActionPerformed -= OnCombatantActionPerformed; 64 | _opponent.OnKilled -= OnOpponentKilled; 65 | } 66 | 67 | private void OnOpponentKilled(object sender, System.EventArgs e) 68 | { 69 | _messageBroker.RaiseMessage(""); 70 | _messageBroker.RaiseMessage($"You defeated the {_opponent.Name}!"); 71 | 72 | _messageBroker.RaiseMessage($"You receive {_opponent.RewardExperiencePoints} experience points."); 73 | _player.AddExperience(_opponent.RewardExperiencePoints); 74 | 75 | _messageBroker.RaiseMessage($"You receive {_opponent.Gold} gold."); 76 | _player.ReceiveGold(_opponent.Gold); 77 | 78 | foreach(GameItem gameItem in _opponent.Inventory.Items) 79 | { 80 | _messageBroker.RaiseMessage($"You receive one {gameItem.Name}."); 81 | _player.AddItemToInventory(gameItem); 82 | } 83 | 84 | OnCombatVictory?.Invoke(this, new CombatVictoryEventArgs()); 85 | } 86 | 87 | private void AttackPlayer() 88 | { 89 | _opponent.UseCurrentWeaponOn(_player); 90 | } 91 | 92 | private void OnCombatantActionPerformed(object sender, string result) 93 | { 94 | _messageBroker.RaiseMessage(result); 95 | } 96 | } 97 | } -------------------------------------------------------------------------------- /Engine/Factories/ItemFactory.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Xml; 5 | using Engine.Actions; 6 | using Engine.Models; 7 | using Engine.Shared; 8 | 9 | namespace Engine.Factories 10 | { 11 | public static class ItemFactory 12 | { 13 | private const string GAME_DATA_FILENAME = ".\\GameData\\GameItems.xml"; 14 | 15 | private static readonly List _standardGameItems = new List(); 16 | 17 | static ItemFactory() 18 | { 19 | if(File.Exists(GAME_DATA_FILENAME)) 20 | { 21 | XmlDocument data = new XmlDocument(); 22 | data.LoadXml(File.ReadAllText(GAME_DATA_FILENAME)); 23 | 24 | LoadItemsFromNodes(data.SelectNodes("/GameItems/Weapons/Weapon")); 25 | LoadItemsFromNodes(data.SelectNodes("/GameItems/HealingItems/HealingItem")); 26 | LoadItemsFromNodes(data.SelectNodes("/GameItems/MiscellaneousItems/MiscellaneousItem")); 27 | } 28 | else 29 | { 30 | throw new FileNotFoundException($"Missing data file: {GAME_DATA_FILENAME}"); 31 | } 32 | } 33 | 34 | public static GameItem CreateGameItem(int itemTypeID) 35 | { 36 | return _standardGameItems.FirstOrDefault(item => item.ItemTypeID == itemTypeID)?.Clone(); 37 | } 38 | 39 | public static string ItemName(int itemTypeID) 40 | { 41 | return _standardGameItems.FirstOrDefault(i => i.ItemTypeID == itemTypeID)?.Name ?? ""; 42 | } 43 | 44 | private static void LoadItemsFromNodes(XmlNodeList nodes) 45 | { 46 | if(nodes == null) 47 | { 48 | return; 49 | } 50 | 51 | foreach(XmlNode node in nodes) 52 | { 53 | GameItem.ItemCategory itemCategory = DetermineItemCategory(node.Name); 54 | 55 | GameItem gameItem = 56 | new GameItem(itemCategory, 57 | node.AttributeAsInt("ID"), 58 | node.AttributeAsString("Name"), 59 | node.AttributeAsInt("Price"), 60 | itemCategory == GameItem.ItemCategory.Weapon); 61 | 62 | if(itemCategory == GameItem.ItemCategory.Weapon) 63 | { 64 | gameItem.Action = 65 | new AttackWithWeapon(gameItem, 66 | node.AttributeAsInt("MinimumDamage"), 67 | node.AttributeAsInt("MaximumDamage")); 68 | } 69 | else if(itemCategory == GameItem.ItemCategory.Consumable) 70 | { 71 | gameItem.Action = 72 | new Heal(gameItem, 73 | node.AttributeAsInt("HitPointsToHeal")); 74 | } 75 | 76 | _standardGameItems.Add(gameItem); 77 | } 78 | } 79 | 80 | private static GameItem.ItemCategory DetermineItemCategory(string itemType) 81 | { 82 | switch(itemType) 83 | { 84 | case "Weapon": 85 | return GameItem.ItemCategory.Weapon; 86 | case "HealingItem": 87 | return GameItem.ItemCategory.Consumable; 88 | default: 89 | return GameItem.ItemCategory.Miscellaneous; 90 | } 91 | } 92 | } 93 | } -------------------------------------------------------------------------------- /Engine/Services/InventoryService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Engine.Factories; 4 | using Engine.Models; 5 | 6 | namespace Engine.Services 7 | { 8 | // This service lets us write C# code that is more "functional". 9 | // Instead of modifying existing objects, and their properties, 10 | // we always instantiate new objects that have the modified values. 11 | 12 | public static class InventoryService 13 | { 14 | public static Inventory AddItem(this Inventory inventory, GameItem item) 15 | { 16 | return inventory.AddItems(new List {item}); 17 | } 18 | 19 | public static Inventory AddItemFromFactory(this Inventory inventory, int itemTypeID) 20 | { 21 | return inventory.AddItems(new List {ItemFactory.CreateGameItem(itemTypeID)}); 22 | } 23 | 24 | public static Inventory AddItems(this Inventory inventory, IEnumerable items) 25 | { 26 | return new Inventory(inventory.Items.Concat(items)); 27 | } 28 | 29 | public static Inventory AddItems(this Inventory inventory, 30 | IEnumerable itemQuantities) 31 | { 32 | List itemsToAdd = new List(); 33 | 34 | foreach(ItemQuantity itemQuantity in itemQuantities) 35 | { 36 | for(int i = 0; i < itemQuantity.Quantity; i++) 37 | { 38 | itemsToAdd.Add(ItemFactory.CreateGameItem(itemQuantity.ItemID)); 39 | } 40 | } 41 | 42 | return inventory.AddItems(itemsToAdd); 43 | } 44 | 45 | public static Inventory RemoveItem(this Inventory inventory, GameItem item) 46 | { 47 | return inventory.RemoveItems(new List {item}); 48 | } 49 | 50 | public static Inventory RemoveItems(this Inventory inventory, IEnumerable items) 51 | { 52 | // REFACTOR: Look for a cleaner solution, with fewer temporary variables. 53 | List workingInventory = inventory.Items.ToList(); 54 | IEnumerable itemsToRemove = items.ToList(); 55 | 56 | foreach(GameItem item in itemsToRemove) 57 | { 58 | workingInventory.Remove(item); 59 | } 60 | 61 | return new Inventory(workingInventory); 62 | } 63 | 64 | public static Inventory RemoveItems(this Inventory inventory, 65 | IEnumerable itemQuantities) 66 | { 67 | // REFACTOR 68 | Inventory workingInventory = inventory; 69 | 70 | foreach(ItemQuantity itemQuantity in itemQuantities) 71 | { 72 | for(int i = 0; i < itemQuantity.Quantity; i++) 73 | { 74 | workingInventory = 75 | workingInventory 76 | .RemoveItem(workingInventory 77 | .Items 78 | .First(item => item.ItemTypeID == itemQuantity.ItemID)); 79 | } 80 | } 81 | 82 | return workingInventory; 83 | } 84 | 85 | public static List ItemsThatAre(this IEnumerable inventory, 86 | GameItem.ItemCategory category) 87 | { 88 | return inventory.Where(i => i.Category == category).ToList(); 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /Engine/Factories/WorldFactory.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Xml; 3 | using Engine.Models; 4 | using Engine.Shared; 5 | 6 | namespace Engine.Factories 7 | { 8 | internal static class WorldFactory 9 | { 10 | private const string GAME_DATA_FILENAME = ".\\GameData\\Locations.xml"; 11 | 12 | internal static World CreateWorld() 13 | { 14 | World world = new World(); 15 | 16 | if(File.Exists(GAME_DATA_FILENAME)) 17 | { 18 | XmlDocument data = new XmlDocument(); 19 | data.LoadXml(File.ReadAllText(GAME_DATA_FILENAME)); 20 | 21 | string rootImagePath = 22 | data.SelectSingleNode("/Locations") 23 | .AttributeAsString("RootImagePath"); 24 | 25 | LoadLocationsFromNodes(world, 26 | rootImagePath, 27 | data.SelectNodes("/Locations/Location")); 28 | } 29 | else 30 | { 31 | throw new FileNotFoundException($"Missing data file: {GAME_DATA_FILENAME}"); 32 | } 33 | 34 | return world; 35 | } 36 | 37 | private static void LoadLocationsFromNodes(World world, string rootImagePath, XmlNodeList nodes) 38 | { 39 | if(nodes == null) 40 | { 41 | return; 42 | } 43 | 44 | foreach(XmlNode node in nodes) 45 | { 46 | Location location = 47 | new Location(node.AttributeAsInt("X"), 48 | node.AttributeAsInt("Y"), 49 | node.AttributeAsString("Name"), 50 | node.SelectSingleNode("./Description")?.InnerText ?? "", 51 | $".{rootImagePath}{node.AttributeAsString("ImageName")}"); 52 | 53 | AddMonsters(location, node.SelectNodes("./Monsters/Monster")); 54 | AddQuests(location, node.SelectNodes("./Quests/Quest")); 55 | AddTrader(location, node.SelectSingleNode("./Trader")); 56 | 57 | world.AddLocation(location); 58 | } 59 | } 60 | 61 | private static void AddMonsters(Location location, XmlNodeList monsters) 62 | { 63 | if(monsters == null) 64 | { 65 | return; 66 | } 67 | 68 | foreach(XmlNode monsterNode in monsters) 69 | { 70 | location.AddMonster(monsterNode.AttributeAsInt("ID"), 71 | monsterNode.AttributeAsInt("Percent")); 72 | } 73 | } 74 | 75 | private static void AddQuests(Location location, XmlNodeList quests) 76 | { 77 | if(quests == null) 78 | { 79 | return; 80 | } 81 | 82 | foreach(XmlNode questNode in quests) 83 | { 84 | location.QuestsAvailableHere 85 | .Add(QuestFactory.GetQuestByID(questNode.AttributeAsInt("ID"))); 86 | } 87 | } 88 | 89 | private static void AddTrader(Location location, XmlNode traderHere) 90 | { 91 | if(traderHere == null) 92 | { 93 | return; 94 | } 95 | 96 | location.TraderHere = 97 | TraderFactory.GetTraderByID(traderHere.AttributeAsInt("ID")); 98 | } 99 | } 100 | } -------------------------------------------------------------------------------- /WPFUI/MainWindow.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Windows; 4 | using System.Windows.Controls; 5 | using System.Windows.Documents; 6 | using System.Windows.Input; 7 | using Engine.EventArgs; 8 | using Engine.Models; 9 | using Engine.Services; 10 | using Engine.ViewModels; 11 | 12 | namespace WPFUI 13 | { 14 | public partial class MainWindow : Window 15 | { 16 | private readonly MessageBroker _messageBroker = MessageBroker.GetInstance(); 17 | private readonly GameSession _gameSession = new GameSession(); 18 | private readonly Dictionary _userInputActions = 19 | new Dictionary(); 20 | 21 | public MainWindow() 22 | { 23 | InitializeComponent(); 24 | 25 | InitializeUserInputActions(); 26 | 27 | _messageBroker.OnMessageRaised += OnGameMessageRaised; 28 | 29 | DataContext = _gameSession; 30 | } 31 | 32 | private void OnClick_MoveNorth(object sender, RoutedEventArgs e) 33 | { 34 | _gameSession.MoveNorth(); 35 | } 36 | 37 | private void OnClick_MoveWest(object sender, RoutedEventArgs e) 38 | { 39 | _gameSession.MoveWest(); 40 | } 41 | 42 | private void OnClick_MoveEast(object sender, RoutedEventArgs e) 43 | { 44 | _gameSession.MoveEast(); 45 | } 46 | 47 | private void OnClick_MoveSouth(object sender, RoutedEventArgs e) 48 | { 49 | _gameSession.MoveSouth(); 50 | } 51 | 52 | private void OnClick_AttackMonster(object sender, RoutedEventArgs e) 53 | { 54 | _gameSession.AttackCurrentMonster(); 55 | } 56 | 57 | private void OnClick_UseCurrentConsumable(object sender, RoutedEventArgs e) 58 | { 59 | _gameSession.UseCurrentConsumable(); 60 | } 61 | 62 | private void OnGameMessageRaised(object sender, GameMessageEventArgs e) 63 | { 64 | GameMessages.Document.Blocks.Add(new Paragraph(new Run(e.Message))); 65 | GameMessages.ScrollToEnd(); 66 | } 67 | 68 | private void OnClick_DisplayTradeScreen(object sender, RoutedEventArgs e) 69 | { 70 | if(_gameSession.CurrentTrader != null) 71 | { 72 | TradeScreen tradeScreen = new TradeScreen(); 73 | tradeScreen.Owner = this; 74 | tradeScreen.DataContext = _gameSession; 75 | tradeScreen.ShowDialog(); 76 | } 77 | } 78 | 79 | private void OnClick_Craft(object sender, RoutedEventArgs e) 80 | { 81 | Recipe recipe = ((FrameworkElement)sender).DataContext as Recipe; 82 | _gameSession.CraftItemUsing(recipe); 83 | } 84 | 85 | private void InitializeUserInputActions() 86 | { 87 | _userInputActions.Add(Key.W, () => _gameSession.MoveNorth()); 88 | _userInputActions.Add(Key.A, () => _gameSession.MoveWest()); 89 | _userInputActions.Add(Key.S, () => _gameSession.MoveSouth()); 90 | _userInputActions.Add(Key.D, () => _gameSession.MoveEast()); 91 | _userInputActions.Add(Key.Z, () => _gameSession.AttackCurrentMonster()); 92 | _userInputActions.Add(Key.C, () => _gameSession.UseCurrentConsumable()); 93 | _userInputActions.Add(Key.I, () => SetTabFocusTo("InventoryTabItem")); 94 | _userInputActions.Add(Key.Q, () => SetTabFocusTo("QuestsTabItem")); 95 | _userInputActions.Add(Key.R, () => SetTabFocusTo("RecipesTabItem")); 96 | _userInputActions.Add(Key.T, () => OnClick_DisplayTradeScreen(this, new RoutedEventArgs())); 97 | } 98 | 99 | private void MainWindow_OnKeyDown(object sender, KeyEventArgs e) 100 | { 101 | if(_userInputActions.ContainsKey(e.Key)) 102 | { 103 | _userInputActions[e.Key].Invoke(); 104 | } 105 | } 106 | 107 | private void SetTabFocusTo(string tabName) 108 | { 109 | foreach(object item in PlayerDataTabControl.Items) 110 | { 111 | if (item is TabItem tabItem) 112 | { 113 | if (tabItem.Name == tabName) 114 | { 115 | tabItem.IsSelected = true; 116 | return; 117 | } 118 | } 119 | } 120 | } 121 | } 122 | } -------------------------------------------------------------------------------- /TestEngine/TestEngine.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {E4073809-B6F2-4230-84D4-3DFEABE7E41F} 8 | Library 9 | Properties 10 | TestEngine 11 | TestEngine 12 | v4.6.1 13 | 512 14 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 15 | 15.0 16 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 17 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 18 | False 19 | UnitTest 20 | 21 | 22 | 23 | 24 | true 25 | full 26 | false 27 | bin\Debug\ 28 | DEBUG;TRACE 29 | prompt 30 | 4 31 | 32 | 33 | pdbonly 34 | true 35 | bin\Release\ 36 | TRACE 37 | prompt 38 | 4 39 | 40 | 41 | 42 | ..\packages\MSTest.TestFramework.1.2.0\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll 43 | 44 | 45 | ..\packages\MSTest.TestFramework.1.2.0\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | {d6199432-81ae-49a5-9ab3-2784d8600450} 62 | Engine 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 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}. 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /WPFUI/TradeScreen.xaml: -------------------------------------------------------------------------------- 1 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |