Removed old engine classes. Needs to be done prior to checking-in the new engine classes re-wrote from ground up.

This commit is contained in:
Scionwest_cp 2011-10-01 22:09:33 -07:00
parent 5a39a7995e
commit 5be2f9bf5b
39 changed files with 201 additions and 3300 deletions

View file

@ -3,9 +3,10 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
namespace MudEngine.Core namespace Engine.Core
{ {
public abstract class BaseGame public abstract class BaseGame
{ {
} }
} }

73
Engine/Core/BaseObject.cs Normal file
View file

@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Engine.Core
{
public abstract class BaseObject
{
private string _Name;
public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
if (this.GetType().Name.StartsWith("Base"))
Filename = value + "." + this.GetType().Name.Substring("Base".Length);
else
Filename = value + "." + this.GetType().Name;
}
}
private string _Filename;
public string Filename
{
//Returns the name of the object + the objects Type as it's extension.
//Filenames are generated by the class itself, users can not assign it.
get
{
return _Filename;
}
set
{
if (this.GetType().Name.StartsWith("Base"))
{
if (value.EndsWith("." + this.GetType().Name.Substring("Base".Length)))
{
_Filename = value;
}
else
_Filename = value + "." + this.GetType().Name.Substring("Base".Length);
}
else
{
if (value.EndsWith("." + this.GetType().Name))
{
_Filename = value;
}
else
_Filename = value + "." + this.GetType().Name;
}
}
}
public string Description { get; set; }
public BaseObject()
{
this.Name = DefaultName();
}
private String DefaultName()
{
return "New " + this.GetType().Name;
}
}
}

13
Engine/Core/IObject.cs Normal file
View file

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Engine.Core
{
public class IObject
{
public string Name { get; set; }
}
}

60
Engine/Engine.csproj Normal file
View file

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{CE880FED-87C0-4BE9-8AAD-82166536FF9B}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Engine</RootNamespace>
<AssemblyName>Engine</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Core\BaseGame.cs" />
<Compile Include="Core\BaseObject.cs" />
<Compile Include="Core\IObject.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- 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>

View file

@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}

View file

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Engine")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Engine")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("37858705-3bec-4c74-8186-543f9cf31eb8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View file

@ -1,191 +0,0 @@
 //Microsoft .NET Framework
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
//MUD Engine
using MudEngine.GameObjects;
using MudEngine.GameObjects.Characters;
using MudEngine.GameObjects.Environment;
using MudEngine.GameManagement;
namespace MudEngine.GameManagement
{
public class CommandEngine
{
/// <summary>
/// Gets or Sets a Dictionary list of available commands to use.
/// </summary>
public static Dictionary<String, IGameCommand> CommandCollection { get; set; }
internal Dictionary<String, IGameCommand> __Commands { get; set; }
public CommandEngine()
{
if ((CommandEngine.CommandCollection == null) || (CommandEngine.CommandCollection.Count == 0))
CommandEngine.LoadBaseCommands();
//_Commands = CommandEngine.CommandCollection;
}
public static List<String> GetCommands()
{
List<String> temp = new List<String>();
foreach (String name in CommandEngine.CommandCollection.Keys)
{
temp.Add(name);
}
return temp;
}
public static IGameCommand GetCommand(String command)
{
if (IsValidCommand(command))
{
foreach (IGameCommand cmd in CommandCollection.Values)
{
if (cmd.Name.ToLower() == command.ToLower())
return cmd;
}
}
return null;
}
public static String GetCommandName(IGameCommand command)
{
return command.Name.Substring("Command".Length);
}
public static Boolean IsValidCommand(String Name)
{
if (CommandCollection.ContainsKey(Name.ToLower()))
return true;
else
return false;
}
/// <summary>
/// Executes the specified command name if it exists in the Commands Dictionary.
/// </summary>
/// <param name="Name"></param>
/// <param name="Parameter"></param>
/// <returns></returns>
public void ExecuteCommand(String command, BaseCharacter player)
{
String commandKey = command.Insert(0, "Command");
foreach (String key in CommandEngine.CommandCollection.Keys)
{
if (commandKey.ToLower().Contains(key.ToLower()))
{
IGameCommand cmd = CommandEngine.CommandCollection[key];
try
{
cmd.Execute(command, player);
}
catch(Exception ex)
{
Log.Write("Fatal Error occured while attempting to execute that command " + command.ToUpper());
Log.Write("Command Error: " + ex.Source + "." + ex.TargetSite.Name + ": " + ex.Message);
}
return;
}
}
player.Send("Invalid Command.");
}
public static void LoadBaseCommands()
{
LoadCommandLibrary(Assembly.GetExecutingAssembly(), true);
}
/// <summary>
/// Dynamically loads the specified library into memory and stores all of the
/// classess inheriting from MudCreator.InputCommands.ICommand into the CommandEngines
/// commands dictionary for use with the project
/// </summary>
/// <param name="CommandLibrary"></param>
public static void LoadCommandLibrary()
{
LoadCommandLibrary(Assembly.GetExecutingAssembly());
}
public static void LoadCommandLibrary(String libraryFilename)
{
if (System.IO.File.Exists(libraryFilename))
{
Assembly assem = Assembly.LoadFile(libraryFilename);
LoadCommandLibrary(assem);
}
}
public static void LoadCommandLibrary(List<Assembly> commandLibraries)
{
foreach (Assembly lib in commandLibraries)
LoadCommandLibrary(lib);
}
public static void LoadCommandLibrary(Assembly commandLibrary)
{
LoadCommandLibrary(commandLibrary, false);
}
public static void LoadCommandLibrary(Assembly commandLibrary, Boolean purgeOldCommands)
{
//no assembly passed for whatever reason, don't attempt to enumerate through it.
if (commandLibrary == null)
return;
Log.Write("Loading commands within " + Path.GetFileName(commandLibrary.Location));
if (purgeOldCommands)
ClearCommands();
foreach (Type t in commandLibrary.GetTypes())
{
if (t.IsAbstract)
continue;
Type inter = t.GetInterface("IGameCommand");
if (inter != null)
{
//Use activator to create an instance
IGameCommand command = (IGameCommand)Activator.CreateInstance(t);
if (command != null)
{
if (command.Name == null)
command.Name = t.Name.ToLower();
else //Make sure the command is always in lower case.
command.Name = command.Name.ToLower();
//Add the command to the commands list if it does not already exist
if (CommandCollection.ContainsKey(command.Name))
{
//Command exists, check if the command is set to override existing commands or not
if (command.Override)
{
CommandCollection[command.Name] = command;
}
}
//Command does not exist, add it to the commands list
else
CommandCollection.Add(command.Name, command);
}
}
}
}
public static void ClearCommands()
{
CommandCollection = new Dictionary<String, IGameCommand>();
}
}
}

View file

@ -1,62 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MudEngine.GameObjects.Characters
{
public enum DialogSlot
{
Entry1,
Entry2,
Entry3,
Entry4,
Entry5,
}
public class DialogChat
{
public Dictionary<DialogSlot, DialogChat> DialogBranch { get; internal set; }
public String Response { get; set; }
public String Question { get; set; }
public DialogChat()
{
DialogBranch = new Dictionary<DialogSlot, DialogChat>();
}
public DialogChat(String response) : this()
{
this.Response = response;
}
public Boolean AddDialog(DialogSlot slot, DialogChat dialog)
{
foreach (DialogSlot s in DialogBranch.Keys)
{
//If an entry is already in use, do not replace it or add a duplicate entry with a different dialog.
//Reject it.
if (s == slot)
{
return false;
}
}
DialogBranch.Add(slot, dialog);
return true;
}
public DialogChat GetDialog(DialogSlot slot)
{
if (DialogBranch.Count == 0)
return null;
if (DialogBranch[slot] == null)
return null;
return DialogBranch[slot];
}
}
}

View file

@ -1,115 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using MudEngine.GameObjects.Characters;
using MudEngine.GameManagement;
namespace MudEngine.Networking
{
public class Server
{
public Server()
{
stage = 0;
port = 0;
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
~Server()
{
stage = 0;
port = 0;
}
public Boolean Initialize(Int32 p, ref BaseCharacter[] pbs)
{
if (stage != 0)
return false;
if (p <= 0)
return false;
port = p;
players = pbs;
clientThreads = new Thread[players.Length];
stage++;
return true;
}
public Boolean Start()
{
try
{
if (stage != 1)
return false;
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, port);
server.Bind(ipep);
server.Listen(10);
stage++;
serverThread = new Thread(ServerThread);
serverThread.Start();
}
catch (Exception)
{
return false;
}
return true;
}
public void EndServer()
{
stage = 0;
serverThread.Abort();
server.Close();
}
private void ServerThread()
{
while (stage == 2)
{
Int32 sub = -1;
do
{
for (Int32 i = 0; i < players.Length; i++)
{
if (!players[i].IsActive)
{
sub = i;
break;
}
}
} while (sub < 0);
players[sub].client = server.Accept();
players[sub].IsActive = true;
players[sub].IsControlled = true;
clientThreads[sub] = new Thread(ReceiveThread);
clientThreads[sub].Start((object)sub);
}
}
private void ReceiveThread(object obj)
{
Int32 sub = (Int32)obj;
players[sub].Initialize();
while (stage == 2 && players[sub].IsActive)
{
players[sub].Receive(players[sub].ReadInput());
}
}
public void Disconnect(Int32 sub)
{
if (sub > 0 && sub < players.Length)
{
clientThreads[sub].Abort();
if (players[sub].IsActive)
players[sub].Disconnect();
}
}
private Thread serverThread;
private Socket server;
private Int32 stage;
private Int32 port;
BaseCharacter[] players;
private Thread[] clientThreads;
}
}

View file

@ -1,516 +0,0 @@
//Microsoft .NET Framework
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
//MUD Engine
using MudEngine.FileSystem;
using MudEngine.Commands;
using MudEngine.GameManagement;
using MudEngine.GameObjects;
using MudEngine.GameObjects.Environment;
using MudEngine.Items;
using MudEngine.Core;
using System.Net;
using System.Net.Sockets;
namespace MudEngine.GameObjects.Characters
{
public class BaseCharacter : BaseObject
{
/// <summary>
/// Password for the player's account.
/// </summary>
private String Password { get; set; }
/// <summary>
/// The last time that the AI (if IsControlled=false) performed any major changes like traversing Rooms etc.
/// </summary>
private GameTime.Time _LastUpdate;
/// <summary>
/// Gets or Sets if the AI (if IsControlled=false) cannot move from it's CurrentRoom.
/// This is used by Shop keeper type NPC's
/// </summary>
public Boolean IsStatic { get; set; }
/// <summary>
/// The current Room this Character is located at.
/// </summary>
public Room CurrentRoom { get; set; }
/// <summary>
/// Gets the complete path to the Characters current location, including Realm, Zone and Room.
/// </summary>
public String CurrentWorldLocation
{
get
{
return CurrentRoom.Realm + "." + CurrentRoom.Zone + "." + CurrentRoom.Filename;
}
}
protected override string SavePath
{
get
{
return ActiveGame.DataPaths.Players;
}
}
/// <summary>
/// Gets or Sets if this Character is controlled by the user. If not user controlled then it will be AI controlled.
/// </summary>
public Boolean IsControlled
{
get
{
return _IsControlled;
}
set
{
if (value)
{
//TODO: Begin AI initialization
}
_IsControlled = value;
}
}
private Boolean _IsControlled;
/// <summary>
/// Gets if this user has Admin privileges or not.
/// </summary>
public SecurityRoles Role { get; private set; }
/// <summary>
/// Gets or if this character is active.
/// </summary>
public Boolean IsActive { get; internal set; }
/// <summary>
/// Gets the current inventory of the character
/// </summary>
public Bag Inventory { get; private set; }
/// <summary>
/// Gets the characters Dialog Branch.
/// If the Character contains Quests, then the Dialog will only be visible when the Quests are not available
/// to the users.
/// </summary>
public DialogChat Dialog { get; internal set; }
/// <summary>
/// Gets a working copy of the CommandEngine used by the player.
/// </summary>
public CommandEngine CommandSystem { get; internal set; }
/// <summary>
/// Gets or Sets the characters stats.
/// Note that this will more and likely become Read-Only in the future.
/// </summary>
public BaseStats Stats { get; set; }
public BaseCharacter(Game game)
: base(game)
{
ActiveGame = game;
IsActive = false;
if ((game.InitialRealm == null) || (game.InitialRealm.InitialZone == null) || (game.InitialRealm.InitialZone.InitialRoom == null))
{
CurrentRoom = new Room(game);
CurrentRoom.Name = "Abyss";
CurrentRoom.Description = "You are currently in the abyss.";
}
else
CurrentRoom = game.InitialRealm.InitialZone.InitialRoom;
Inventory = new Bag(game);
CommandSystem = new CommandEngine();
}
public override void Load(String filename)
{
base.Load(filename);
Password = FileManager.GetData(filename, "Password");
this.IsControlled = Convert.ToBoolean(FileManager.GetData(filename, "IsControlled"));
//Need to re-assign the enumerator value that was previously assigned to the Role property
Array values = Enum.GetValues(typeof(SecurityRoles));
foreach (Int32 value in values)
{
//Since enum values are not strings, we can't simply just assign the String to the enum
String displayName = Enum.GetName(typeof(SecurityRoles), value);
//If the value = the String saved, then perform the needed conversion to get our data back
if (displayName.ToLower() == FileManager.GetData(filename, "Role").ToLower())
{
Role = (SecurityRoles)Enum.Parse(typeof(SecurityRoles), displayName);
break;
}
}
//Restore the users current Room.
Realm realm = (Realm)ActiveGame.World.GetRealm(FileManager.GetData(filename, "CurrentRealm"));
if (realm == null)
{
realm = new Realm(ActiveGame);
return;
}
List<Zone> zones = realm.GetZone(FileManager.GetData(filename, "CurrentZone"));
Zone zone = new Zone(ActiveGame);
if (zones.Count == 0)
{
Log.Write("Error: Failed to find " + FileManager.GetData(filename, "CurrentZone") + " zone.");
return;
}
else if (zones.Count == 1)
{
zone = zones[0];
}
else
{
//TODO: determin which zone is the appropriate zone to assign if more than one exists.
foreach (Zone z in zones)
{
if (z.GetRoom(FileManager.GetData(filename, "CurrentRoom")) != null)
{
zone = z;
break;
}
}
}
List<Room> rooms = zone.GetRoom(FileManager.GetData(filename, "CurrentRoom"));
if (rooms.Count == 0)
{
Log.Write("Error: Failed to find " + FileManager.GetData(filename, "CurrentRoom") + " room.");
return;
}
else if (rooms.Count == 1)
{
CurrentRoom = rooms[0];
}
else
{
//TODO: Loop through each found room and determin in some manor what should be the correct Room to assign.
}
if (CurrentRoom == null)
{
CurrentRoom = new Room(ActiveGame);
CurrentRoom.Name = "Abyss";
CurrentRoom.Description = "You are in the Aybss. It is void of all life.";
return;
}
//TODO: Load player Inventory.
/* Due to private accessor Inv needs to be restored via
* foreach (Item in Inventory)
* this.AddItem(Item);
*/
}
public override void Save()
{
base.Save();
String path = Path.Combine(SavePath, Filename);
FileManager.WriteLine(path, this.Password, "Password");
FileManager.WriteLine(path, this.IsControlled.ToString(), "IsControlled");
FileManager.WriteLine(path, this.Role.ToString(), "Role");
FileManager.WriteLine(path, this.CurrentRoom.Filename, "CurrentRoom");
FileManager.WriteLine(path, this.CurrentRoom.Zone, "CurrentZone");
FileManager.WriteLine(path, this.CurrentRoom.Realm, "CurrentRealm");
}
public virtual void Update()
{
//TODO: Update AI logic.
Log.Write("BaseCharacter.Update Called!", true);
//TODO: AI Logic: Don't attack anything if CurrentRoom.IsSafe
//TODO: Add Stat modifiers for Zone and Rooms.
}
/// <summary>
/// Moves the player from one Room to another if the supplied direction contains a doorway.
/// Returns false if no doorway is available.
/// </summary>
/// <param name="travelDirection"></param>
/// <returns></returns>
public Boolean Move(AvailableTravelDirections travelDirection)
{
//Check if the current room has a doorway in the supplied direction of travel.
if (!CurrentRoom.DoorwayExist(travelDirection))
{
return false;
}
//Let other players know that the user walked out.
for (Int32 i = 0; i != ActiveGame.GetPlayerCollection().Length; i++)
{
if (ActiveGame.GetPlayerCollection()[i].Name == Name)
continue;
String room = ActiveGame.GetPlayerCollection()[i].CurrentRoom.Filename;
String realm = ActiveGame.GetPlayerCollection()[i].CurrentRoom.Realm;
String zone = ActiveGame.GetPlayerCollection()[i].CurrentRoom.Zone;
if ((room == CurrentRoom.Filename) && (realm == CurrentRoom.Realm) && (zone == CurrentRoom.Zone))
{
ActiveGame.GetPlayerCollection()[i].Send(Name + " walked out towards the " + travelDirection.ToString());
}
}
//We have a doorway, lets move to the next room.
CurrentRoom = CurrentRoom.GetDoor(travelDirection).ArrivalRoom;
OnTravel(travelDirection);
return true;
}
public virtual void OnTravel(AvailableTravelDirections travelDirection)
{
//TODO: Check the Room/Zone/Realm to see if anything needs to occure during travel.
//Let other players know that the user walked in.
for (Int32 i = 0; i != ActiveGame.GetPlayerCollection().Length; i++)
{
if (ActiveGame.GetPlayerCollection()[i].Name == Name)
continue;
String room = ActiveGame.GetPlayerCollection()[i].CurrentRoom.Name;
String realm = ActiveGame.GetPlayerCollection()[i].CurrentRoom.Realm;
String zone = ActiveGame.GetPlayerCollection()[i].CurrentRoom.Zone;
if ((room == CurrentRoom.Name) && (realm == CurrentRoom.Realm) && (zone == CurrentRoom.Zone))
{
ActiveGame.GetPlayerCollection()[i].Send(Name + " walked in from the " + TravelDirections.GetReverseDirection(travelDirection));
}
}
}
public virtual void OnTalk(String message, BaseCharacter instigator)
{
//If the instigator is not sending a message to this character, then the
//AI can ignore it. No response will be sent.
if (!message.ToLower().Substring("say".Length).Trim().Contains(this.Name.ToLower()))
return;
//If the message was directed at this player, we will only respond
//if this character is controlled by AI.
if (!this.IsControlled)
{
//Instance a new Say command, and send the dialog response that we have saved.
IGameCommand cmd = CommandEngine.GetCommand("Say");
if (cmd != null)
cmd.Execute("say " + this.Dialog.Response, instigator);
}
}
public void ExecuteCommand(String command)
{
CommandSystem.ExecuteCommand(command, this);
Send(""); //Blank line to help readability.
//Now that the command has been executed, restore the Command: message
Send("Command: ", false);
}
public virtual void Create(string playerName, string password)
{
Name = playerName;
Password = password;
Save();
}
public bool VarifyPassword(string password)
{
if (Password == password)
return true;
else
return false;
}
public virtual void Initialize()
{
if (ActiveGame.IsMultiplayer)
client.Receive(new byte[255]);
//Ensure custom commands are loaded until everything is fleshed out.
if (Game.IsDebug)
{
foreach (String command in CommandEngine.GetCommands())
{
Log.Write("Command loaded: " + command);
}
}
//Set the players initial room
if ((ActiveGame.InitialRealm == null) || (ActiveGame.InitialRealm.InitialZone == null) || (ActiveGame.InitialRealm.InitialZone.InitialRoom == null))
{
CurrentRoom = new Room(ActiveGame);
CurrentRoom.Name = "Abyss";
CurrentRoom.Description = "You are in the Abyss. It is dark and void of life.";
}
else
CurrentRoom = ActiveGame.InitialRealm.InitialZone.InitialRoom;
IGameCommand gc = CommandEngine.GetCommand("CommandLogin");
gc.Execute("Login", this);
Log.Write(Name + " has logged in.");
gc = CommandEngine.GetCommand("CommandLook");
gc.Execute("Look", this); //MUST happen after Room setup is completed, otherwise the player default Abyss Room is printed.
this.Send("Command: ", false);
}
public virtual void OnCreate()
{
}
public virtual void OnDestroy()
{
}
public virtual void OnEquip()
{
}
public virtual void OnUnequip()
{
}
internal void Receive(String data)
{
//data = ExecuteCommand(data);
ExecuteCommand(data);
//Send(data); //Results no longer returned as Player.Send() is used by the commands now.
if (!ActiveGame.IsRunning)
Disconnect();
}
/// <summary>
/// Sends data to the player.
/// </summary>
/// <param name="data"></param>
/// <param name="newLine"></param>
public void Send(String data, Boolean newLine)
{
try
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
if (newLine)
data += "\n\r";
if (ActiveGame.IsMultiplayer)
client.Send(encoding.GetBytes(data));
else
Console.Write(data);
}
catch (Exception)
{
Disconnect();
}
}
/// <summary>
/// Sends data to the player.
/// </summary>
/// <param name="data"></param>
public void Send(String data)
{
Send(data, true);
}
public void FlushConsole()
{
try
{
if (ActiveGame.IsMultiplayer)
{
System.Text.ASCIIEncoding encoding = new ASCIIEncoding();
//\x1B is hex
//[2J is terminal sequences for clearing the screen.
client.Send(encoding.GetBytes("\x1B[2J"));
//[H is terminal sequence for sending the cursor back to its home position.
client.Send(encoding.GetBytes("\x1B[H"));
}
else
Console.Clear();
}
catch
{
Disconnect();
}
}
public void Disconnect()
{
if (IsActive)
{
this.Save();
Send("Goodbye!");
IsActive = false;
client.Close();
Log.Write(Name + " disconnected.");
}
}
public String ReadInput()
{
if (ActiveGame.IsMultiplayer)
{
List<byte> buffer = new List<byte>();
while (true)
{
try
{
byte[] buf = new byte[1];
Int32 recved = client.Receive(buf);
if (recved > 0)
{
if (buf[0] == '\n' && buffer.Count > 0)
{
if (buffer[buffer.Count - 1] == '\r')
buffer.RemoveAt(buffer.Count - 1);
String str;
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
str = enc.GetString(buffer.ToArray());
return str;
}
else
buffer.Add(buf[0]);
}
}
catch (Exception e)
{
Disconnect();
return e.Message;
}
}
}
else
{
return Console.ReadLine();
}
}
internal Socket client;
}
}

View file

@ -1,32 +0,0 @@
using System;
using System.Collections.Generic;
using MudEngine.GameManagement;
using MudEngine.GameObjects.Characters;
using MudEngine.GameObjects.Environment;
namespace MudEngine.Commands
{
public abstract class BaseCommand : IGameCommand
{
public Boolean Override { get; set; }
public String Name { get; set; }
//public String Name { get; set; }
public List<String> Help { get; set; }
protected Realm realm;
protected Zone zone;
protected Room room;
protected BaseCharacter player;
protected Boolean isEditing;
public BaseCommand()
{
Help = new List<string>();
}
public abstract void Execute(String command, BaseCharacter player);
}
}

View file

@ -1,41 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace MudEngine.Core
{
public abstract class BaseEnvironment : BaseObject
{
[Category("Environment Information")]
[Description("If a user asks to use his/her senses to investigate an area, this is one of the results that will be displayed. Senses can be used to assist blind characters.")]
[DefaultValue("You don't smell anything unsual.")]
public String Smell { get; set; }
[Category("Environment Information")]
[Description("If a user asks to use his/her senses to investigate an area, this is one of the results that will be displayed. Senses can be used to assist blind characters.")]
[DefaultValue("You hear nothing of interest.")]
public String Listen { get; set; }
[Category("Environment Information")]
[Description("If a user asks to use his/her senses to investigate an area, this is one of the results that will be displayed. Senses can be used to assist blind characters.")]
[DefaultValue("You feel nothing.")]
public String Feel { get; set; }
public BaseEnvironment(BaseGame game) : base(game)
{
this.Feel = "You feel nothing.";
this.Listen = "You hear nothing of interest.";
this.Smell = "You don't smell anything unsual.";
}
public virtual void OnEnter()
{
}
public virtual void OnExit()
{
}
}
}

View file

@ -1,17 +0,0 @@
//Microsoft .NET Framework
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MudEngine.GameManagement;
namespace MudEngine.Core
{
public class BaseItem : BaseObject
{
public BaseItem(Game game) : base(game)
{
}
}
}

View file

@ -1,175 +0,0 @@
//Microsoft .NET Framework
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;
using System.Xml.Serialization;
using System.IO;
//MUD Engine
using MudEngine.FileSystem;
using MudEngine.GameManagement;
using rScripting;
using rScripting.LateBinding;
namespace MudEngine.Core
{
public abstract class BaseObject
{
[Category("Object Setup")]
[Description("The Display Name assigned to this object.")]
//Required to refresh Filename property in the editors propertygrid
[RefreshProperties(RefreshProperties.All)]
public String Name
{
get
{
return _Name;
}
set
{
_Name = value;
if (this.GetType().Name.StartsWith("Base"))
Filename = value + "." + this.GetType().Name.Substring("Base".Length);
else
Filename = value + "." + this.GetType().Name;
}
}
private String _Name;
[Category("Object Setup")]
[Description("A brief description of this object. The description is displayed to users when they use a command for investigating an object")]
public String Description { get; set; }
/// <summary>
/// A detailed description that treats each entry as a seperete line when outputted to the player
/// </summary>
[Browsable(false)] //not visible within any Property Controls
public List<String> DetailedDescription { get; set; }
[Category("Object Setup")]
[ReadOnly(true)]
[Description("The filename of the current object. This is assigned by the engine and not editable.")]
public String Filename
{
//Returns the name of the object + the objects Type as it's extension.
//Filenames are generated by the class itself, users can not assign it.
get
{
return _Filename;
}
set
{
if (this.GetType().Name.StartsWith("Base"))
{
if (value.EndsWith("." + this.GetType().Name.Substring("Base".Length)))
{
_Filename = value;
}
else
_Filename = value + "." + this.GetType().Name.Substring("Base".Length);
}
else
{
if (value.EndsWith("." + this.GetType().Name))
{
_Filename = value;
}
else
_Filename =value + "." + this.GetType().Name;
}
}
}
String _Filename;
protected virtual String SavePath { get; set; }
public BaseGame ActiveGame { get; set; }
/// <summary>
/// Initializes the base object
/// </summary>
public BaseObject(BaseGame game)
{
Name = "New " + this.GetType().Name;
ActiveGame = game;
DetailedDescription = new List<String>();
this.Name = DefaultName();
this.Filename = DefaultName() + "." + this.GetType().Name;
}
private Boolean ShouldSerializeName()
{
return this.Name != DefaultName();
}
private void ResetName()
{
this.Name = DefaultName();
}
private String DefaultName()
{
return "New " + this.GetType().Name;
}
#region Public Methods
public override String ToString()
{
return this.Name;
}
public virtual void Initialize()
{
}
public virtual void Save()
{
string path = this.SavePath;
if (String.IsNullOrEmpty(path))
return;
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
String filename = Path.Combine(path, Filename);
if (File.Exists(filename))
File.Delete(filename);
FileManager.WriteLine(filename, this.Name, "Name");
FileManager.WriteLine(filename, this.Description, "Description");
foreach (String line in DetailedDescription)
FileManager.WriteLine(filename, line, "DetailedDescription");
}
public virtual void Load(String filename)
{
if (String.IsNullOrEmpty(filename))
return;
if (!File.Exists(filename))
{
Log.Write("Error: Attempted to load file " + filename);
return;
}
this.Name = FileManager.GetData(filename, "Name");
this.Description = FileManager.GetData(filename, "Description");
List<String> data = FileManager.GetCollectionData(filename, "DetailedDescription");
foreach (String line in data)
DetailedDescription.Add(line);
//Set the Filename property based off the physical filename, as setting this.Name sets a default filename
//which might not match that of the actual physical filename on the harddrive.
this.Filename = Path.GetFileName(filename);
}
#endregion
}
}

View file

@ -1,204 +0,0 @@
//Microsoft .NET Framework
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using MudEngine.GameManagement;
namespace MudEngine.FileSystem
{
/// <summary>
/// Handles saving and loading of engine objects
/// </summary>
public static class FileManager
{
public enum OutputFormats
{
XML = 0,
}
/// <summary>
/// The filetype that the MUDs files will be saved as
/// </summary>
public static OutputFormats FileType
{
get;
set;
}
/// <summary>
/// Writes content out to a file.
/// </summary>
/// <param name="filename"></param>
/// <param name="name"></param>
/// <param name="value"></param>
public static void WriteLine(String filename, String value, String name)
{
if (!File.Exists(filename))
{
FileStream s = File.Create(filename);
s.Close();
}
using (StreamWriter sw = File.AppendText(filename))
{
StringBuilder sb = new StringBuilder();
sb.Append(name);
sb.Append("=");
sb.Append(value);
sw.WriteLine(sb.ToString());
sw.Close();
}
}
public static String GetData(String filename, String name)
{
if (!File.Exists(filename))
{
Log.Write("Error: Failed attempting to load " + filename + ". File does not exist.");
return "No data Found." ;
}
foreach (String line in File.ReadAllLines(filename))
{
//Ignore comments
if (line.StartsWith(";"))
continue;
if (line.ToLower().StartsWith(name.ToLower()))
return line.Substring(name.Length + 1); //Accounts for name=value;
}
return "No data Found.";
}
public static List<String> GetCollectionData(String filename, String item)
{
List<String> items = new List<string>();
foreach (String line in File.ReadAllLines(filename))
{
//Ignore comments
if (line.StartsWith(";"))
continue;
if (line.ToLower().StartsWith(item.ToLower()))
items.Add(line.Substring(item.Length + 1)); //Accounts for name=value;
}
return items;
}
/// <summary>
/// Gets a collection of data from a file spanning
/// </summary>
/// <param name="filename"></param>
/// <param name="startingLine"></param>
/// <param name="endingLine"></param>
/// <returns></returns>
public static List<String> GetDataSpan(String filename, Int32 linesToSpan)
{
List<String> items = new List<String>();
Int32 currentLine = 1;
foreach (String line in File.ReadAllLines(filename))
{
if (line.StartsWith(";"))
continue;
items.Add(line);
if (currentLine == linesToSpan)
break;
else
currentLine++;
}
return items;
}
public static List<String> GetDataSpan(String filename, Int32 linesToSpan, String startingValue, Boolean spanAllSimilar)
{
List<String> items = new List<String>();
String[] fileData = File.ReadAllLines(filename);
Int32 line = 0;
while (line <= fileData.Length - 1)
{
if (fileData[line].StartsWith(";"))
continue;
else if (fileData[line].ToLower().StartsWith(startingValue.ToLower()))
{
Boolean isComplete = false;
while (!isComplete)
{
Int32 startingLine = line;
//Exception prevention first.
if (line >= fileData.Length)
{
isComplete = true;
continue;
}
if (fileData[line].ToLower().StartsWith(startingValue.ToLower()))
{
for (Int32 i = startingLine; i != (startingLine + linesToSpan); i++)
{
String[] content = fileData[i].Split('=');
items.Add(content[1]);
line++;
}
if (!spanAllSimilar)
isComplete = true;
}
}
}
line++;
}
return items;
}
/// <summary>
/// Returns the complete path to the specified data's save folder.
/// </summary>
/// <param name="DataType"></param>
/// <returns></returns>
public static String GetDataPath(SaveDataTypes DataType)
{
String assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName;
String assemblyName = System.IO.Path.GetFileName(assemblyPath);
String installBase = assemblyPath.Substring(0, assemblyPath.Length - assemblyName.Length);
if (DataType == SaveDataTypes.Root)
return installBase;
else
return System.IO.Path.Combine(installBase, DataType.ToString());
}
public static String GetDataPath(String Realm, String Zone)
{
String assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName;
String assemblyName = System.IO.Path.GetFileName(assemblyPath);
String installBase = assemblyPath.Substring(0, assemblyPath.Length - assemblyName.Length);
String realmsPath = System.IO.Path.Combine(installBase, "Realms");
String requestRealm = Path.Combine(installBase, Realm);
String requestedRealmZones = Path.Combine(installBase, "Zones");
String requestedZone = Path.Combine(installBase, Zone);
return requestedZone;
}
public static String GetDataPath(String Realm, String Zone, String Room)
{
return System.IO.Path.Combine(GetDataPath(Realm, Zone), Room);
}
//TODO Write CopyDirectory method.
}
}

View file

@ -1,57 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MudEngine.FileSystem
{
public struct SaveDataPaths
{
public String Players
{
get
{
return _Players;
}
set
{
_Players = value;
}
}
public String Environment
{
get
{
return _Environment;
}
set
{
_Environment = value;
}
}
public String Scripts
{
get
{
return _Scripts;
}
set
{
_Scripts = value;
}
}
private String _Players;
private String _Environment;
private String _Scripts;
public SaveDataPaths(String environment, String players, String scripts)
{
_Players = players;
_Environment = environment;
_Scripts = scripts;
}
}
}

View file

@ -1,11 +0,0 @@
namespace MudEngine.FileSystem
{
public enum SaveDataTypes
{
Root,
Player,
Currencies,
Realms,
Zones,
}
}

View file

@ -1,40 +0,0 @@
//Microsoft .NET Framework
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
namespace MudEngine.FileSystem
{
internal class XmlSerialization
{
internal static void Save(String Filename, object o)
{
Stream stream = File.Create(Filename);
XmlSerializer serializer = new XmlSerializer(o.GetType());
serializer.Serialize(stream, o);
stream.Close();
}
/// <summary>
/// Loads an item via Xml Deserialization
/// </summary>
/// <param name="Filename">The Xml document to deserialize.</param>
/// <returns></returns>
internal static object Load(String Filename, object o)
{
Stream stream = File.OpenRead(Filename);
object obj = new object();
XmlSerializer serializer = new XmlSerializer(o.GetType());
obj = (object)serializer.Deserialize(stream);
stream.Close();
return obj;
}
}
}

View file

@ -1,40 +0,0 @@
//Microsoft .NET Framework
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//MUD Engine
using MudEngine.Core;
namespace MudEngine.Items
{
public class Bag : BaseItem
{
/// <summary>
/// Gets or Sets the size of the bag.
/// </summary>
public Int32 Size
{
get;
set;
}
private List<BaseItem> Items { get; set; }
public Bag(GameManagement.Game game) : base(game)
{
}
public void Add(BaseItem item)
{
if (Items.Count < Size)
Items.Add(item);
}
public Int32 GetSlotsRemaining()
{
return Size - Items.Count;
}
}
}

View file

@ -1,32 +0,0 @@
//Microsoft .NET Framework
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using MudEngine.Core;
namespace MudEngine.GameObjects
{
public class Currency : BaseItem
{
[Category("Currency Settings")]
[Description("The value of the currency is based off the BaseCurrencyValue set in the Project Information. If BaseCurrencyValue is 1, and a new Currency is 10, then it will take 10 BaseCurrency to equal 1 of the new Currencies.")]
[DefaultValue(100)]
/// <summary>
/// The value of this currency. It should be how many 'base currency' it takes to equal 1 of this currency
/// </summary>
public Int32 Value
{
get;
set;
}
public Currency(GameManagement.Game game) : base(game)
{
this.Name = "New Currency";
this.Value = 100;
}
}
}

View file

@ -54,40 +54,14 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Core\BaseCommand.cs" /> <Compile Include="ClassesPendingMigration\GameTime.cs" />
<Compile Include="Core\BaseEnvironment.cs" /> <Compile Include="ClassesPendingMigration\GameWorld.cs" />
<Compile Include="Core\BaseGame.cs" /> <Compile Include="ClassesPendingMigration\Game.cs" />
<Compile Include="DAL\SaveDataPaths.cs" /> <Compile Include="ClassesPendingMigration\ICommand.cs" />
<Compile Include="Commands\CommandSystem.cs" /> <Compile Include="ClassesPendingMigration\Log.cs" />
<Compile Include="Game\GameTime.cs" /> <Compile Include="ClassesPendingMigration\SecurityRoles.cs" />
<Compile Include="Game\GameWorld.cs" /> <Compile Include="ClassesPendingMigration\BaseStats.cs" />
<Compile Include="DAL\FileManager.cs" />
<Compile Include="DAL\SaveDataTypes.cs" />
<Compile Include="DAL\XmlSerialization.cs" />
<Compile Include="Game\Game.cs" />
<Compile Include="Game\ICommand.cs" />
<Compile Include="Game\Log.cs" />
<Compile Include="Game\SecurityRoles.cs" />
<Compile Include="Items\Bag.cs" />
<Compile Include="Core\BaseObject.cs" />
<Compile Include="Core\BaseCharacter.cs" />
<Compile Include="Game\BaseStats.cs" />
<Compile Include="Communication\DialogChat.cs" />
<Compile Include="Scripting\CompileEngine.cs" />
<Compile Include="Scripting\ScriptFactory.cs" />
<Compile Include="Scripting\ScriptObject.cs" />
<Compile Include="World\Door.cs" />
<Compile Include="World\Realm.cs" />
<Compile Include="World\Room.cs" />
<Compile Include="World\StartingLocation.cs" />
<Compile Include="World\TerrainType.cs" />
<Compile Include="World\TravelDirections.cs" />
<Compile Include="World\Zone.cs" />
<Compile Include="Core\BaseItem.cs" />
<Compile Include="Items\Currency.cs" />
<Compile Include="Communication\Server.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Scripting\MudScriptCompiler.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\rScripting\rScripting.csproj"> <ProjectReference Include="..\rScripting\rScripting.csproj">

View file

@ -1,404 +0,0 @@
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
using rScripting.Compilers;
using rScripting.LateBinding;
namespace MudEngine.Scripting
{
/// <summary>
/// Provides Properties & Methods needed to compile script source code into .NET assemblies.
/// </summary>
public class CompileEngine
{
/// <summary>
/// The file extension used for the script files.
/// </summary>
public String ScriptExtension
{
get
{
return _ScriptExtension;
}
set
{
if (value.StartsWith("."))
_ScriptExtension = value;
else
_ScriptExtension = "." + value;
}
}
private String _ScriptExtension;
/// <summary>
/// Provides a collection of Assemblies that the compiler will add to its reference list.
/// </summary>
public List<String> AssemblyReferences { get; private set; }
/// <summary>
/// Provides a reference to the assembly generated during script compilation.
/// </summary>
public Assembly CompiledAssembly { get; set; }
/// <summary>
/// The compiler that will be used when the contents of ScriptRepository are compiled.
/// </summary>
public String Compiler { get; set; }
/// <summary>
/// Used to supply compiling options to various compilers if they support this feature.
/// </summary>
public Dictionary<String, String> CompilerOptions { get; set; }
/// <summary>
/// Used to check if the compilation contained any errors.
/// </summary>
public Boolean HasErrors { get; internal set; }
/// <summary>
/// String of errors that occurred during compilation, if any.
/// </summary>
public String Errors
{
get
{
if (_CompileMessages.Length == 0)
return "No Errors.";
else
{
StringBuilder builder = new StringBuilder();
foreach (String error in _CompileMessages)
{
builder.AppendLine(error);
}
return builder.ToString();
}
}
}
//Messages stored from the compilers CompilerResults property.
private String[] _CompileMessages;
//Returns all of the assemblies currently loaded in the current domain.
private Assembly[] _Assemblies
{
get
{
return AppDomain.CurrentDomain.GetAssemblies();
}
}
public CompileEngine() : this(".cs")
{
//Passes defaults off to the parameterized constructor.
}
public CompileEngine(String scriptExtensions)
{
_CompileMessages = new String[] { "No compiler messages available." };
CompilerOptions = new Dictionary<string, string>();
Compiler = "C#";
AssemblyReferences = new List<string>();
AssemblyReferences.Add("mscorlib.dll");
AssemblyReferences.Add("System.dll");
AssemblyReferences.Add("System.Core.dll");
ScriptExtension = scriptExtensions;
}
/// <summary>
/// Adds a reference to the supplied Assembly name to the compilers reference collection.
/// </summary>
/// <param name="assembly"></param>
public void AddAssemblyReference(String assembly)
{
if (!AssemblyReferences.Contains(assembly))
AssemblyReferences.Add(assembly);
}
/// <summary>
/// Adds a reference to the supplied Assembly to the compilers reference collection.
/// </summary>
/// <param name="assembly"></param>
public void AddAssemblyReference(Assembly assembly)
{
if (!AssemblyReferences.Contains(assembly.GetName().Name))
AssemblyReferences.Add(assembly.GetName().Name);
}
/// <summary>
/// Removes the supplied assembly from the compilers reference collection.
/// </summary>
/// <param name="assembly"></param>
public void RemoveAssemblyReference(String assembly)
{
if (AssemblyReferences.Contains(assembly))
AssemblyReferences.Remove(assembly);
}
/// <summary>
/// Clears the compilers reference collection, leaving it empty.
/// </summary>
public void ClearAssemblyReference()
{
AssemblyReferences.Clear();
}
/// <summary>
/// Compiles the scripts found within the CompileEngine.ScriptRepository directory that match the CompileEngine.ScriptExtension file extension.
/// The compiler will compile the scripts using the compiler specified with the CompileEngine.Compiler Property.
/// </summary>
/// <returns>Returns true if compilation was completed without any errors.</returns>
public Boolean Compile(String scriptRepository)
{
//Get the compiler that the developer has selected.
//If the developer chooses a compiler that is not part of the engine, the GetCompiler() method
//will check all the currently loaded assemblies in memory for a custom compiler implementing
//the ICompiler interface.
Type compiler = GetCompiler();
//Incase a non-default compiler was specified and we could not find it in memory, fail.
if (compiler.Name == "ICompiler")
{
this._CompileMessages = new string[] { "Compilation Failed.", "Unable to locate the specified compiler of Type '" + Compiler + "'." };
return false;
}
//Get the compiler parameters.
CompilerParameters param = GetParameters();
//Create a Instance of the compiler, either custom or internal.
ICompiler com = (ICompiler)Activator.CreateInstance(compiler);
//Setup it's properties to match that of our CompileEngine.
com.AssemblyReferences = AssemblyReferences;
com.ScriptExtension = ScriptExtension;
com.CompilerOptions = this.CompilerOptions;
//Compile the scripts.
Boolean isSuccess = com.Compile(param, scriptRepository);
HasErrors = !isSuccess;
//If the compilation failed, store all of the compiler errors
//into our _CompileMessages string.
if (!isSuccess)
{
List<String> compilerMessages = new List<string>();
foreach (String message in com.Results.Output)
{
compilerMessages.Add(message);
}
_CompileMessages = compilerMessages.ToArray();
return false;
}
else
{
//Compiling completed without error, so we need to save
//a reference to the compiled assembly.
CompiledAssembly = com.Results.CompiledAssembly;
return true;
}
}
/// <summary>
/// Compiles the script supplied.
/// The compiler will compile the script using the compiler specified with the CompileEngine.Compiler Property.
/// </summary>
/// <returns>Returns true if compilation was completed without any errors.</returns>
public Boolean Compile(FileInfo sourceFile)
{
if (!sourceFile.Exists)
{
this._CompileMessages = new String[] { "Error: File " + sourceFile.FullName + " does not exists." };
return false;
}
//Get the compiler that the developer has selected.
//If the developer chooses a compiler that is not part of the engine, the GetCompiler() method
//will check all the currently loaded assemblies in memory for a custom compiler implementing
//the ICompiler interface.
Type compiler = GetCompiler();
//Incase a non-default compiler was specified and we could not find it in memory, fail.
if (compiler.Name == "ICompiler")
{
this._CompileMessages = new string[] { "Compilation Failed.", "Unable to locate the specified compiler of Type '" + Compiler + "'." };
return false;
}
//Get the compiler parameters.
CompilerParameters param = GetParameters();
//Create a Instance of the compiler, either custom or internal.
ICompiler com = (ICompiler)Activator.CreateInstance(compiler);
//Setup it's properties to match that of our CompileEngine.
com.AssemblyReferences = AssemblyReferences;
com.ScriptExtension = ScriptExtension;
com.CompilerOptions = this.CompilerOptions;
//Compile the script.
Boolean isSuccess = com.Compile(param, sourceFile);
HasErrors = !isSuccess;
//If the compilation failed, store all of the compiler errors
//into our _CompileMessages string.
if (!isSuccess)
{
List<String> compilerMessages = new List<string>();
foreach (String message in com.Results.Output)
{
compilerMessages.Add(message);
}
_CompileMessages = compilerMessages.ToArray();
return false;
}
else
{
//Compiling completed without error, so we need to save
//a reference to the compiled assembly.
CompiledAssembly = com.Results.CompiledAssembly;
return true;
}
}
/// <summary>
/// Compiles the source code provided.
/// The compiler will compile the scripts using the compiler specified with the CompileEngine.Compiler Property.
/// </summary>
/// <returns>Returns true if compilation was completed without any errors.</returns>
public Boolean Compile(String[] sourceCode)
{
//Get the compiler that the developer has selected.
//If the developer chooses a compiler that is not part of the engine, the GetCompiler() method
//will check all the currently loaded assemblies in memory for a custom compiler implementing
//the ICompiler interface.
Type compiler = GetCompiler();
//Incase a non-default compiler was specified and we could not find it in memory, fail.
if (compiler.Name == "ICompiler")
{
this._CompileMessages = new string[] { "Compilation Failed.", "Unable to locate the specified compiler of Type '" + Compiler + "'." };
return false;
}
//Get the compiler parameters.
CompilerParameters param = GetParameters();
//Create a Instance of the compiler, either custom or internal.
ICompiler com = (ICompiler)Activator.CreateInstance(compiler);
//Setup it's properties to match that of our CompileEngine.
com.AssemblyReferences = AssemblyReferences;
com.ScriptExtension = ScriptExtension;
com.CompilerOptions = this.CompilerOptions;
//Compile the scripts.
Boolean isSuccess = com.Compile(param, sourceCode);
HasErrors = !isSuccess;
//If the compilation failed, store all of the compiler errors
//into our _CompileMessages string.
if (!isSuccess)
{
List<String> compilerMessages = new List<string>();
foreach (String message in com.Results.Output)
{
compilerMessages.Add(message);
}
_CompileMessages = compilerMessages.ToArray();
return false;
}
else
{
//Compiling completed without error, so we need to save
//a reference to the compiled assembly.
CompiledAssembly = com.Results.CompiledAssembly;
return true;
}
}
/// <summary>
/// Gets compiler parameters that the compiler will be supplied with.
/// </summary>
/// <returns></returns>
private CompilerParameters GetParameters()
{
//Setup some default parameters that will be used by the compilers.
CompilerParameters param = new CompilerParameters(this.AssemblyReferences.ToArray());
param.GenerateExecutable = false;
param.GenerateInMemory = true;
//Left out, Add as CompileEngine properties in the future.
//param.TreatWarningsAsErrors = true;
//param.WarningLevel = 0;
//param.IncludeDebugInformation = true;
return param;
}
/// <summary>
/// Gets the compiler that will be used during the compilation of the scripts.
/// If a custom compiler is used, then the method will check every assembly in memory
/// and find the custom one requested. If none are found, then it will return a new
/// Object of type ICompiler.
/// </summary>
/// <returns></returns>
private Type GetCompiler()
{
Type compiler = typeof(ICompiler);
//Internal CSharpRaw compiler Type specified, so we'll use that.
if ((this.Compiler.ToLower() == "MudCompiler"))
{
compiler = typeof(MudEngine.Scripting.MudScriptCompiler);
return compiler;
}
//Build a collection of available compilers by scanning all the assemblies loaded in memory.
//If any of the assemblies contain a Type that uses the ICompiler interface, we will assume that the
//assembly is a add-on assembly for rScript, adding a new compiler to the CompileEngine.
//Only used if a non-internal compiler is specified
else
{ //Non-internal compiler supplied, so loop through every assembly loaded in memory
foreach (Assembly a in _Assemblies)
{
Boolean isCompiler = false;
//Create an array of all Types within this assembly
Type[] types = a.GetTypes();
//Itterate through each Type; See if any implement the ICompiler interface.
foreach (Type t in a.GetTypes())
{
//If this Type implements ICompiler, then our compiler field needs to reference the Type.
if ((t.GetInterface("ICompiler") != null) && (t.Name.ToLower() == Compiler.ToLower()))
{
//compiler needs to reference this custom compiler Type.
compiler = t;
isCompiler = true;
break;
}
}
//If we found a matching compiler, then exit this loop.
if (isCompiler)
break;
}
}
return compiler;
}
}
}

View file

@ -1,208 +0,0 @@
/*
* Microsoft Public License (Ms-PL)
* This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
* 1. Definitions
* The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
* A "contribution" is the original software, or any additions or changes to the software.
* A "contributor" is any person that distributes its contribution under this license.
* "Licensed patents" are a contributor's patent claims that read directly on its contribution.
* 2. Grant of Rights
* (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
* (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
* 3. Conditions and Limitations
* (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
* (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
* (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
* (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
* (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
*/
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using Microsoft.CSharp;
namespace MudEngine.Scripting
{
/// <summary>
/// Standard C# source code compiler.
/// </summary>
public class MudScriptCompiler : rScripting.Compilers.ICompiler
{
/// <summary>
/// The file extension used for the script files.
/// </summary>
public String ScriptExtension { get; set; }
/// <summary>
/// Provides a collection of Assemblies that the compiler will add to its reference list.
/// </summary>
public List<String> AssemblyReferences { get; set; }
/// <summary>
/// The results of the compilation
/// </summary>
public CompilerResults Results { get; set; }
/// <summary>
/// Provides compiling options to various compilers, if they support this feature.
/// </summary>
public Dictionary<String, String> CompilerOptions { get; set; }
public MudScriptCompiler()
{
}
/// <summary>
/// Compiles the source files found within the scriptRepository directory matching the ICompiler.ScriptExtension
/// The Compiler defaults to the C# 4.0 compiler if none other is supplied via the ICompiler.CompilerOptions argument.
/// </summary>
/// <param name="param">Compiler Parameters that can be supplied to customize the compilation of the source.</param>
/// <returns>Returns true if the compilation was completed without error.</returns>
public Boolean Compile(CompilerParameters param, String scriptRepository)
{
//Make sure we have a compiler version supplied.
if (!CompilerOptions.ContainsKey("CompilerVersion"))
CompilerOptions.Add("CompilerVersion", "v4.0");
//Instance a reference to the C# code provider, this is what will perform the compiling.
CSharpCodeProvider provider = new CSharpCodeProvider(CompilerOptions);
//Create an array of script files found within the ScriptRepository matching the ScriptExtension properties.
String[] baseScripts = Directory.GetFiles(scriptRepository, "*" + this.ScriptExtension, SearchOption.AllDirectories);
String modifiedScriptsPath = "temp";
//Setup the additional sourcecode that's needed in the script.
String[] usingStatements = new String[]
{
"using System;",
"using System.Collections.Generic;",
"using System.Text;",
"using System.Linq;",
"using MudEngine.Commands;",
"using MudEngine.GameObjects;",
"using MudEngine.GameObjects.Characters;",
"using MudEngine.GameObjects.Environment;",
"using MudEngine.GameObjects.Items;",
"using MudEngine.GameManagement;",
"using MudEngine.FileSystem;",
"using MudEngine.Scripting;"
};
if (System.IO.Directory.Exists(modifiedScriptsPath))
System.IO.Directory.Delete(modifiedScriptsPath, true);
System.IO.Directory.CreateDirectory(modifiedScriptsPath);
//Wrap the scripts around a namespace.
foreach (String script in baseScripts)
{
String revisedScriptContent = "namespace MudScripts\n{\n\n\n}";
FileStream input = new FileStream(script, FileMode.Open, FileAccess.Read, FileShare.None);
FileStream output = new FileStream(Path.Combine(modifiedScriptsPath, Path.GetFileName(script)), FileMode.Create, FileAccess.Write);
StreamReader reader = new StreamReader(input, System.Text.Encoding.Default);
StreamWriter writer = new StreamWriter(output, System.Text.Encoding.Default);
//Read the script into a private field for manipulation
String scriptContent = reader.ReadToEnd();
//No longer need the reader, as we now have the content that we need.
reader.Close();
//Insert using statements into the revised code section containing the scripts namespace
foreach (String statement in usingStatements)
revisedScriptContent = revisedScriptContent.Insert(0, statement);
//Insert the original script content into the revised content, now including the correct script header
revisedScriptContent = revisedScriptContent.Insert(revisedScriptContent.Length - 1, scriptContent);
writer.Write(revisedScriptContent);
writer.Flush();
writer.Close();
}
String[] ConvertedScripts = Directory.GetFiles("temp", "*" + this.ScriptExtension, SearchOption.AllDirectories);
//Compile the scripts and provide the Results property with a reference to the compilation results.
param.ReferencedAssemblies.Add("MudEngine.dll");
Results = provider.CompileAssemblyFromFile(param, ConvertedScripts);
System.IO.Directory.Delete(modifiedScriptsPath, true);
//if the compiler has errors, return false.
if (Results.Errors.HasErrors)
return false;
else
return true;
}
/// <summary>
/// Compiles the source files found within the scriptFile argument.
/// The Compiler defaults to the C# 4.0 compiler if none other is supplied via the ICompiler.CompilerOptions argument.
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public Boolean Compile(CompilerParameters param, FileInfo scriptFile)
{
//TODO: Add single-file compilation support
return false; //Single file compiling not implemented. TODO!
/**** Unreachable Code at the moment
//Make sure we have a compiler version supplied.
if (!CompilerOptions.ContainsKey("CompilerVersion"))
CompilerOptions.Add("CompilerVersion", "v4.0");
CSharpCodeProvider provider = new CSharpCodeProvider(CompilerOptions);
//Make sure the file exists prior to attempting to compile it.
if (scriptFile.Exists)
{
//Compile the script and provide the Results property with a referece to the compilation results.
Results = provider.CompileAssemblyFromFile(param, scriptFile.FullName);
}
else
{
Results.Errors.Add(new CompilerError(scriptFile.FullName, 0, 0, "rS01", "The supplied filename does not exist."));
return false;
}
if (Results.Errors.HasErrors)
return false;
else
return true;
***/
}
/// <summary>
/// Compiles the source code found within the scriptSourceCode argument
/// The Compiler defaults to the C# 4.0 compiler if none other is supplied via the ICompiler.CompilerOptions argument.
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public Boolean Compile(CompilerParameters param, String[] scriptSourceCode)
{
//Source Code compiling not implemented.
return false; //TODO: Add source code compiling support.
/**** Unreachable code at the moment
if (!CompilerOptions.ContainsKey("CompilerVersion"))
CompilerOptions.Add("CompilerVersion", "v4.0");
CSharpCodeProvider provider = new CSharpCodeProvider(CompilerOptions);
if (scriptSourceCode.Length == 0)
{
Results.Errors.Add(new CompilerError("None", 0, 0, "rS02", "No Source provided."));
return false;
}
else
{
Results = provider.CompileAssemblyFromSource(param, scriptSourceCode);
}
if (Results.Errors.HasErrors)
return false;
else
return true;
****/
}
}
}

View file

@ -1,135 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace MudEngine.Scripting
{
public class ScriptFactory
{
//The assembly loaded that will be used.
private List<Assembly> _AssemblyCollection;
#if WINDOWS_PC
/// <summary>
/// Constructor for a Windows PC Script Factory
/// </summary>
/// <param name="assembly"></param>
public ScriptFactory(String assembly)
{
Assembly a;
_AssemblyCollection = new List<Assembly>();
//See if a file exists first with this assembly name.
if (File.Exists(assembly))
{
a = Assembly.Load(assembly);
}
//If not, then try and load it differently
else
{
a = Assembly.Load(new AssemblyName(assembly));
}
if (a == null)
return;
//Add the assembly to our assembly collection.
_AssemblyCollection.Add(a);
}
/// <summary>
/// Alternate Constructor for a Windows PC ScriptFactory
/// </summary>
/// <param name="assembly"></param>
public ScriptFactory(Assembly assembly)
{
_AssemblyCollection = new List<Assembly>();
//Add the supplied assembly to our AssemblyCollection
_AssemblyCollection.Add(assembly);
}
#elif WINDOWS_PHONE
public ScriptFactory()
{
_AssemblyCollection = new List<Assembly>();
foreach(System.Windows.AssemblyPart part in System.Windows.Deployment.Current.Parts)
{
String assemName = part.Source.Replace(".dll", String.Empty);
Assembly a = Assembly.Load(assemName);
_AssemblyCollection.Add(a);
}
}
#endif
/// <summary>
/// Adds another assembly to the factories assembly collection.
/// </summary>
/// <param name="assembly">provides the name of the assembly, or file name that needs to be loaded.</param>
public void AddAssembly(String assembly)
{
Assembly a;
//See if a file exists first with this assembly name.
if (File.Exists(assembly))
{
a = Assembly.Load(new AssemblyName(assembly));
}
//If not, then try and load it differently
else
{
a = Assembly.Load(assembly);
}
//Add the assembly to our assembly collection.
_AssemblyCollection.Add(a);
}
/// <summary>
/// Adds another assembly to the factories assembly collection.
/// </summary>
/// <param name="assembly">Provides a reference to the assembly that will be added to the collection.</param>
public void AddAssembly (Assembly assembly)
{
//Add the supplied assembly to our AssemblyCollection
_AssemblyCollection.Add(assembly);
}
public ScriptObject GetScript(String scriptName)
{
Type script = typeof(Object);
Boolean foundScript = false;
if (_AssemblyCollection.Count == 0)
return new ScriptObject(null);
try
{
foreach (Assembly a in _AssemblyCollection)
{
//The assembly can be null if accessing after a failed compilation.
if (a == null)
continue;
foreach (Type t in a.GetTypes())
{
if (t.Name == scriptName)
{
script = t;
foundScript = true;
break;
}
}
if (foundScript)
break;
}
}
catch
{
throw new Exception("Error encounted during factory instancing of script " + scriptName + ".");
}
ScriptObject obj = new ScriptObject(Activator.CreateInstance(script));
return obj;
}
}
}

View file

@ -1,92 +0,0 @@
using System;
using System.Reflection;
using System.Text;
namespace MudEngine.Scripting
{
public class ScriptObject
{
public Object Instance { get; set; }
public ScriptObject(Object instance)
{
if (instance == null)
Instance = new Object();
else
Instance = instance;
}
~ScriptObject()
{
//TODO: Add ability to call a Shutdown() method within this Instance.
Instance = null;
}
public void SetProperty(String propertyName, object propertyValue)
{
PropertyInfo propertyInfo = Instance.GetType().GetProperty(propertyName);
if (propertyValue is String)
{
if (propertyInfo.PropertyType.Name is String)
{
propertyInfo.SetValue(Instance, propertyValue, null);
}
}
}
public object GetProperty(String propertyName)
{
String[] tokens = propertyName.Split('.');
PropertyInfo previousProperty = Instance.GetType().GetProperty(tokens[0]);
return previousProperty.GetValue(Instance, null);
}
#if WINDOWS_PC
public dynamic GetProperty()
{
return Instance;
}
#endif
public object GetField(String propertyName)
{
String[] tokens = propertyName.Split('.');
FieldInfo previousField = Instance.GetType().GetField(tokens[0]);
return previousField.GetValue(Instance);
}
#if WINDOWS_PC
public dynamic GetField()
{
return Instance;
}
#endif
public Object InvokeMethod(String methodName)
{
return InvokeMethod(methodName, null);
}
public Object InvokeMethod(String methodName, params Object[] parameters)
{
MethodInfo method = Instance.GetType().GetMethod(methodName);
try
{
if (parameters == null || parameters.Length == 0)
return method.Invoke(Instance, null);
else
return method.Invoke(Instance, parameters);
}
catch
{
StringBuilder sb = new StringBuilder();
sb.Append("Error invoking method. Does the method exist?");
return sb.ToString();
}
}
}
}

View file

@ -1,126 +0,0 @@
//Microsoft .NET Framework
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.ComponentModel;
//MUD Engine
using MudEngine.Core;
using MudEngine.GameManagement;
namespace MudEngine.GameObjects.Environment
{
[XmlInclude(typeof(BaseItem))]
[Serializable]
public class Door
{
public enum RoomTravelType
{
Arrival,
Departure
}
[Category("Door Settings")]
[DefaultValue(false)]
public Boolean IsLocked
{
get;
set;
}
[Category("Door Settings")]
[Browsable(false)]
public BaseItem RequiredKey
{
get;
set;
}
[Category("Door Settings")]
[DefaultValue(0)]
public Int32 LevelRequirement
{
get;
set;
}
[Category("Door Settings")]
public AvailableTravelDirections TravelDirection { get; set; }
/// <summary>
/// Gets or Sets the Room that the player will be arriving.
/// </summary>
public Room ArrivalRoom { get; set; }
/// <summary>
/// Gets or Sets the Room that the user is leaving.
/// </summary>
public Room DepartureRoom { get; set; }
private Game _Game;
public Door(GameManagement.Game game)
{
LevelRequirement = 0;
IsLocked = false;
RequiredKey = new BaseItem(game);
_Game = game;
}
public Boolean SetRoom(RoomTravelType roomType, String roomPath)
{
String[] path = roomPath.Split('>');
if (path.Length > 3)
{
Log.Write("Error in Door.SetRoom(" + roomType.ToString() + ", " + roomPath + ") does not contain a full Room Path.");
return false;
}
//TODO: Load the Realm via Game.World if it isn't loaded yet. Ensures that the Realm is only ever loaded once.
if (_Game.World.GetRealm(path[0]) != null)
{
Realm r = _Game.World.GetRealm(path[0]);
//TODO: Load the Zone via Game.World.GetRealm(). Ensures that only 1 instance of the Realm is loaded.
if (r.GetZone(path[1]) != null)
{
List<Zone> zlist = r.GetZone(path[1]);
Zone z = zlist[0];
//TODO: Load the Room via Game.World.GetRealm().GetZone(). Ensures that the Room is only loaded once in memory.
if (z.GetRoom(path[2]) != null)
{
List<Room> rlist = z.GetRoom(path[2]);
if (roomType == RoomTravelType.Arrival)
ArrivalRoom = rlist[0];
else
DepartureRoom = rlist[0];
return true;
}
else
{
Log.Write("Error in Door.SetRoom(" + roomType.ToString() + ", " + roomPath + ") does not contain a valid Room");
return false;
}//GetRoom
}//GetZone
else
{
Log.Write("Error in Door.SetRoom(" + roomType.ToString() + ", " + roomPath + ") does not contain a valid zone.");
return false;
}
}//GetRealm
else
{
Log.Write("Error in Door.SetRoom(" + roomType.ToString() + ", " + roomPath + ") does not contain a valid Realm");
return false;
}
}
}
}

View file

@ -1,158 +0,0 @@
//Microsoft .NET Framework
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.ComponentModel;
//MUD Engine
using MudEngine.FileSystem;
using MudEngine.GameObjects;
using MudEngine.Core;
namespace MudEngine.GameObjects.Environment
{
public class Realm : BaseEnvironment
{
[Category("Environment Information")]
[Description("A collection of Zones that are contained within this Realm. Players can traverse the world be traveling through Rooms that are contained within Zones. Note that it is not required to place a Zone into a Realm.")]
//[EditorAttribute(typeof(UIRealmEditor), typeof(System.Drawing.Design.UITypeEditor))]
public List<Zone> ZoneCollection { get; private set; }
/// <summary>
/// Gets or Sets if this Realm is the starting realm for the game.
/// </summary>
public Boolean IsInitialRealm { get; set; }
/// <summary>
/// The Initial Starting Zone for this Realm.
/// </summary>
public Zone InitialZone { get; set; }
protected override string SavePath
{
get
{
return Path.Combine(ActiveGame.DataPaths.Environment, Path.GetFileNameWithoutExtension(this.Filename));
}
}
/// <summary>
///
/// </summary>
/// <param name="game"></param>
public Realm(GameManagement.Game game) : base(game)
{
ZoneCollection = new List<Zone>();
InitialZone = new Zone(game);
}
/// <summary>
///
/// </summary>
/// <param name="filename"></param>
public override void Load(string filename)
{
base.Load(filename);
IsInitialRealm = Convert.ToBoolean(FileManager.GetData(filename, "IsInitialRealm"));
//Load all zones
foreach (String zone in FileManager.GetCollectionData(filename, "ZoneCollection"))
{
Zone z = new Zone(ActiveGame);
String path = Path.Combine(ActiveGame.DataPaths.Environment, Path.GetFileNameWithoutExtension(this.Filename), "Zones", Path.GetFileNameWithoutExtension(zone));
z.Load(Path.Combine(path, zone));
//Check if this is the initial Zone.
if (z.IsInitialZone)
InitialZone = z;
ZoneCollection.Add(z);
}
}
/// <summary>
///
/// </summary>
public override void Save()
{
String path = Path.Combine(ActiveGame.DataPaths.Environment, Path.GetFileNameWithoutExtension(Filename));
base.Save();
String filename = Path.Combine(path, Filename);
FileManager.WriteLine(filename, this.IsInitialRealm.ToString(), "IsInitialRealm");
if (this.InitialZone.Name != "New Zone")
FileManager.WriteLine(filename, this.InitialZone.Filename, "InitialZone");
String zonePath = Path.Combine(path, "Zones");
foreach (Zone z in ZoneCollection)
{
FileManager.WriteLine(filename, z.Filename, "ZoneCollection");
z.Save();
}
}
/// <summary>
///
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public List<Zone> GetZone(String filename)
{
List<Zone> zones = new List<Zone>();
if (!filename.ToLower().EndsWith(".zone"))
filename += ".zone";
foreach (Zone zone in ZoneCollection)
{
if (zone.Filename.ToLower() == filename.ToLower())
{
zones.Add(zone);
}
}
return zones;
}
/// <summary>
///
/// </summary>
/// <param name="zone"></param>
public void AddZone(Zone zone)
{
if (zone.IsInitialZone)
{
foreach (Zone z in ZoneCollection)
{
if (z.IsInitialZone)
{
z.IsInitialZone = false;
break;
}
}
}
if (zone.IsInitialZone)
InitialZone = zone;
//TODO: Check fo duplicates
ZoneCollection.Add(zone);
zone.Realm = Filename;
//Set the Zones default senses to that of the Realm provided the Zone does
//not already have a sense description assigned to it.
if ((!String.IsNullOrEmpty(this.Feel)) && (String.IsNullOrEmpty(zone.Feel)))
zone.Feel = this.Feel;
if ((!String.IsNullOrEmpty(this.Listen)) && (String.IsNullOrEmpty(zone.Listen)))
zone.Listen = this.Listen;
if ((!String.IsNullOrEmpty(this.Smell)) && (String.IsNullOrEmpty(zone.Smell)))
zone.Smell = this.Smell;
}
}
}

View file

@ -1,191 +0,0 @@
//Microsoft .NET Framework
using System;
using System.Collections;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
//MUD Engine
using MudEngine.FileSystem;
using MudEngine.Core;
using MudEngine.GameManagement;
namespace MudEngine.GameObjects.Environment
{
[XmlInclude(typeof(Door))]
public class Room : BaseObject
{
[Category("Environment Information")]
[Description("Allows for linking of Rooms together via Doorways")]
//[EditorAttribute(typeof(UIDoorwayEditor), typeof(UITypeEditor))]
[RefreshProperties(RefreshProperties.All)]
public List<Door> Doorways { get; internal set; }
[ReadOnly(true)]
[Description("This is the Zone that the Room is currently assigned to.")]
[Category("Environment Information")]
public String Zone
{
get;
set;
}
[ReadOnly(true)]
[Description("This is the Realm that the Room belongs to.")]
[Category("Environment Information")]
public String Realm
{
get;
set;
}
[Category("Environment Information")]
[DefaultValue(false)]
[Description("Determins if the Player can be attacked within this Room or not.")]
public Boolean IsSafe
{
get;
set;
}
/// <summary>
/// Gets or Sets if this is the starting room for the Zone that contains it.
/// </summary>
[Browsable(true)]
[Description("Sets if this is the starting room for the Zone that contains it.")]
public Boolean IsInitialRoom
{
get;
set;
}
/// <summary>
/// Gets the current complete location for this Room, including Realm and Zone paths.
/// This includes the objects Filenames.
/// </summary>
public String RoomLocation
{
get
{
return this.Realm + ">" + this.Zone + ">" + this.Filename;
}
}
/// <summary>
/// Gets the current complete location for this Room, including Realm and Zone paths.
/// This includes the objects Filenames without their file extension.
/// </summary>
public String RoomLocationWithoutExtension
{
get
{
return Path.GetFileNameWithoutExtension(Realm) + ">" + Path.GetFileNameWithoutExtension(Zone) + ">" + Path.GetFileNameWithoutExtension(Filename);
}
}
protected override string SavePath
{
get
{
return Path.Combine(ActiveGame.DataPaths.Environment, Path.GetFileNameWithoutExtension(this.Realm), "Zones", Path.GetFileNameWithoutExtension(this.Zone), "Rooms");
}
}
protected TerrainTypes Terrain { get; set; }
public Room(Game game) :base(game)
{
Doorways = new List<Door>();
IsSafe = false;
}
/// <summary>
/// Saves the Room to file within the Game.DataPath.Environment path.
/// Room is saved within a Realm/Zone/Room directory structure
/// </summary>
/// <param name="path"></param>
public override void Save()
{
base.Save();
String filename = Path.Combine(this.SavePath, Filename);
FileManager.WriteLine(filename, IsInitialRoom.ToString(), "IsInitialRoom");
FileManager.WriteLine(filename, this.IsSafe.ToString(), "IsSafe");
FileManager.WriteLine(filename, this.RoomLocationWithoutExtension, "RoomLocation");
FileManager.WriteLine(filename, Doorways.Count.ToString(), "DoorwayCount");
foreach (Door d in Doorways)
{
FileManager.WriteLine(filename, d.ArrivalRoom.RoomLocation, "DoorwayArrivalRoom");
FileManager.WriteLine(filename, d.DepartureRoom.RoomLocation, "DoorwayDepartureRoom");
FileManager.WriteLine(filename, d.IsLocked.ToString(), "DoorwayIsLocked");
FileManager.WriteLine(filename, d.LevelRequirement.ToString(), "DoorwayLevelRequirement");
FileManager.WriteLine(filename, d.TravelDirection.ToString(), "DoorwayTravelDirection");
//TODO: Save Doorway Keys
}
}
public override void Load(string filename)
{
base.Load(filename);
this.IsInitialRoom = Convert.ToBoolean(FileManager.GetData(filename, "IsInitialRoom"));
this.IsSafe = Convert.ToBoolean(FileManager.GetData(filename, "IsSafe"));
String[] env = FileManager.GetData(filename, "RoomLocation").Split('>');
if (env.Length != 3)
{
Log.Write("ERROR: Room " + filename + " does not contain a proper location path in Room.RoomLocation. Path is " + FileManager.GetData(filename, "RoomLocation"));
return;
}
this.Realm = env[0] + ".Realm";
this.Zone = env[1] + ".Zone";
//SetRoomToDoorNorth
//SetRoomToDoorEast
//etc...
//Restoring Doorways performed by Zone.RestoreLinkedRooms() Called via GameWorld.Load();
}
/// <summary>
/// Checks to see if a doorway in the travelDirection exists.
/// </summary>
/// <param name="travelDirection"></param>
/// <returns></returns>
public Boolean DoorwayExist(AvailableTravelDirections travelDirection)
{
return Doorways.Exists(d => d.TravelDirection == travelDirection);
//foreach (Door door in Doorways)
//{
// if (door.TravelDirection == travelDirection)
// return true;
//}
//return false;
}
/// <summary>
/// Gets reference to the Rooms door connected in the supplied travelDirection
/// </summary>
/// <param name="travelDirection"></param>
/// <returns></returns>
public Door GetDoor(AvailableTravelDirections travelDirection)
{
return Doorways.First(d => d.TravelDirection == travelDirection);
//foreach (Door door in this.Doorways)
//{
// if (door.TravelDirection == travelDirection)
// return door;
//}
//return null;
}
}
}

View file

@ -1,34 +0,0 @@
using System;
//MUD Engine
using MudEngine.FileSystem;
using MudEngine.GameObjects;
using MudEngine.GameObjects.Environment;
namespace MudEngine.GameObjects.Environment
{
public struct StartingLocation
{
public String Room;
public String Zone;
public String Realm;
public override String ToString()
{
if (String.IsNullOrEmpty(Room))
return "No initial location defined.";
else
{
if (Realm == "No Realm Associated.")
{
return Zone + "->" + Room;
}
else
{
return Realm + "->" + Zone + "->" + Room;
}
}
}
}
}

View file

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MudEngine.GameObjects.Environment
{
public enum TerrainTypes
{
Stone,
Dirt,
Grass,
Rock,
Wood,
Water,
Air,
Mud,
Other,
}
}

View file

@ -1,68 +0,0 @@
//Microsoft .NET Framework
using System;
namespace MudEngine.GameObjects
{
[System.Flags]
public enum AvailableTravelDirections : uint
{
None = 0,
North = 1,
South = 2,
East = 4,
West = 8,
Up = 16,
Down = 32,
Northeast = North | East,
Northwest = North | West,
Southeast = South | East,
Southwest = South | West
}
public static class TravelDirections
{
public static AvailableTravelDirections GetReverseDirection(AvailableTravelDirections Direction)
{
switch (Direction)
{
case AvailableTravelDirections.North:
return AvailableTravelDirections.South;
case AvailableTravelDirections.South:
return AvailableTravelDirections.North;
case AvailableTravelDirections.East:
return AvailableTravelDirections.West;
case AvailableTravelDirections.West:
return AvailableTravelDirections.East;
case AvailableTravelDirections.Up:
return AvailableTravelDirections.Down;
case AvailableTravelDirections.Down:
return AvailableTravelDirections.Up;
case AvailableTravelDirections.Northeast:
return AvailableTravelDirections.Southwest;
case AvailableTravelDirections.Southwest:
return AvailableTravelDirections.Northeast;
case AvailableTravelDirections.Northwest:
return AvailableTravelDirections.Southeast;
case AvailableTravelDirections.Southeast:
return AvailableTravelDirections.Northwest;
default:
return AvailableTravelDirections.None;
}
}
public static AvailableTravelDirections GetTravelDirectionValue(String Direction)
{
Array values = Enum.GetValues(typeof(AvailableTravelDirections));
foreach (Int32 value in values)
{
String displayName = Enum.GetName(typeof(AvailableTravelDirections), value);
if (displayName.ToLower() == Direction.ToLower())
return (AvailableTravelDirections)Enum.Parse(typeof(AvailableTravelDirections), displayName);
}
return AvailableTravelDirections.None;
}
}
}

View file

@ -1,297 +0,0 @@
//Microsoft .NET Framework
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Xml.Serialization;
//MUD Engine
using MudEngine.FileSystem;
using MudEngine.GameManagement;
using MudEngine.GameObjects;
using MudEngine.Items;
using MudEngine.Core;
namespace MudEngine.GameObjects.Environment
{
[XmlInclude(typeof(Room))]
public class Zone : BaseObject
{
[Category("Environment Information")]
[DefaultValue(0)]
[Description("The amount to drain each stat by if StatDrain is enabled.")]
public Int32 StatDrainAmount
{
get;
set;
}
[Category("Environment Information")]
[Description("Enable or Disable the ability for draining stats while traversing.")]
[DefaultValue(false)]
public Boolean StatDrain
{
get;
set;
}
[ReadOnly(true)]
[Category("Environment Information")]
[Description("The Realm that this Zone is assigned to. It is not required to be contained within a Realm.")]
public String Realm
{
get;
set;
}
[Category("Environment Information")]
[Description("Determins if the Player can be attacked within this Room or not.")]
[DefaultValue(false)]
public Boolean IsSafe
{
get;
set;
}
/// <summary>
/// Gets or Sets the ability for this Zone to be the initial starting Zone for the game.
/// </summary>
[Category("Environment Information")]
[Description("Sets that this Zone is a starting Zone for the game.")]
[DefaultValue(false)]
public Boolean IsInitialZone
{
get;
set;
}
[Category("Environment Information")]
//[EditorAttribute(typeof(UIRoomEditor), typeof(UITypeEditor))]
[Description("Collection of Rooms that have been created. Editing the Rooms Collection lets you manage the Zones rooms.")]
public List<Room> RoomCollection { get; private set; }
/// <summary>
/// Gets the initial Room for this Zone.
/// </summary>
[Category("Environment Information")]
public Room InitialRoom { get; set; }
protected override String SavePath
{
get
{
return Path.Combine(ActiveGame.DataPaths.Environment, Path.GetFileNameWithoutExtension(this.Realm), "Zones", Path.GetFileNameWithoutExtension(Filename));
}
}
public Zone(GameManagement.Game game)
: base(game)
{
RoomCollection = new List<Room>();
InitialRoom = new Room(game);
IsSafe = false;
Realm = "No Realm Associated.";
}
public override void Save()
{
base.Save();
String filename = Path.Combine(SavePath, Filename);
FileManager.WriteLine(filename, this.IsInitialZone.ToString(), "IsInitialZone");
FileManager.WriteLine(filename, this.IsSafe.ToString(), "IsSafe");
FileManager.WriteLine(filename, this.Realm, "Realm");
FileManager.WriteLine(filename, this.StatDrain.ToString(), "StatDrain");
FileManager.WriteLine(filename, this.StatDrainAmount.ToString(), "StatDrainAmount");
if (this.InitialRoom.Name != "New Room")
FileManager.WriteLine(filename, this.InitialRoom.Filename, "InitialRoom");
String roomPath = Path.Combine(SavePath, "Rooms");
foreach (Room r in RoomCollection)
{
FileManager.WriteLine(filename, r.Filename, "RoomCollection");
r.Save();
}
}
public override void Load(string filename)
{
base.Load(filename);
this.IsInitialZone = Convert.ToBoolean(FileManager.GetData(filename, "IsInitialZone"));
this.IsSafe = Convert.ToBoolean(FileManager.GetData(filename, "IsSafe"));
this.Realm = FileManager.GetData(filename, "Realm");
this.StatDrain = Convert.ToBoolean(FileManager.GetData(filename, "StatDrain"));
this.StatDrainAmount = Convert.ToInt32(FileManager.GetData(filename, "StatDrainAmount"));
//Now get the rooms in the zone
foreach (String room in FileManager.GetCollectionData(filename, "RoomCollection"))
{
Room r = new Room(ActiveGame);
String path = Path.Combine(ActiveGame.DataPaths.Environment, Path.GetFileNameWithoutExtension(this.Realm), "Zones", Path.GetFileNameWithoutExtension(this.Filename), "Rooms");
r.Load(Path.Combine(path, room));
RoomCollection.Add(r);
if (r.IsInitialRoom)
this.InitialRoom = r;
}
}
/// <summary>
/// Adds the supplied room into the Zones Room collection.
/// </summary>
/// <param name="room"></param>
public void AddRoom(Room room)
{
if (room.IsInitialRoom)
{
//Look if we already have a initial room. If so change it. Only 1 InitialRoom per Zone permitted.
foreach (Room r in RoomCollection)
{
if (r.IsInitialRoom)
{
r.IsInitialRoom = false;
break;
}
}
}
if (room.IsInitialRoom)
InitialRoom = room;
//TODO: Check for duplicate Rooms.
RoomCollection.Add(room);
room.Zone = Filename;
room.Realm = Realm;
//Set the Rooms default senses to that of the Zones provided the Room does
//not already have a sense description assigned to it.
if ((!String.IsNullOrEmpty(this.Feel)) && (String.IsNullOrEmpty(room.Feel)))
room.Feel = this.Feel;
if ((!String.IsNullOrEmpty(this.Listen)) && (String.IsNullOrEmpty(room.Listen)))
room.Listen = this.Listen;
if ((!String.IsNullOrEmpty(this.Smell)) && (String.IsNullOrEmpty(room.Smell)))
room.Smell = this.Smell;
}
public List<Room> GetRoom(String filename)
{
List<Room> rooms = new List<Room>();
if (!filename.ToLower().EndsWith(".room"))
filename += ".Room";
foreach (Room r in RoomCollection)
{
if (r.Filename.ToLower() == filename.ToLower())
{
rooms.Add(r);
}
}
return rooms;
}
public void RestoreLinkedRooms()
{
//Iterate through each Room within this Zones collection and link it with it's corresponding Room.
foreach (Room r in RoomCollection)
{
String filename = ActiveGame.DataPaths.Environment + "\\" + Path.GetFileNameWithoutExtension(r.Realm) + "\\Zones\\" + Path.GetFileNameWithoutExtension(r.Zone) + "\\" + "Rooms\\" + r.Filename;
//Get how many doors this Room contains
Int32 count = Convert.ToInt32(FileManager.GetData(filename, "DoorwayCount"));
List<String> data = new List<string>();
data = FileManager.GetDataSpan(filename, 5, "DoorwayArrivalRoom", true);
//If no doors, then skip to the next room in the collection.
if ((count == 0) || (data.Count == 0))
continue;
for (int x = 0; x < (count * 5); x += 5)
{
Door d = new Door(ActiveGame);
Int32 index = x;
//Restore the Arrival Room first.
if (!d.SetRoom(Door.RoomTravelType.Arrival, data[index]))
{
Log.Write("Error: Failed to set the Arrival Doorway for Room " + r.RoomLocationWithoutExtension);
}
if (!d.SetRoom(Door.RoomTravelType.Departure, data[index + 1]))
{
Log.Write("Error: Failed to set the departure Doorway for Room " + r.RoomLocationWithoutExtension);
}
//Restore settings.
d.IsLocked = Convert.ToBoolean(data[index + 2]);
d.LevelRequirement = Convert.ToInt32(data[index + 3]);
//Restore the travel direction enum value.
Array values = Enum.GetValues(typeof(AvailableTravelDirections));
foreach (Int32 value in values)
{
//Since enum values are not strings, we can't simply just assign the String to the enum
String displayName = Enum.GetName(typeof(AvailableTravelDirections), value);
//If the value = the String saved, then perform the needed conversion to get our data back
if (displayName.ToLower() == data[index + 4].ToLower())
{
d.TravelDirection = (AvailableTravelDirections)Enum.Parse(typeof(AvailableTravelDirections), displayName);
break;
}
}
r.Doorways.Add(d);
}
}
}
public void LinkRooms(AvailableTravelDirections departureDirection, Room arrivalRoom, Room departureRoom)
{
LinkRooms(departureDirection, arrivalRoom, departureRoom, 0);
}
public void LinkRooms(AvailableTravelDirections departureDirection, Room arrivalRoom, Room departureRoom, Int32 requiredLevel)
{
LinkRooms(departureDirection, arrivalRoom, departureRoom, requiredLevel, false, null);
}
public void LinkRooms(AvailableTravelDirections departureDirection, Room arrivalRoom, Room departureRoom, Int32 requiredLevel, Boolean isLocked, BaseItem requiredKey)
{
Door door = new Door(ActiveGame);
door.ArrivalRoom = arrivalRoom;
door.DepartureRoom = departureRoom;
if (isLocked)
{
door.IsLocked = isLocked;
door.RequiredKey = requiredKey;
}
door.TravelDirection = departureDirection;
departureRoom.Doorways.Add(door);
//Now we set up the door for the opposite room.
door = new Door(ActiveGame);
door.DepartureRoom = arrivalRoom;
door.ArrivalRoom = departureRoom;
if (isLocked)
{
door.IsLocked = isLocked;
door.RequiredKey = requiredKey;
}
door.TravelDirection = TravelDirections.GetReverseDirection(departureDirection);
arrivalRoom.Doorways.Add(door);
}
}
}