Skip to content

Instantly share code, notes, and snippets.

@linxlad
Last active June 6, 2016 15:27
Show Gist options
  • Save linxlad/3f7f3f78b4a8cc64575a4fe1c8d50225 to your computer and use it in GitHub Desktop.
Save linxlad/3f7f3f78b4a8cc64575a4fe1c8d50225 to your computer and use it in GitHub Desktop.
Game logic with C# 7.0 and pattern matching.
/**
* In functional programming, data types do not include operations. Instead, each function implements a single operation
* for all the data types. This makes it much easier to add a new operation (just define and implement a new function),
* but much more difficult to add a new data type (modify all existing functions accordingly). While this is already
* possible in C#, it is much more verbose than it could be.
*/
interface IEnemy
{
int Health { get; set; }
}
interface IWeapon
{
int Damage { get; set; }
}
class Sword : IWeapon
{
public int Damage { get; set; }
public int Durability { get; set; }
}
class Bow : IWeapon
{
public int Damage { get; set; }
public int Arrows { get; set; }
}
static class WeaponOperations
{
static void Attack(this IWeapon weapon, IEnemy enemy)
{
switch (weapon)
{
case Sword sword when sword.Durability > 0:
enemy.Health -= sword.Damage;
sword.Durability--;
break;
case Bow bow when bow.Arrows > 0:
enemy.Health -= bow.Damage;
bow.Arrows--;
break;
}
}
static void Repair(this IWeapon weapon)
{
if (weapon is Sword)
{
var sword = weapon as Sword;
sword.Durability += 100;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment