Skip to content

Instantly share code, notes, and snippets.

Created Sep 10, 2015
Embed
What would you like to do?
using Engine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Adventure
{
public partial class Adventure : Form
{
private Player _player;
private Monster _currentMonster;
public const string PLAYER_DATA_FILE_NAME = "PlayerData.xml";
public Adventure(bool startNewGame, string playerName)
{
InitializeComponent();
if (startNewGame == false)
{
if (File.Exists(PLAYER_DATA_FILE_NAME))
{
_player = Player.CreatePlayerFromXmlString(File.ReadAllText(PLAYER_DATA_FILE_NAME));
}
else
{
MessageBox.Show("There was no file to load from. Starting new game");
lblPlayerName.Text = playerName;
_player = Player.CreateDefaultPlayer();
}
}
else
{
lblPlayerName.Text = playerName;
_player = Player.CreateDefaultPlayer();
}
MoveTo(_player.CurrentLocation);
UpdatePlayerStats();
}
private void btnNorth_Click(object sender, EventArgs e)
{
MoveTo(_player.CurrentLocation.LocationToNorth);
}
private void btnEast_Click(object sender, EventArgs e)
{
MoveTo(_player.CurrentLocation.LocationToEast);
}
private void btnSouth_Click(object sender, EventArgs e)
{
MoveTo(_player.CurrentLocation.LocationToSouth);
}
private void btnWest_Click(object sender, EventArgs e)
{
MoveTo(_player.CurrentLocation.LocationToWest);
}
private void MoveTo(Location newLocation)
{
//rtbLocation.Text += Player.val.ToString();
//Does the location have any required items
if (!_player.HasRequiredItemToEnterThisLocation(newLocation))
{
rtbMessages.Text += "You must have a " + newLocation.ItemRequiredToEnter.Name + " to enter this location." + Environment.NewLine;
return;
}
// Update the player's current location
_player.CurrentLocation = newLocation;
// Show/hide available movement buttons
btnNorth.Visible = (newLocation.LocationToNorth != null);
btnEast.Visible = (newLocation.LocationToEast != null);
btnSouth.Visible = (newLocation.LocationToSouth != null);
btnWest.Visible = (newLocation.LocationToWest != null);
// Display current location name and description
rtbLocation.Text = "You are here: " + newLocation.Name + Environment.NewLine;
rtbLocation.Text += newLocation.Description + Environment.NewLine;
// Heal the player by 1 point, everytime they change locations
//_player.CurrentHitPoints = _player.MaximumHitPoints;
_player.CurrentHitPoints = _player.CurrentHitPoints + 1;
if (_player.CurrentHitPoints > _player.MaximumHitPoints)
{
_player.CurrentHitPoints = _player.MaximumHitPoints;
}
// Update Hit Points in UI
lblHitPoints.Text = _player.CurrentHitPoints.ToString();
// Does the location have a quest?
if (newLocation.QuestAvailableHere != null)
{
// See if the player already has the quest, and if they've completed it
bool playerAlreadyHasQuest = _player.HasThisQuest(newLocation.QuestAvailableHere);
bool playerAlreadyCompletedQuest = _player.CompletedThisQuest(newLocation.QuestAvailableHere);
// See if the player already has the quest
if (playerAlreadyHasQuest)
{
// If the player has not completed the quest yet
if (!playerAlreadyCompletedQuest)
{
// See if the player has all the items needed to complete the quest
bool playerHasAllItemsToCompleteQuest = _player.HasAllQuestCompletionItems(newLocation.QuestAvailableHere);
// The player has all items required to complete the quest
if (playerHasAllItemsToCompleteQuest)
{
// Display message
rtbMessages.Text += Environment.NewLine;
rtbMessages.Text += "You complete the '" + newLocation.QuestAvailableHere.Name + "' quest." + Environment.NewLine;
rtbMessages.Text += newLocation.QuestAvailableHere.CompletionDialogue + Environment.NewLine;
// Remove quest items from inventory
_player.RemoveQuestCompletionItems(newLocation.QuestAvailableHere);
// Give quest rewards
rtbMessages.Text += "You receive: " + Environment.NewLine;
rtbMessages.Text += newLocation.QuestAvailableHere.RewardExperiencePoints.ToString() + " experience points" + Environment.NewLine;
rtbMessages.Text += newLocation.QuestAvailableHere.RewardGold.ToString() + " gold" + Environment.NewLine;
rtbMessages.Text += newLocation.QuestAvailableHere.RewardItem.Name + Environment.NewLine;
rtbMessages.Text += Environment.NewLine;
_player.AddExperiencePoints(newLocation.QuestAvailableHere.RewardExperiencePoints);
_player.Gold += newLocation.QuestAvailableHere.RewardGold;
// Add the reward item to the player's inventory
_player.AddItemToInventory(newLocation.QuestAvailableHere.RewardItem);
// Mark the quest as completed
_player.MarkQuestCompleted(newLocation.QuestAvailableHere);
}
}
}
else
{
// The player does not already have the quest
// Display the messages
rtbMessages.Text += Environment.NewLine;
rtbMessages.Text += "You receive the ''" + newLocation.QuestAvailableHere.Name + "'' quest." + Environment.NewLine;
rtbMessages.Text += newLocation.QuestAvailableHere.Description + Environment.NewLine;
rtbMessages.Text += "To complete it, return with: " + Environment.NewLine;
foreach (QuestCompletionItem qci in newLocation.QuestAvailableHere.QuestCompletionItems)
{
if (qci.Quantity == 1)
{
rtbMessages.Text += "-- " + qci.Details.Name + Environment.NewLine;
}
else
{
rtbMessages.Text += "-- " + qci.Quantity.ToString() + " " + qci.Details.NamePlural + Environment.NewLine;
}
}
rtbMessages.Text += Environment.NewLine;
// Add the quest to the player's quest list
_player.Quests.Add(new PlayerQuest(newLocation.QuestAvailableHere));
}
}
if (newLocation.KilledBossMonster)
{
_currentMonster = null;
}
else
{
_currentMonster = newLocation.BossMonster;
}
// Does the location have a monster?
if (newLocation.MonsterLivingHere != null)
{
//Randomize monster spawn, makes it so monster will not spawn on tile everytime, even if there is a monster there
int rndVal = RandomNumberGenerator.NumberBetween(0, 100);
if (rndVal >= 30)
{
rtbMessages.Text += "You see a " + newLocation.MonsterLivingHere.Name + Environment.NewLine;
// Make a new monster, using the values from the standard monster in the World.Monster list
Monster standardMonster = World.MonsterByID(newLocation.MonsterLivingHere.ID);
_currentMonster = new Monster(standardMonster.ID, standardMonster.Name, standardMonster.MaximumDamage,
standardMonster.RewardExperiencePoints, standardMonster.RewardGold, standardMonster.CurrentHitPoints, standardMonster.MaximumHitPoints);
foreach (LootItem lootItem in standardMonster.LootTable)
{
_currentMonster.LootTable.Add(lootItem);
}
cboWeapons.Enabled = true;
cboShield.Enabled = true;
cboPotions.Enabled = true;
btnUseWeapon.Enabled = true;
btnUsePotion.Enabled = true;
}
else
{
_currentMonster = null;
cboWeapons.Enabled = false;
cboShield.Enabled = false;
cboPotions.Enabled = false;
btnUseWeapon.Enabled = false;
btnUsePotion.Enabled = false;
}
}
else
{
_currentMonster = null;
cboWeapons.Enabled = false;
cboShield.Enabled = false;
cboPotions.Enabled = false;
btnUseWeapon.Enabled = false;
btnUsePotion.Enabled = false;
}
//Refresh player's stats
UpdatePlayerStats();
// Refresh player's inventory list
UpdateInventoryListInUI();
// Refresh player's quest list
UpdateQuestListInUI();
// Refresh player's weapons combobox
UpdateWeaponListInUI();
//Refresh player's shields combobox
UpdateShieldListInUI();
// Refresh player's potions combobox
UpdatePotionListInUI();
}
private void UpdatePlayerStats()
{
lblHitPoints.Text = _player.CurrentHitPoints.ToString();
lblGold.Text = _player.Gold.ToString();
lblExperience.Text = _player.ExperiencePoints.ToString();
lblLevel.Text = _player.Level.ToString();
}
private void UpdateInventoryListInUI()
{
dgvInventory.RowHeadersVisible = false;
dgvInventory.ColumnCount = 2;
dgvInventory.Columns[0].Name = "Name";
dgvInventory.Columns[0].Width = 197;
dgvInventory.Columns[1].Name = "Quantity";
dgvInventory.Rows.Clear();
foreach (InventoryItem inventoryItem in _player.Inventory)
{
if (inventoryItem.Quantity > 0)
{
dgvInventory.Rows.Add(new[] { inventoryItem.Details.Name, inventoryItem.Quantity.ToString() });
}
}
}
private void UpdateQuestListInUI()
{
dgvQuests.RowHeadersVisible = false;
dgvQuests.ColumnCount = 2;
dgvQuests.Columns[0].Name = "Name";
dgvQuests.Columns[0].Width = 197;
dgvQuests.Columns[1].Name = "Done?";
dgvQuests.Rows.Clear();
foreach (PlayerQuest playerQuest in _player.Quests)
{
dgvQuests.Rows.Add(new[] { playerQuest.Details.Name, playerQuest.IsCompleted.ToString() });
}
}
private void UpdateWeaponListInUI()
{
List<Weapon> weapons = new List<Weapon>();
foreach (InventoryItem inventoryItem in _player.Inventory)
{
if (inventoryItem.Details is Weapon)
{
if (inventoryItem.Quantity > 0)
{
weapons.Add((Weapon)inventoryItem.Details);
}
}
}
if (weapons.Count == 0)
{
// The player doesn't have any weapons, so hide the weapon combobox and "Use" button
cboWeapons.Enabled = false;
btnUseWeapon.Enabled = false;
}
else
{
cboWeapons.SelectedIndexChanged -= cboWeapons_SelectedIndexChanged;
cboWeapons.DataSource = weapons;
cboWeapons.SelectedIndexChanged += cboWeapons_SelectedIndexChanged;
cboWeapons.DisplayMember = "Name";
cboWeapons.ValueMember = "ID";
if (_player.CurrentWeapon != null)
{
cboWeapons.SelectedItem = _player.CurrentWeapon;
}
else
{
cboWeapons.SelectedIndex = 0;
}
}
}
private void UpdateShieldListInUI()
{
List<Shield> shields = new List<Shield>();
foreach (InventoryItem inventoryItem in _player.Inventory)
{
if (inventoryItem.Details is Shield)
{
if (inventoryItem.Quantity > 0)
{
shields.Add((Shield)inventoryItem.Details);
}
}
}
if (shields.Count == 0)
{
cboShield.Enabled = false;
}
else
{
cboShield.SelectedIndexChanged -= cboShield_SelectedIndexChanged;
cboShield.DataSource = shields;
cboShield.SelectedIndexChanged += cboShield_SelectedIndexChanged;
cboShield.DisplayMember = "Name";
cboShield.ValueMember = "ID";
if (_player.CurrentShield != null)
{
cboShield.SelectedItem = _player.CurrentShield;
}
else
{
cboShield.SelectedIndex = 0;
}
}
}
private void UpdatePotionListInUI()
{
List<Potion> potions = new List<Potion>();
foreach (InventoryItem inventoryItem in _player.Inventory)
{
if (inventoryItem.Details is Potion)
{
if (inventoryItem.Quantity > 0)
{
potions.Add((Potion)inventoryItem.Details);
}
}
}
if (potions.Count == 0)
{
// The player doesn't have any potions, so hide the potion combobox and "Use" button
cboPotions.Enabled = false;
btnUsePotion.Enabled = false;
}
else
{
cboPotions.SelectedIndexChanged -= cboPotions_SelectedIndexChanged;
cboPotions.DataSource = potions;
//cboPotions_SelectedIndexChanged += cboPotions_SelectedIndexChanged;
cboPotions.DisplayMember = "Name";
cboPotions.ValueMember = "ID";
if (_player.CurrentPotion != null)
{
cboPotions.SelectedItem = _player.CurrentPotion;
}
else
{
cboPotions.SelectedIndex = 0;
}
}
}
private void btnUseWeapon_Click(object sender, EventArgs e)
{
// Get the currently selected weapon from the cboWeapons ComboBox
Weapon currentWeapon = (Weapon)cboWeapons.SelectedItem;
Shield currentShield = (Shield)cboShield.SelectedItem;
// Determine the amount of damage to do to the monster
int damageToMonster = RandomNumberGenerator.NumberBetween(currentWeapon.MinimumDamage, currentWeapon.MaximumDamage);
// Apply the damage to the monster's CurrentHitPoints
_currentMonster.CurrentHitPoints -= damageToMonster;
// Display message
rtbMessages.Text += "You hit the " + _currentMonster.Name + " for " + damageToMonster.ToString() + " points." + Environment.NewLine;
// Check if the monster is dead
if (_currentMonster.CurrentHitPoints <= 0)
{
// Monster is dead
rtbMessages.Text += Environment.NewLine;
rtbMessages.Text += "You defeated the " + _currentMonster.Name + Environment.NewLine;
// Give player experience points for killing the monster
_player.AddExperiencePoints(_currentMonster.RewardExperiencePoints);
rtbMessages.Text += "You receive " + _currentMonster.RewardExperiencePoints.ToString() + " experience points" + Environment.NewLine;
// Give player gold for killing the monster
_player.Gold += _currentMonster.RewardGold;
rtbMessages.Text += "You receive " + _currentMonster.RewardGold.ToString() + " gold" + Environment.NewLine;
// Get random loot items from the monster
List<InventoryItem> lootedItems = new List<InventoryItem>();
// Add items to the lootedItems list, comparing a random number to the drop percentage
foreach (LootItem lootItem in _currentMonster.LootTable)
{
if (RandomNumberGenerator.NumberBetween(1, 100) <= lootItem.DropPercentage)
{
lootedItems.Add(new InventoryItem(lootItem.Details, 1));
}
}
// If no items were randomly selected, then add the default loot item(s).
if (lootedItems.Count == 0)
{
foreach (LootItem lootItem in _currentMonster.LootTable)
{
if (lootItem.IsDefaultItem)
{
lootedItems.Add(new InventoryItem(lootItem.Details, 1));
}
}
}
// Add the looted items to the player's inventory
foreach (InventoryItem inventoryItem in lootedItems)
{
_player.AddItemToInventory(inventoryItem.Details);
if (inventoryItem.Quantity == 1)
{
rtbMessages.Text += "You loot " + inventoryItem.Quantity.ToString() + " " + inventoryItem.Details.Name + Environment.NewLine;
}
else
{
rtbMessages.Text += "You loot " + inventoryItem.Quantity.ToString() + " " + inventoryItem.Details.NamePlural + Environment.NewLine;
}
}
// Refresh player information and inventory controls
lblHitPoints.Text = _player.CurrentHitPoints.ToString();
lblGold.Text = _player.Gold.ToString();
lblExperience.Text = _player.ExperiencePoints.ToString();
lblLevel.Text = _player.Level.ToString();
UpdateInventoryListInUI();
UpdateWeaponListInUI();
UpdateShieldListInUI();
UpdatePotionListInUI();
// Add a blank line to the messages box, just for appearance.
rtbMessages.Text += Environment.NewLine;
// Move player to current location (to heal player and create a new monster to fight)
MoveTo(_player.CurrentLocation);
}
else
{
// Monster is still alive
// Determine the amount of damage the monster does to the player
int damageDealt = RandomNumberGenerator.NumberBetween(0, _currentMonster.MaximumDamage);
int shieldReduction = (RandomNumberGenerator.NumberBetween(0, currentShield.DefensePoints));
int damageToPlayer = damageDealt - shieldReduction;
//If damage to player is negative, make it zero
if (damageToPlayer < 0)
{
damageToPlayer = 0;
}
// Display message
rtbMessages.Text += "The " + _currentMonster.Name + " did " + damageToPlayer.ToString() + " points of damage." + Environment.NewLine;
rtbMessages.Text += "Your shield reduced the damage by " + shieldReduction.ToString() + " points" + Environment.NewLine;
// Subtract damage from player
_player.CurrentHitPoints -= damageToPlayer;
// Refresh player data in UI
lblHitPoints.Text = _player.CurrentHitPoints.ToString();
if (_player.CurrentHitPoints <= 0)
{
// Display message
rtbMessages.Text += "The " + _currentMonster.Name + " killed you." + Environment.NewLine;
rtbMessages.Text += "You respawn at home." + Environment.NewLine + Environment.NewLine;
// Move player to "Home"
MoveTo(World.LocationByID(World.LOCATION_ID_HOME));
}
}
}
private void btnUsePotion_Click(object sender, EventArgs e)
{
// Get the currently selected potion from the combobox
Potion potions = (Potion)cboPotions.SelectedItem;
Weapon currentWeapon = (Weapon)cboWeapons.SelectedItem;
Shield currentShield = (Shield)cboShield.SelectedItem;
if (potions.ID == World.ITEM_ID_WEAK_HEALING_POTION)
{
// Add healing amount to the player's current hit points
_player.CurrentHitPoints = (_player.CurrentHitPoints + potions.AmountToHeal);
// CurrentHitPoints cannot exceed player's MaximumHitPoints
if (_player.CurrentHitPoints > _player.MaximumHitPoints)
{
_player.CurrentHitPoints = _player.MaximumHitPoints;
}
// Display message
rtbMessages.Text += "You drink a " + potions.Name + Environment.NewLine;
rtbMessages.Text += "It heals " + potions.AmountToHeal + " health." + Environment.NewLine;
}
else if (potions.ID == World.ITEM_ID_WEAK_STRENGTH_POTION)
{
//Add boost amount to currently selected weapons max damage
currentWeapon.MaximumDamage = currentWeapon.MaximumDamage + potions.AmountToBoostStr;
//Display message
rtbMessages.Text += "You drink a " + potions.Name + Environment.NewLine;
rtbMessages.Text += "It increases your current weapons maximum damage by " + potions.AmountToBoostStr + " points." + Environment.NewLine;
}
else if (potions.ID == World.ITEM_ID_WEAK_DEFENSE_POTION)
{
//Add boost amount to currently selected weapons max damage
currentShield.DefensePoints = currentShield.DefensePoints + potions.AmountToBoostDef;
//Display message
rtbMessages.Text += "You drink a " + potions.Name + Environment.NewLine;
rtbMessages.Text += "It increases your current shields defense by " + potions.AmountToBoostDef + " points." + Environment.NewLine;
}
// Remove the potion from the player's inventory
foreach (InventoryItem ii in _player.Inventory)
{
if (ii.Details.ID == potions.ID)
{
ii.Quantity--;
break;
}
}
// Monster gets their turn to attack
// Determine the amount of damage the monster does to the player
int damageDealt = RandomNumberGenerator.NumberBetween(0, _currentMonster.MaximumDamage);
int shieldReduction = (RandomNumberGenerator.NumberBetween(0, currentShield.DefensePoints));
int damageToPlayer = damageDealt - shieldReduction;
if (damageToPlayer < 0)
{
damageToPlayer = 0;
}
// Display message
rtbMessages.Text += "The " + _currentMonster.Name + " did " + damageToPlayer.ToString() + " points of damage." + Environment.NewLine;
rtbMessages.Text += "Your shield reduced the damage by " + shieldReduction.ToString() + " points" + Environment.NewLine;
// Subtract damage from player
_player.CurrentHitPoints -= damageToPlayer;
if (_player.CurrentHitPoints <= 0)
{
// Display message
rtbMessages.Text += "The " + _currentMonster.Name + " killed you." + Environment.NewLine;
rtbMessages.Text += "You respawn at home." + Environment.NewLine;
// Move player to "Home"
MoveTo(World.LocationByID(World.LOCATION_ID_HOME));
}
// Refresh player data in UI
lblHitPoints.Text = _player.CurrentHitPoints.ToString();
UpdateInventoryListInUI();
UpdatePotionListInUI();
}
private void rtbLocation_TextChanged(object sender, EventArgs e)
{
rtbLocation.SelectionStart = rtbLocation.Text.Length;
rtbLocation.ScrollToCaret();
}
private void rtbMessages_TextChanged(object sender, EventArgs e)
{
rtbMessages.SelectionStart = rtbMessages.Text.Length;
rtbMessages.ScrollToCaret();
}
private void btnHelp_Click(object sender, EventArgs e)
{
HelpScreen help = new HelpScreen();
help.ShowDialog();
}
private void Adventure_FormClosing(object sender, FormClosingEventArgs e)
{
File.WriteAllText(PLAYER_DATA_FILE_NAME, _player.ToXmlString());
}
private void cboWeapons_SelectedIndexChanged(object sender, EventArgs e)
{
_player.CurrentWeapon = (Weapon)cboWeapons.SelectedItem;
}
private void cboShield_SelectedIndexChanged(object sender, EventArgs e)
{
_player.CurrentShield = (Shield)cboShield.SelectedItem;
}
private void cboPotions_SelectedIndexChanged(object sender, EventArgs e)
{
_player.CurrentPotion = (Potion)cboPotions.SelectedItem;
}
private void btnMap_Click(object sender, EventArgs e)
{
Map map = new Map();
map.Show();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Engine
{
public class Player : LivingCreature
{
public string PlayerName { get; set; }
public int Gold { get; set; }
public int ExperiencePoints { get; private set; }
public int Level
{
get { return (Convert.ToInt32((0.1018 * Math.Pow(ExperiencePoints, 0.5291)) + 1)); }
}
public int Defense { get; set; }
public Location CurrentLocation { get; set; }
public Weapon CurrentWeapon { get; set; }
public Shield CurrentShield { get; set; }
public Potion CurrentPotion { get; set; }
public List<InventoryItem> Inventory { get; set; }
public List<PlayerQuest> Quests { get; set; }
private Player(string playerName, int currentHitPoints, int maximumHitPoints, int gold, int experiencePoints) : base(currentHitPoints, maximumHitPoints)
{
PlayerName = playerName;
Gold = gold;
ExperiencePoints = experiencePoints;
Inventory = new List<InventoryItem>();
Quests = new List<PlayerQuest>();
}
public static Player CreateDefaultPlayer()
{
Player player = new Player("", 10, 10, 0, 0);
player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_RUSTY_SWORD), 1));
player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_RUSTY_SHIELD), 1));
//Added items for testing purposes
//player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_STEEL_SWORD), 1));
//player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_STEEL_SHIELD), 1));
//player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_THE_SWORD_OF_LIGHT), 1));
//player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_TIME_FRAGMENT_1), 1));
//player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_TIME_FRAGMENT_2), 1));
//player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_TIME_FRAGMENT_3), 1));
//player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_TIME_FRAGMENT_4), 1));
//player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_TIME_FRAGMENT_5), 1));
//player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_TIME_FRAGMENT_7), 1));
//player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_TIME_FRAGMENT_6), 1));
//player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_TIME_FRAGMENT_8), 1));
player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_WEAK_STRENGTH_POTION), 10));
player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_WEAK_HEALING_POTION), 10));
player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_WEAK_DEFENSE_POTION), 10));
player.CurrentLocation = World.LocationByID(World.LOCATION_ID_HOME);
return player;
}
public static Player CreatePlayerFromXmlString(string xmlPlayerData)
{
try
{
XmlDocument playerData = new XmlDocument();
playerData.LoadXml(xmlPlayerData);
string playerName = playerData.SelectSingleNode("/Player/Stats/PlayerName").InnerText;
int currentHitPoints = Convert.ToInt32(playerData.SelectSingleNode("/Player/Stats/CurrentHitPoints").InnerText);
int maximumHitPoints = Convert.ToInt32(playerData.SelectSingleNode("/Player/Stats/MaximumHitPoints").InnerText);
int gold = Convert.ToInt32(playerData.SelectSingleNode("/Player/Stats/Gold").InnerText);
int experiencePoints = Convert.ToInt32(playerData.SelectSingleNode("/Player/Stats/ExperiencePoints").InnerText);
Player player = new Player(playerName, currentHitPoints, maximumHitPoints, gold, experiencePoints);
int currentLocationID = Convert.ToInt32(playerData.SelectSingleNode("/Player/Stats/CurrentLocation").InnerText);
player.CurrentLocation = World.LocationByID(currentLocationID);
if (playerData.SelectSingleNode("/Player/Stats/CurrentWeapon") != null)
{
int currentWeaponID = Convert.ToInt32(playerData.SelectSingleNode("Player/Stats/CurrentWeapon").InnerText);
player.CurrentWeapon = (Weapon)World.ItemByID(currentWeaponID);
}
if (playerData.SelectSingleNode("/Player/Stats/CurrentShield") != null)
{
int currentShieldID = Convert.ToInt32(playerData.SelectSingleNode("Player/Stats/CurrentShield").InnerText);
player.CurrentShield = (Shield)World.ItemByID(currentShieldID);
}
if (playerData.SelectSingleNode("/Player/Stats/CurrentPotion") != null)
{
int currentPotionID = Convert.ToInt32(playerData.SelectSingleNode("Player/Stats/CurrentPotion").InnerText);
player.CurrentPotion = (Potion)World.ItemByID(currentPotionID);
}
foreach (XmlNode node in playerData.SelectNodes("/Player/InventoryItems/InventoryItem"))
{
int id = Convert.ToInt32(node.Attributes["ID"].Value);
int quantity = Convert.ToInt32(node.Attributes["Quantity"].Value);
for (int i = 0; i < quantity; i++)
{
player.AddItemToInventory(World.ItemByID(id));
}
}
foreach (XmlNode node in playerData.SelectNodes("/Player/PlayerQuests/PlayerQuest"))
{
int id = Convert.ToInt32(node.Attributes["ID"].Value);
bool isCompleted = Convert.ToBoolean(node.Attributes["IsCompleted"].Value);
PlayerQuest playerQuest = new PlayerQuest(World.QuestByID(id));
playerQuest.IsCompleted = isCompleted;
player.Quests.Add(playerQuest);
}
return player;
}
catch
{
// If there was an error with the XML data, return a default player object
return Player.CreateDefaultPlayer();
}
}
public void AddExperiencePoints(int experiencePointsToAdd)
{
ExperiencePoints += experiencePointsToAdd;
MaximumHitPoints = (Level * 10);
}
public bool HasRequiredItemToEnterThisLocation(Location location)
{
if (location.ItemRequiredToEnter == null)
{
// There is no required item for this location, so return "true"
return true;
}
// See if the player has the required item in their inventory
foreach (InventoryItem ii in Inventory)
{
if (ii.Details.ID == location.ItemRequiredToEnter.ID)
{
// We found the required item, so return "true"
return true;
}
}
// We didn't find the required item in their inventory, so return "false"
return false;
}
public bool HasThisQuest(Quest quest)
{
foreach (PlayerQuest playerQuest in Quests)
{
if (playerQuest.Details.ID == quest.ID)
{
return true;
}
}
return false;
}
public bool CompletedThisQuest(Quest quest)
{
foreach (PlayerQuest playerQuest in Quests)
{
if (playerQuest.Details.ID == quest.ID)
{
return playerQuest.IsCompleted;
}
}
return false;
}
public bool HasAllQuestCompletionItems(Quest quest)
{
// See if the player has all the items needed to complete the quest here
foreach (QuestCompletionItem qci in quest.QuestCompletionItems)
{
bool foundItemInPlayersInventory = false;
// Check each item in the player's inventory, to see if they have it, and enough of it
foreach (InventoryItem ii in Inventory)
{
if (ii.Details.ID == qci.Details.ID) // The player has the item in their inventory
{
foundItemInPlayersInventory = true;
if (ii.Quantity < qci.Quantity) // The player does not have enough of this item to complete the quest
{
return false;
}
}
}
// The player does not have any of this quest completion item in their inventory
if (!foundItemInPlayersInventory)
{
return false;
}
}
// If we got here, then the player must have all the required items, and enough of them, to complete the quest.
return true;
}
public void RemoveQuestCompletionItems(Quest quest)
{
foreach (QuestCompletionItem qci in quest.QuestCompletionItems)
{
foreach (InventoryItem ii in Inventory)
{
if (ii.Details.ID == qci.Details.ID)
{
// Subtract the quantity from the player's inventory that was needed to complete the quest
ii.Quantity -= qci.Quantity;
break;
}
}
}
}
public void AddItemToInventory(Item itemToAdd)
{
foreach (InventoryItem ii in Inventory)
{
if (ii.Details.ID == itemToAdd.ID)
{
// They have the item in their inventory, so increase the quantity by one
ii.Quantity++;
return; // We added the item, and are done, so get out of this function
}
}
// They didn't have the item, so add it to their inventory, with a quantity of 1
Inventory.Add(new InventoryItem(itemToAdd, 1));
}
public void MarkQuestCompleted(Quest quest)
{
// Find the quest in the player's quest list
foreach (PlayerQuest pq in Quests)
{
if (pq.Details.ID == quest.ID)
{
// Mark it as completed
pq.IsCompleted = true;
return; // We found the quest, and marked it complete, so get out of this function
}
}
}
public string ToXmlString()
{
XmlDocument playerData = new XmlDocument();
// Create the top-level XML node
XmlNode player = playerData.CreateElement("Player");
playerData.AppendChild(player);
// Create the "Stats" child node to hold the other player statistics nodes
XmlNode stats = playerData.CreateElement("Stats");
player.AppendChild(stats);
// Create the child nodes for the "Stats" node
XmlNode playerName = playerData.CreateElement("PlayerName");
playerName.AppendChild(playerData.CreateTextNode(this.PlayerName.ToString()));
stats.AppendChild(playerName);
XmlNode currentHitPoints = playerData.CreateElement("CurrentHitPoints");
currentHitPoints.AppendChild(playerData.CreateTextNode(this.CurrentHitPoints.ToString()));
stats.AppendChild(currentHitPoints);
XmlNode maximumHitPoints = playerData.CreateElement("MaximumHitPoints");
maximumHitPoints.AppendChild(playerData.CreateTextNode(this.MaximumHitPoints.ToString()));
stats.AppendChild(maximumHitPoints);
XmlNode gold = playerData.CreateElement("Gold");
gold.AppendChild(playerData.CreateTextNode(this.Gold.ToString()));
stats.AppendChild(gold);
XmlNode experiencePoints = playerData.CreateElement("ExperiencePoints");
experiencePoints.AppendChild(playerData.CreateTextNode(this.ExperiencePoints.ToString()));
stats.AppendChild(experiencePoints);
XmlNode currentLocation = playerData.CreateElement("CurrentLocation");
currentLocation.AppendChild(playerData.CreateTextNode(this.CurrentLocation.ID.ToString()));
stats.AppendChild(currentLocation);
if (CurrentWeapon != null)
{
XmlNode currentWeapon = playerData.CreateElement("CurrentWeapon");
currentWeapon.AppendChild(playerData.CreateTextNode(this.CurrentWeapon.ID.ToString()));
stats.AppendChild(currentWeapon);
}
if (CurrentShield != null)
{
XmlNode currentShield = playerData.CreateElement("CurrentShield");
currentShield.AppendChild(playerData.CreateTextNode(this.CurrentShield.ID.ToString()));
stats.AppendChild(currentShield);
}
if (CurrentPotion != null)
{
XmlNode currentPotion = playerData.CreateElement("CurrentPotion");
currentPotion.AppendChild(playerData.CreateTextNode(this.CurrentPotion.ID.ToString()));
stats.AppendChild(currentPotion);
}
// Create the "InventoryItems" child node to hold each InventoryItem node
XmlNode inventoryItems = playerData.CreateElement("InventoryItems");
player.AppendChild(inventoryItems);
// Create an "InventoryItem" node for each item in the player's inventory
foreach(InventoryItem item in this.Inventory)
{
XmlNode inventoryItem = playerData.CreateElement("InventoryItem");
XmlAttribute idAttribute = playerData.CreateAttribute("ID");
idAttribute.Value = item.Details.ID.ToString();
inventoryItem.Attributes.Append(idAttribute);
XmlAttribute quantityAttribute = playerData.CreateAttribute("Quantity");
quantityAttribute.Value = item.Quantity.ToString();
inventoryItem.Attributes.Append(quantityAttribute);
inventoryItems.AppendChild(inventoryItem);
}
// Create the "PlayerQuests" child node to hold each PlayerQuest node
XmlNode playerQuests = playerData.CreateElement("PlayerQuests");
player.AppendChild(playerQuests);
// Create a "PlayerQuest" node for each quest the player has acquired
foreach(PlayerQuest quest in this.Quests)
{
XmlNode playerQuest = playerData.CreateElement("PlayerQuest");
XmlAttribute idAttribute = playerData.CreateAttribute("ID");
idAttribute.Value = quest.Details.ID.ToString();
playerQuest.Attributes.Append(idAttribute);
XmlAttribute isCompletedAttribute = playerData.CreateAttribute("IsCompleted");
isCompletedAttribute.Value = quest.IsCompleted.ToString();
playerQuest.Attributes.Append(isCompletedAttribute);
playerQuests.AppendChild(playerQuest);
}
return playerData.InnerXml; // The XML document, as a string, so we can save the data to disk
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment