<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-5965588490067077786</id><updated>2025-06-13T06:41:08.435-07:00</updated><category term="C#"/><category term="Tutorials"/><category term="Design Patterns"/><category term="XNA"/><category term="Code Samples"/><category term="C++"/><category term="Content Pipeline"/><category term="Game Physics"/><title type='text'>Program Your Face Off</title><subtitle type='html'>Because it&#39;s fun.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>20</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-7249298267124338177</id><published>2014-10-20T06:17:00.001-07:00</published><updated>2014-10-20T06:21:25.497-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C++"/><category scheme="http://www.blogger.com/atom/ns#" term="Code Samples"/><title type='text'>Let&#39;s write a c++ math libraryI (part 2)</title><content type='html'>&lt;br /&gt;
&lt;a href=&quot;http://programyourfaceoff.blogspot.com/2014/10/lets-write-c-math-library.html&quot; target=&quot;_blank&quot;&gt;Last time&lt;/a&gt;&amp;nbsp;we made a class to encapsulate a 2D vector with floating point entries. &amp;nbsp;In this post we&#39;ll finish up with the 3 and 4 dimensional vector classes. &amp;nbsp;None of these will be particularly useful however, until we make a matrix class that can transform these vectors.&lt;br /&gt;
&lt;div&gt;
So let&#39;s get started.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
vector3f.h&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;pre class=&quot;brush:c++&quot; name=&quot;code&quot;&gt;#ifndef _VECTOR3F_H_
#define _VECTOR3F_H_

class vector3f
{
private:
    float elements[3];
public:

    static const int SIZE;

    vector3f(float x = 0.0f, float y = 0.0f, float z = 0.0f);

    vector3f(const vector3f&amp;amp; other);

    vector3f normal() const;

    void normalize();

    float length() const;

    static float dot(const vector3f&amp;amp; vector1, const vector3f&amp;amp; vector2);

    static vector3f cross(const vector3f&amp;amp; vector1, const vector3f&amp;amp; vector2);

    vector3f&amp;amp; operator=(const vector3f&amp;amp; other);

    vector3f operator-() const;

    vector3f operator*(float scalar) const;

    vector3f operator/(float scalar) const;

    friend vector3f operator+(const vector3f&amp;amp; vector1, const vector3f&amp;amp; vector2);

    friend vector3f operator-(const vector3f&amp;amp; vector1, const vector3f&amp;amp; vector2);

    friend vector3f operator*(float scalar, const vector3f&amp;amp; vector);

    friend bool operator==(const vector3f&amp;amp; vector1, const vector3f&amp;amp; vector2);

    friend bool operator!=(const vector3f&amp;amp; vector1, const vector3f&amp;amp; vector2);

    float&amp;amp; operator[](int index);
};

#endif
&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
You&#39;ll notice we have a function that the vector2f class does not: &amp;nbsp;cross&lt;br /&gt;
This is the&amp;nbsp;&lt;a href=&quot;http://en.wikipedia.org/wiki/Cross_product&quot; target=&quot;_blank&quot;&gt;cross product&lt;/a&gt;&amp;nbsp;of two 3D vectors which produces a vector perpendicular to both input vectors in a direction determined by the&amp;nbsp;&lt;a href=&quot;http://en.wikipedia.org/wiki/Right-hand_rule&quot; target=&quot;_blank&quot;&gt;right hand rule&lt;/a&gt;. &amp;nbsp;It is only defined for 3 dimensional vectors.&lt;br /&gt;
&lt;br /&gt;
vector3f.cpp&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c++&quot; name=&quot;code&quot;&gt;#include &quot;vector3f.h&quot;
#include &amp;lt;cmath&amp;gt;

const int vector3f::SIZE = 3;

vector3f::vector3f(float x, float y, float z)
{
    elements[0] = x;
    elements[1] = y;
    elements[2] = z;
}

vector3f::vector3f(const vector3f&amp;amp; other)
{
    elements[0] = other.elements[0];
    elements[1] = other.elements[1];
    elements[2] = other.elements[2];
}

vector3f vector3f::normal() const
{
    float l = length();
    return vector3f(elements[0] / l, elements[1] / l, elements[2] / l);
}

void vector3f::normalize()
{
    float l = length();
    elements[0] /= l;
    elements[1] /= l;
    elements[2] /= l;
}

float vector3f::length() const
{
    return std::sqrt(elements[0] * elements[0] + elements[1] * elements[1] + elements[2] * elements[2]);
}

float vector3f::dot(const vector3f&amp;amp; vector1, const vector3f&amp;amp; vector2)
{
    return vector1.elements[0] * vector2.elements[0] + vector1.elements[1] * vector2.elements[1] +
        vector1.elements[2] * vector2.elements[2];
}

vector3f vector3f::cross(const vector3f&amp;amp; vector1, const vector3f&amp;amp; vector2)
{
    return vector3f(vector1.elements[1] * vector2.elements[2] - vector1.elements[2] * vector2.elements[0],
        vector1.elements[2] * vector2.elements[0] - vector1.elements[0] * vector2.elements[2],
        vector1.elements[0] * vector2.elements[1] - vector1.elements[1] * vector2.elements[0]);
}

vector3f&amp;amp; vector3f::operator=(const vector3f&amp;amp; other)
{
    if (this != &amp;amp;other)
    {
        elements[0] = other.elements[0];
        elements[1] = other.elements[1];
        elements[2] = other.elements[2];
    }
        return *this;
}

vector3f vector3f::operator-() const
{
    return vector3f(-elements[0], -elements[1], -elements[2]);
}

vector3f vector3f::operator*(float scalar) const
{
    return vector3f(scalar * elements[0], scalar * elements[1], scalar * elements[2]);
}

vector3f vector3f::operator/(float scalar) const
{
    return vector3f(elements[0] / scalar, elements[1] / scalar, elements[2] / scalar);
}

vector3f operator+(const vector3f&amp;amp; vector1, const vector3f&amp;amp; vector2)
{
    return vector3f(vector1.elements[0] + vector2.elements[0], vector1.elements[1] + vector2.elements[1],
        vector1.elements[2] * vector2.elements[2]);
}

vector3f operator-(const vector3f&amp;amp; vector1, const vector3f&amp;amp; vector2)
{
    return vector3f(vector1.elements[0] - vector2.elements[0], vector1.elements[1] - vector2.elements[1],
        vector1.elements[2] - vector2.elements[2]);
}

vector3f operator*(float scalar, const vector3f&amp;amp; vector)
{
    return vector3f(scalar * vector.elements[0], scalar * vector.elements[1],
        scalar * vector.elements[2]);
}

bool operator==(const vector3f&amp;amp; vector1, const vector3f&amp;amp; vector2)
{
    return ((vector1.elements[0] == vector2.elements[0]) &amp;amp;&amp;amp; (vector1.elements[1] == vector2.elements[1]) &amp;amp;&amp;amp;
        vector1.elements[2] == vector2.elements[2]);
}

bool operator!=(const vector3f&amp;amp; vector1, const vector3f&amp;amp; vector2)
{
    return ((vector1.elements[0] != vector2.elements[0]) || (vector1.elements[1] != vector2.elements[1]) ||
        vector1.elements[2] != vector2.elements[2]);
}

float&amp;amp; vector3f::operator[](int index)
{
    return elements[index];
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
vector4f.h
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c++&quot; name=&quot;code&quot;&gt;#ifndef _VECTOR4F_H_
#define _VECTOR4F_H_

class KOGAPI vector4f
{
private:
    float elements[4];
 
public:

    static const int SIZE;

    vector4f(float x = 0.0f, float y = 0.0f, float z = 0.0f, float w = 0.0f);

    vector4f(const vector4f&amp;amp; other);

    vector4f normal() const;

    void normalize();

    float length() const;

    static float dot(const vector4f&amp;amp; vector1, const vector4f&amp;amp; vector2);

    vector4f&amp;amp; operator=(const vector4f&amp;amp; other);

    vector4f operator-() const;

    vector4f operator*(float scalar) const;

    vector4f operator/(float scalar) const;

    friend vector4f operator+(const vector4f&amp;amp; vector1, const vector4f&amp;amp; vector2);

    friend vector4f operator-(const vector4f&amp;amp; vector1, const vector4f&amp;amp; vector2);

    friend vector4f operator*(float scalar, const vector4f&amp;amp; vector);

    friend bool operator==(const vector4f&amp;amp; vector1, const vector4f&amp;amp; vector2);

    friend bool operator!=(const vector4f&amp;amp; vector1, const vector4f&amp;amp; vector2);

    float&amp;amp; operator[](int index);
};

#endif
&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
vector4f.cpp
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c++&quot; name=&quot;code&quot;&gt;#include &quot;vector4f.h&quot;
#include &amp;lt;cmath&amp;gt;

vector4f::vector4f(float x, float y, float z, float w)
{
    elements[0] = x;
    elements[1] = y;
    elements[2] = z;
    elements[3] = w;
}

vector4f::vector4f(const vector4f&amp;amp; other)
{
    elements[0] = other.elements[0];
    elements[1] = other.elements[1];
    elements[2] = other.elements[2];
    elements[3] = other.elements[3];
}

vector4f vector4f::normal() const
{
    float l = length();
    return vector4f(elements[0] / l, elements[1] / l, elements[2] / l, elements[3] / l);
}

void vector4f::normalize()
{
    float l = length();
    elements[0] /= l;
    elements[1] /= l;
    elements[2] /= l;
    elements[3] /= l;
}

float vector4f::length() const
{
    return std::sqrt(elements[0] * elements[0] + elements[1] * elements[1] + elements[2] * elements[2] +
        elements[3] * elements[3]);
}

float vector4f::dot(const vector4f&amp;amp; vector1, const vector4f&amp;amp; vector2)
{
    return vector1.elements[0] * vector2.elements[0] + vector1.elements[1] * vector2.elements[1] +
        vector1.elements[2] * vector2.elements[2] + vector1.elements[3] * vector2.elements[3];
}

vector4f&amp;amp; vector4f::operator=(const vector4f&amp;amp; other)
{
    if (this != &amp;amp;other)
    {
        elements[0] = other.elements[0];
        elements[1] = other.elements[1];
        elements[2] = other.elements[2];
        elements[3] = other.elements[3];
    }
    return *this;
}

vector4f vector4f::operator-() const
{
    return vector4f(-elements[0], -elements[1], -elements[2], -elements[3]);
}

vector4f vector4f::operator*(float scalar) const
{
    return vector4f(scalar * elements[0], scalar * elements[1], scalar * elements[2],
        scalar * elements[3]);
}

vector4f vector4f::operator/(float scalar) const
{
    return vector4f(elements[0] / scalar, elements[1] / scalar, elements[2] / scalar,
        elements[3] / scalar);
}

vector4f operator+(const vector4f&amp;amp; vector1, const vector4f&amp;amp; vector2)
{
    return vector4f(vector1.elements[0] + vector2.elements[0], vector1.elements[1] + vector2.elements[1],
        vector1.elements[2] * vector2.elements[2], vector1.elements[3] + vector2.elements[3]);
}

vector4f operator-(const vector4f&amp;amp; vector1, const vector4f&amp;amp; vector2)
{
    return vector4f(vector1.elements[0] - vector2.elements[0], vector1.elements[1] - vector2.elements[1],
        vector1.elements[2] - vector2.elements[2], vector1.elements[3] - vector2.elements[3]);
}

vector4f operator*(float scalar, const vector4f&amp;amp; vector)
{
    return vector4f(scalar * vector.elements[0], scalar * vector.elements[1],
        scalar * vector.elements[2], scalar * vector.elements[3]);
}

bool operator==(const vector4f&amp;amp; vector1, const vector4f&amp;amp; vector2)
{
    return ((vector1.elements[0] == vector2.elements[0]) &amp;amp;&amp;amp; (vector1.elements[1] == vector2.elements[1]) &amp;amp;&amp;amp;
        vector1.elements[2] == vector2.elements[2] &amp;amp;&amp;amp; vector1.elements[3] == vector2.elements[3]);
}

bool operator!=(const vector4f&amp;amp; vector1, const vector4f&amp;amp; vector2)
{
    return ((vector1.elements[0] != vector2.elements[0]) || (vector1.elements[1] != vector2.elements[1]) ||
        (vector1.elements[2] != vector2.elements[2]) || (vector1.elements[3] != vector2.elements[3]));
}

float&amp;amp; vector4f::operator[](int index)
{
    return elements[index];
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
That&#39;s it for now. &amp;nbsp;Next post we&#39;ll set up the matrix and quaternion class.&lt;br /&gt;
Questions are always welcome and if you have an idea for a tutorial or series you&#39;d like to see feel free to comment it!.</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/7249298267124338177/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2014/10/lets-write-c-math-libraryi-part-1.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/7249298267124338177'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/7249298267124338177'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2014/10/lets-write-c-math-libraryi-part-1.html' title='Let&#39;s write a c++ math libraryI (part 2)'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-3431509349234069523</id><published>2014-10-17T06:30:00.003-07:00</published><updated>2014-10-20T06:19:03.963-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C++"/><category scheme="http://www.blogger.com/atom/ns#" term="Code Samples"/><title type='text'>Let&#39;s write a c++ math library!</title><content type='html'>Wow, it&#39;s been a long time since I&#39;ve updated this blog.  So I&#39;ve really been getting into C++ and OpenGL lately.&lt;br /&gt;
Why C++?&lt;br /&gt;
Well,&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;It&#39;s been around forever&lt;/li&gt;
&lt;li&gt;It&#39;s easier to write cross platform applications&lt;/li&gt;
&lt;li&gt;Unlike C it&#39;s object oriented out of the box&lt;/li&gt;
&lt;li&gt;Pointers are fun&lt;/li&gt;
&lt;li&gt;I like it. &amp;nbsp;Whatever, I know someone who puts garlic on their peanut butter sandwiches, go bother him.&lt;/li&gt;
&lt;/ul&gt;
If you don&#39;t know C++ there&#39;s &lt;a href=&quot;http://www.reddit.com/r/learnprogramming/search?q=c%2B%2B&amp;amp;restrict_sr=on&amp;amp;sort=relevance&amp;amp;t=all&quot; target=&quot;_blank&quot;&gt;endless resources&lt;/a&gt; out there. &amp;nbsp;So I&#39;d like to start by writing a math library for rendering graphics. &amp;nbsp;This means linear algebra. &amp;nbsp;Go beef up on your linear algebra if you don&#39;t know much about it. &amp;nbsp;Here&#39;s&amp;nbsp;&lt;a href=&quot;https://www.youtube.com/watch?v=ZK3O402wf1c&amp;amp;list=PLE7DDD91010BC51F8&quot; target=&quot;_blank&quot;&gt;an MIT course&lt;/a&gt;&amp;nbsp;on the subject. &amp;nbsp;Have fun.&lt;br /&gt;
&lt;ul&gt;
&lt;/ul&gt;
&lt;div&gt;
Let&#39;s get started! &amp;nbsp;First we&#39;ll need a vector class. &amp;nbsp;A few actually so let&#39;s start with a 2D vector with floating point elements.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;br /&gt;
vector2f.h
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c++&quot; name=&quot;code&quot;&gt;#ifndef _VECTOR2F_H_
#define _VECTOR2F_H_

class vector2f
{
private:
    float elements[2];

public:
    vector2f(float x = 0.0f, float y = 0.0f);

    vector2f(const vector2f&amp;amp; other);
    
    float length() const;

    static float dot(const vector2f&amp;amp; vector1, const vector2f&amp;amp; vector2);

    vector2f operator-();
    
    vector2f operator*(float scalar);

    friend operator*(float scalar, const vector2f&amp;amp; vector);

    friend operator/(const vector2f&amp;amp; vector, float scalar);

    friend operator+(const vector2f&amp;amp; vector1, const vector2f&amp;amp; vector2);

    friend operator-(const vector2f&amp;amp; vector1, const vector2f&amp;amp; vector2);

    vector2f&amp;amp; operator=(const vector2f&amp;amp; other);

    float&amp;amp; operator[](int index);

    friend bool operator==(const vector2f&amp;amp; vector1, const vector2f&amp;amp; vector2);

    friend bool operator!=(const vector2f&amp;amp; vector1, const vector2f&amp;amp; vector2);
};

#endif
&lt;/pre&gt;
&lt;br /&gt;
That&#39;s good for now but we&#39;ll probably add more to this class later. &amp;nbsp;Let&#39;s take a look at the source code.&lt;br /&gt;
&lt;br /&gt;
vector2f.cpp&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c++&quot; name=&quot;code&quot;&gt;#include &quot;vector2f.h&quot;
#include &amp;lt;cmath&amp;gt;

vector2f::vector2f(float x, float y)
{
 elements[0] = x;
 elements[1] = y;
}

vector2f::vector2f(const vector2f&amp;amp; other)
{
    elements[0] = other.elements[0];
    elements[1] = other.elements[1];
}

float vector2f::length() const
{
    return std::sqrt(elements[0] * elements[0] + elements[1] * elements[1]);
}

float vector2f::dot(const vector2f&amp;amp; vector1, const vector2f&amp;amp; vector2)
{
    return vector1.elements[0] * vector2.elements[0] + vector1.elements[1] * vector2.elements[1];
}

vector2f vector2f::operator-()
{
    return vector2f(-elements[0], -elements[1]);
}

vector2f vector2f::operator*(float scalar)
{
    return vector2f(scalar * elements[0], scalar * elements[1]);
}

vector2f operator*(float scalar, const vector2f&amp;amp; vector)
{
    return vector2f(scalar * vector.elements[0], scalar * vector.elements[1]);
}

vector2f operator/(const vector2f&amp;amp; vector, float scalar)
{
    return vector2f(vector.elements[0] / scalar, vector.elements[1] / scalar);
}

vector2f operator+(const vector2f&amp;amp; vector1, const vector2f&amp;amp; vector2)
{
    return vector2f(vector1.elements[0] + vector2.elements[0], vector1.elements[1] + vector2.elements[1]);
}

vector2f operator-(const vector2f&amp;amp; vector1, const vector2f&amp;amp; vector2)
{
    return vector2f(vector1.elements[0] - vector2.elements[0], vector1.elements[1] - vector2.elements[1]);
}

vector2f&amp;amp; vector2f::operator=(const vector2f&amp;amp; other)
{
    if (this != &amp;amp;other)
    {
     elements[0] = other.elements[0];
     elements[1] = other.elements[1];
    }
    return *this;
}

float&amp;amp; vector2f::operator[](int index)
{
     //unsafe!  TODO:  add bounds checking
     return elements[index];
}

bool operator==(const vector2f&amp;amp; vector1, const vector2f&amp;amp; vector2)
{
    return (vector1.elements[0] == vector2.elements[0] &amp;amp;&amp;amp;
        vector1.elements[1] == vector2.elements[1]);
}

bool operator!=(const vector2f&amp;amp; vector1, const vector2f&amp;amp; vector2)
{
    return (vector1.elements[0] != vector2.elements[0] ||
        vector1.elements[1] != vector2.elements[1]);
}
&lt;/pre&gt;
&lt;br /&gt;
Hey, alright! &amp;nbsp;That should be pretty good for now. &amp;nbsp;This is pretty basic stuff but I thought someone might benefit from seeing how it&#39;s done. &amp;nbsp;Later we&#39;ll add matrix classes and even a quaternion class for rotation.&lt;br /&gt;
That&#39;s it for now, though!&lt;br /&gt;
&lt;br /&gt;
next: &amp;nbsp;&lt;a href=&quot;http://programyourfaceoff.blogspot.com/2014/10/lets-write-c-math-libraryi-part-1.html&quot; target=&quot;_blank&quot;&gt;part 2&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/3431509349234069523/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2014/10/lets-write-c-math-library.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/3431509349234069523'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/3431509349234069523'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2014/10/lets-write-c-math-library.html' title='Let&#39;s write a c++ math library!'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-4267506962948078816</id><published>2012-01-17T12:33:00.000-08:00</published><updated>2012-04-18T08:21:26.582-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Code Samples"/><category scheme="http://www.blogger.com/atom/ns#" term="Game Physics"/><category scheme="http://www.blogger.com/atom/ns#" term="XNA"/><title type='text'>The GJK Algorithm</title><content type='html'>This code sample uses the &lt;A href=&quot;http://en.wikipedia.org/wiki/Gilbert%E2%80%93Johnson%E2%80%93Keerthi_distance_algorithm&quot;&gt;GJK Algorithm&lt;/a&gt; to determine if two convex regions in 3-space are intersecting.&lt;/br&gt;
There&#39;s a good tutorial on how this algorithm actually works &lt;a href=&quot;http://mollyrocket.com/849&quot;&gt;here&lt;/a&gt; and another one &lt;a href=&quot;http://www.codezealot.org/archives/88&quot;&gt;here&lt;/a&gt;.  This is my implementation in c#.&lt;/br&gt;
One can extend this to handle any convex shape at all as long as it has a function to determine the furthest point in the shape along a give direction, ie. if one were to walk along a line determined by a direction, starting &quot;behind&quot; the shape, determine the last point of the shape that you&#39;ll pass.  This basically boils down to finding the shape&#39;s position that has the largest dot product with the direction.&lt;/br&gt;
While this can be tricky, GJK can handle any convex shape that implements this function making it very flexible.  It&#39;s also faster than many other methods and uses minimal resources.&lt;/br&gt;
Now on to the code.&lt;/br&gt;
PhysicsExtensionMethods static class:&lt;/br&gt;
&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
static class PhysicsExtensionMethods
{
    public static bool IsInSameDirection(this Vector3 vector, Vector3 otherVector)
    {
        return Vector3.Dot(vector, otherVector) &gt; 0;
    }

    public static bool IsInOppositeDirection(this Vector3 vector, Vector3 otherVector)
    {
        return Vector3.Dot(vector, otherVector) &lt; 0;
    }
}
&lt;/pre&gt;
&lt;/br&gt;
IConvexRegion interface:&lt;/br&gt;
&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public interface IConvexRegion
{
    /// &amp;lt;summary&amp;gt;
    /// Calculates the furthest point on the region 
    /// along a given direction.
    /// &amp;lt;/summary&amp;gt;
    Vector3 GetFurthestPoint(Vector3 direction);
}
&lt;/pre&gt;
&lt;/br&gt;
Simplex class:&lt;/br&gt;
&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
/// &amp;lt;summary&amp;gt;
/// Represents a generalized Tetrehedron
/// &amp;lt;/summary&amp;gt;
class Simplex
{
    List&amp;lt;Vector3&amp;gt; _vertices =
        new List&amp;lt;Vector3&amp;gt;();

    public int Count
    {
        get { return _vertices.Count; }
    }

    public Vector3 this[int i]
    {
        get { return _vertices[i]; }
    }

    public Simplex(params Vector3[] vertices)
    {
        for (int i = 0; i &amp;lt; vertices.Length; i++)
        {
            _vertices.Add(vertices[i]);
        }
    }
      
    public void Add(Vector3 vertex)
    {
        _vertices.Add(vertex);
    }

    public void Remove(Vector3 vertex)
    {
        _vertices.Remove(vertex);
    }
}
&lt;/pre&gt;
&lt;/br&gt;
GJKAlgorithm static class:&lt;/br&gt;
&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public static class GJKAlgorithm
{
    public static bool Intersects(IConvexRegion regioneOne, IConvexRegion regionTwo)
    {
        //Get an initial point on the Minkowski difference.
        Vector3 s = Support(regioneOne, regionTwo, Vector3.One);
        
        //Create our initial simplex.
        Simplex simplex = new Simplex(s);

        //Choose an initial direction toward the origin.
        Vector3 d = -s;

        //Choose a maximim number of iterations to avoid an 
        //infinite loop during a non-convergent search.
        int maxIterations = 50;

        for (int i = 0; i &amp;lt; maxIterations; i++)
        {
            //Get our next simplex point toward the origin.
            Vector3 a = Support(regioneOne, regionTwo, d);

            //If we move toward the origin and didn&#39;t pass it 
            //then we never will and there&#39;s no intersection.
            if (a.IsInOppositeDirection(d))
            {
                return false;
            }
            //otherwise we add the new
            //point to the simplex and
            //process it.
            simplex.Add(a);
            //Here we either find a collision or we find the closest feature of
            //the simplex to the origin, make that the new simplex and update the direction
            //to move toward the origin from that feature.
            if (ProcessSimplex(ref simplex, ref d))
            {
                return true;
            }
        }
        //If we still couldn&#39;t find a simplex 
        //that contains the origin then we
        //&amp;quot;probably&amp;quot; have an intersection.
        return true;
    }

    /// &amp;lt;summary&amp;gt;
    ///Either finds a collision or the closest feature of the simplex to the origin, 
    ///and updates the simplex and direction.
    /// &amp;lt;/summary&amp;gt;
    static bool ProcessSimplex(ref Simplex simplex, ref Vector3 direction)
    {
        if (simplex.Count == 2)
        {
            return ProcessLine(ref simplex, ref direction);
        }
        else if (simplex.Count == 3)
        {
            return ProcessTriangle(ref simplex, ref direction);
        }
        else
        {
            return ProcessTetrehedron(ref simplex, ref direction);
        }
    }

    /// &amp;lt;summary&amp;gt;
    /// Determines which Veronoi region of a line segment 
    /// the origin is in, utilizing the preserved winding
    /// of the simplex to eliminate certain regions.
    /// &amp;lt;/summary&amp;gt;
    static bool ProcessLine(ref Simplex simplex, ref Vector3 direction)
    {
        Vector3 a = simplex[1];
        Vector3 b = simplex[0];
        Vector3 ab = b - a;
        Vector3 aO = -a;

        if (ab.IsInSameDirection(aO))
        {
            float dot = Vector3.Dot(ab, aO);
            float angle = (float)Math.Acos(dot / (ab.Length() * aO.Length()));
            direction = Vector3.Cross(Vector3.Cross(ab, aO), ab);
        }
        else
        {
            simplex.Remove(b);
            direction = aO;
        }
        return false;
    }

    /// &amp;lt;summary&amp;gt;
    /// Determines which Veronoi region of a triangle 
    /// the origin is in, utilizing the preserved winding
    /// of the simplex to eliminate certain regions.
    /// &amp;lt;/summary&amp;gt;
    static bool ProcessTriangle(ref Simplex simplex, ref Vector3 direction)
    {
        Vector3 a = simplex[2];
        Vector3 b = simplex[1];
        Vector3 c = simplex[0];
        Vector3 ab = b - a;
        Vector3 ac = c - a;
        Vector3 abc = Vector3.Cross(ab, ac);
        Vector3 aO = -a;
        Vector3 acNormal = Vector3.Cross(abc, ac);
        Vector3 abNormal = Vector3.Cross(ab, abc);

        if (acNormal.IsInSameDirection(aO))
        {
            if (ac.IsInSameDirection(aO))
            {
                simplex.Remove(b);
                direction = Vector3.Cross(Vector3.Cross(ac, aO), ac);
            }
            else
            {
                if (ab.IsInSameDirection(aO))
                {
                    simplex.Remove(c);
                    direction = Vector3.Cross(Vector3.Cross(ab, aO), ab);
                }
                else
                {
                    simplex.Remove(b);
                    simplex.Remove(c);
                    direction = aO;
                }
            }
        }
        else
        {
            if (abNormal.IsInSameDirection(aO))
            {
                if (ab.IsInSameDirection(aO))
                {
                    simplex.Remove(c);
                    direction = Vector3.Cross(Vector3.Cross(ab, aO), ab);
                }
                else
                {
                    simplex.Remove(b);
                    simplex.Remove(c);
                    direction = aO;
                }
            }
            else
            {
                if (abc.IsInSameDirection(aO))
                {
                    direction = Vector3.Cross(Vector3.Cross(abc, aO), abc);
                }
                else
                {
                    direction = Vector3.Cross(Vector3.Cross(-abc, aO), -abc);
                }
            }
        }
        return false;
    }

    /// &amp;lt;summary&amp;gt;
    /// Determines which Veronoi region of a tetrahedron
    /// the origin is in, utilizing the preserved winding
    /// of the simplex to eliminate certain regions.
    /// &amp;lt;/summary&amp;gt;
    static bool ProcessTetrehedron(ref Simplex simplex, ref Vector3 direction)
    {
        Vector3 a = simplex[3];
        Vector3 b = simplex[2];
        Vector3 c = simplex[1];
        Vector3 d = simplex[0];
        Vector3 ac = c - a;
        Vector3 ad = d - a;
        Vector3 ab = b - a;
        Vector3 bc = c - b;
        Vector3 bd = d - b;
            
        Vector3 acd = Vector3.Cross(ad, ac);
        Vector3 abd = Vector3.Cross(ab, ad);
        Vector3 abc = Vector3.Cross(ac, ab);
            
        Vector3 aO = -a;

        if (abc.IsInSameDirection(aO))
        {
            if (Vector3.Cross(abc, ac).IsInSameDirection(aO))
            {
                simplex.Remove(b);
                simplex.Remove(d);
                direction = Vector3.Cross(Vector3.Cross(ac, aO), ac);
            }
            else if (Vector3.Cross(ab, abc).IsInSameDirection(aO))
            {
                simplex.Remove(c);
                simplex.Remove(d);
                direction = Vector3.Cross(Vector3.Cross(ab, aO), ab);
            }
            else
            {
                simplex.Remove(d);
                direction = abc;
            }
        }
        else if (acd.IsInSameDirection(aO))
        {
            if (Vector3.Cross(acd, ad).IsInSameDirection(aO))
            {
                simplex.Remove(b);
                simplex.Remove(c);
                direction = Vector3.Cross(Vector3.Cross(ad, aO), ad);
            }
            else if (Vector3.Cross(ac, acd).IsInSameDirection(aO))
            {
                simplex.Remove(b);
                simplex.Remove(d);
                direction = Vector3.Cross(Vector3.Cross(ac, aO), ac);
            }
            else
            {
                simplex.Remove(b);
                direction = acd;
            }
        }
        else if (abd.IsInSameDirection(aO))
        {
            if (Vector3.Cross(abd, ab).IsInSameDirection(aO))
            {
                simplex.Remove(c);
                simplex.Remove(d);
                direction = Vector3.Cross(Vector3.Cross(ab, aO), ab);
            }
            else if (Vector3.Cross(ad, abd).IsInSameDirection(aO))
            {
                simplex.Remove(b);
                simplex.Remove(c);
                direction = Vector3.Cross(Vector3.Cross(ad, aO), ad);
            }
            else
            {
                simplex.Remove(c);
                direction = abd;
            }
        }
        else
        {
            return true;
        }

        return false;
    }

    /// &amp;lt;summary&amp;gt;
    /// Calculates the furthest point on the Minkowski 
    /// difference along a given direction.
    /// &amp;lt;/summary&amp;gt;
    static Vector3 Support(
        IConvexRegion regionOne, 
        IConvexRegion regionTwo,
        Vector3 direction)
    {
        return regionOne.GetFurthestPoint(direction) -
            regionTwo.GetFurthestPoint(-direction);
    }
}
&lt;/pre&gt;
&lt;/br&gt;
Sphere class:&lt;/br&gt;
&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public class Sphere : IConvexRegion
{
    public Vector3 Center;
    public float Radius;

    public Sphere(Vector3 center, float radius)
    {
        Center = center;
        Radius = radius;
    }

    public Vector3 GetFurthestPoint(Vector3 direction)
    {
        if (direction != Vector3.Zero)
        {
            direction.Normalize();
        }
        return Center + Radius * direction;
    }
}
&lt;/pre&gt;
&lt;/br&gt;
Box class:&lt;/br&gt;
&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public class Box : IConvexRegion
{
    public Vector3 Center;
    Vector3 _halfDimensions = Vector3.One;
    Quaternion _orientation = Quaternion.Identity;

    public Vector3 Dimensions
    {
        get { return 2f * _halfDimensions; }
    }

    public Box(Vector3 center)
        : this(center, 1f, 1f, 1f) { }

    public Box(Vector3 center,
        float width,
        float height,
        float depth)
        : this(center, width, height, depth, Matrix.Identity) { }

    public Box(Vector3 center,
        float width,
        float height,
        float depth,
        Matrix rotationMatrix)
    {
        Center = center;
        _halfDimensions = new Vector3(
            width / 2f,
            height / 2f,
            depth / 2f);
        _orientation = Quaternion.CreateFromRotationMatrix(rotationMatrix);
    }

    public Vector3 GetFurthestPoint(Vector3 direction)
    {
        Vector3 halfHeight = _halfDimensions.Y * Vector3.Up;
        Vector3 halfWidth = _halfDimensions.X * Vector3.Right;
        Vector3 halfDepth = _halfDimensions.Z * Vector3.Backward;

        Vector3[] vertices = new Vector3[8];
        vertices[0] = halfWidth + halfHeight + halfDepth;
        vertices[1] = -halfWidth + halfHeight + halfDepth;
        vertices[2] = halfWidth - halfHeight + halfDepth;
        vertices[3] = halfWidth + halfHeight - halfDepth;
        vertices[4] = -halfWidth - halfHeight + halfDepth;
        vertices[5] = halfWidth - halfHeight - halfDepth;
        vertices[6] = -halfWidth + halfHeight - halfDepth;
        vertices[7] = -halfWidth - halfHeight - halfDepth;

        Matrix rotationTransform = Matrix.CreateFromQuaternion(_orientation);
        Matrix translation = Matrix.CreateTranslation(Center);
        Matrix world = rotationTransform *
            translation;

        Vector3 furthestPoint = Vector3.Transform(vertices[0], world);
        float maxDot = Vector3.Dot(furthestPoint, direction);
        for (int i = 1; i &amp;lt; 8; i++)
        {
            Vector3 vertex = Vector3.Transform(vertices[i], world);
            float dot = Vector3.Dot(vertex, direction);
            if (dot &amp;gt; maxDot)
            {
                maxDot = dot;
                furthestPoint = vertex;
            }               
        }
        return furthestPoint;
    }

    public Matrix CalculateWorld()
    {
        return Matrix.CreateScale(Dimensions) *
            Matrix.CreateFromQuaternion(_orientation) *
            Matrix.CreateTranslation(Center);
    }
}
&lt;/pre&gt;
&lt;/br&gt;
I hope this is helpful to someone :)
Enjoy!</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/4267506962948078816/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2012/01/gjk-algorithm.html#comment-form' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/4267506962948078816'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/4267506962948078816'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2012/01/gjk-algorithm.html' title='The GJK Algorithm'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-3764465217041544826</id><published>2012-01-08T13:06:00.000-08:00</published><updated>2012-03-04T12:34:58.979-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><category scheme="http://www.blogger.com/atom/ns#" term="XNA"/><title type='text'>Game State Management</title><content type='html'>In this article we&#39;ll be building a game state management system similar to the one &lt;a href=&quot;http://create.msdn.com/en-US/education/catalog/sample/game_state_management&quot;&gt;here&lt;/a&gt; on the Microsoft App Hub.  It&#39;s a nice little framework if you&#39;ve never checked it out before.&lt;br /&gt;
We&#39;ll be going through how to build something like this as well as extending the idea to support controls, eg. buttons, check-boxes, etc.&lt;br /&gt;
The basic idea is that we have a collection of GameScreens that update, handle input, and draw themselves.  A ScreenManager class holds this collection and treats it as sort of a &lt;a href=&quot;http://en.wikipedia.org/wiki/Stack_(data_structure)&quot;&gt;stack&lt;/a&gt; in the update process (although it&#39;s held in memory as a list).  The top-most screen on the stack accepts input and forces screens below it to hide.  We&#39;ll also have a collection of ScreenControls contained in each Screen.  These will also update, handle input and draw but will have no effect on each other and will generally contain some &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/awbftdfh.aspx&quot;&gt;events&lt;/a&gt; like Clicked or what have you.  How these events are handled will be up to the GameScreen but the conditions under which each event fires will be decided by the ScreenControl.&lt;br /&gt;
For starters, go ahead and create a new XNA Windows Game project.  I named mine GameStateTutorial.&lt;br /&gt;
We&#39;re going to need four classes to start go ahead and right click on the game project in your solution explorer and select Add -&amp;gt; Class... then add a class named ScreenManager.  Do the same thing to create a GameScreen class, an InputState class and a ScreenControl class.&lt;br /&gt;
Let&#39;s work on the InputState class first.&lt;br /&gt;
This class will watch for player input and will be passed to screens when they handle input.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class InputState
{
    //We&#39;re going to handle the XBox case for input too so we&#39;ll
    //need to specify the max number of players.
    const int _maxInputs = 4;

    //We&#39;ll hold the input state for each player in arrays.
    public readonly KeyboardState[] CurrentKeyStates;
    public readonly KeyboardState[] PreviousKeyStates;
    public readonly GamePadState[] CurrentGamePadStates;
    public readonly GamePadState[] PreviousGamePadStates;

    //And we want to keep track of whether or not a game pad
    //was ever connected so we&#39;ll use another array for that.
    public readonly bool[] GamePadWasConnected;

    //There&#39;s only one possible mouse input since there&#39;s
    //no mouse for the Xbox.
    MouseState _currentMouseState;
    MouseState _previousMouseState;

    public MouseState CurrentMouseState
    {
        get { return _currentMouseState; }
    }

    public MouseState PreviousMouseState
    {
        get { return _previousMouseState; }
    }

    public InputState()
    {
        CurrentKeyStates = new KeyboardState[_maxInputs];
        PreviousKeyStates = new KeyboardState[_maxInputs];
        CurrentGamePadStates = new GamePadState[_maxInputs];
        PreviousGamePadStates = new GamePadState[_maxInputs];
        CurrentGamePadStates = new GamePadState[_maxInputs];
        GamePadWasConnected= new bool[_maxInputs];
    }

    public void Update()
    {
        //We update the state of each player.
        for (int i = 0; i &amp;lt; _maxInputs; i++)
        {
            PreviousKeyStates[i] = CurrentKeyStates[i];
            CurrentKeyStates[i] = Keyboard.GetState((PlayerIndex)i);
            PreviousGamePadStates[i] = CurrentGamePadStates[i];
            CurrentGamePadStates[i] = GamePad.GetState((PlayerIndex)i);
            
            //if a game pad was ever connected we set that to true.
            if (CurrentGamePadStates[i].IsConnected)
            {
                GamePadWasConnected[i] = true;
            }
        }

        _previousMouseState = _currentMouseState;
        _currentMouseState = Mouse.GetState();
    }

    //This method checks to see if a key has just been pressed this frame.
    //We have a PlayerIndex as a nullable parameter; if it is null we&#39;ll check
    //for input from every player, otherwise just from the specified player.  
    //The out parameter, playerIndex, returns which player pressed the key.
    public bool IsNewKeyPressed(
        Keys key,
        PlayerIndex? controllingPlayer,
        out playerIndex)
    {
        if (controllingPlayer != null)
        {
            playerIndex = controllingPlayer.Value;
            int i = (int)playerIndex;
            
            return (CurrentKeyState[i].IsKeyDown(key) &amp;amp;&amp;amp;
                PreviousKeyState[i].IsKeyUp(key));
        }
        else
        {
            return (IsNewKeyPressed(key, PlayerIndex.One, out playerIndex) ||
                IsNewKeyPressed(key, PlayerIndex.Two, out playerIndex) ||
                IsNewKeyPressed(key, PlayerIndex.Three, out playerIndex) ||
                IsNewKeyPressed(key, PlayerIndex.Four, out playerIndex));
        }
    }

    //We do basically the same thing for game pad buttons.
    public bool IsNewButtonPressed(
        Buttons button,
        PlayerIndex? controllingPlayer,
        out playerIndex)
    {
        if (controllingPlayer != null)
        {
            playerIndex = controllingPlayer.Value;
            int i = (int)playerIndex;
            
            return (CurrentGamePadState[i].IsButtonDown(button) &amp;amp;&amp;amp;
                PreviousGamePadState[i].IsButtonUp(button));
        }
        else
        {
            return (IsNewButtonPressed(key, PlayerIndex.One, out playerIndex) ||
                IsNewButtonPressed(key, PlayerIndex.Two, out playerIndex) ||
                IsNewButtonPressed(key, PlayerIndex.Three, out playerIndex) ||
                IsNewButtonPressed(key, PlayerIndex.Four, out playerIndex));
        }
    }

    //And a simple method to check for a left mouse click.
    public bool WasMouseLeftClicked()
    {
        return (_currentMouseState.LeftButton == ButtonState.Pressed &amp;amp;&amp;amp;
            _previousMouseState.LeftButton == ButtonState.Released);
    }
}
&lt;/pre&gt;
That&#39;s all we need for now.&lt;br /&gt;
Let&#39;s work on the ScreenControl class.  These will be used for our buttons and labels and such.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;abstract class ScreenControl
{
    Vector2 _position;
    GameScreen _screen;
    
    public Vector2 Position
    {
        get { return _position; }
        set { _position = value; }
    }

    public GameScreen Screen
    {
        get { return _screen; }
    }

    public abstract int Width { get; set; }
    public abstract int Height { get; set; }

    public ScreenControl(GameScreen screen)
    {
        _screen = screen;
    }

    public virtual void LoadContent(ContentManager content) { }
    
    //The screens transition on and off and the positionTransform parameter will help us have
    //our controls slide in and out of view as the screen transitions.
    public virtual void HandleInput(InputState input, Matrix positionTransform) { }

    public virtual void Update(GameTime gameTime, Matrix positionTransform) { }

    //The alpha parameter has a similar purpose to the positionTransform.
    public virtual void Draw(GameTime gameTime, Matrix positionTransform, float alpha) { }
    
    public virtual Rectangle CalculateControlRectangle(Matrix positionTransform)
    {
        Vector2 transformedPosition = Vector2.Transform(_position, positionTransform);
        return new Rectangle(
            (int)transformedPosition.X,
            (int)transformedPosition.Y,
            Width,
            Height);
    }
}
&lt;/pre&gt;
Next up is the GameScreen class.  We need it to be able to transition on and off smoothly so it will contain an enum that represents its transition state as well as how far transitioned it is, the total time it takes to transition on or off, whether or not it&#39;s a pop-up screen, and several other fields and helper methods.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;//The transition state of the screen.
public enum ScreenState
{
    TransitionOn,
    TransitionOff,
    Active,
    Hidden,
}
abstract class GameScreen
{
    PlayerIndex? _controllingPlayer;
    ScreenManager _screenManager;
    bool _isExiting = false;
    bool _isPopup = false;
    ScreenState _state = ScreenState.TransitionOn;
    TimeSpan _transitionOnTime = TimeSpan.Zero;
    TimeSpan _transitionOffTime = TimeSpan.Zero;
    
    //_transitionPosition at 1f means full transition while 0f means no transition.
    float _transitionPosition = 1f;

    bool _otherScreenHasFocus;
    List&amp;lt;ScreenControl&amp;gt; _controls = new List&amp;lt;ScreenControl&amp;gt;();

    public PlayerIndex? ControllingPlayer
    {
        get { return _controllingPlayer; }
        internal set { _controllingPlayer = value; }
    }

    public ScreenManager ScreenManager
    {
        get { return _screenManager; }
        internal set { _screenManager = value; }
    }

    public bool IsPopup
    {
        get { return _isPopup; }
        protected set { _isPopup = value; }
    }

    public bool IsActive
    {
        get
        {
            return !_otherScreenHasFocus &amp;amp;&amp;amp;
                (_state == ScreenState.TransitionOn ||
                _state == ScreenState.Active);
        }
    }

    public ScreenState ScreenState 
    {
        get { return _state; }
        protected set { _state = value; }
    }

    public float TransitionAlpha 
    {
        get { return 1f - _transitionPosition; }
    }

    public float TransitionPosition 
    {
        get { return _transitionPosition; }
    }

    public bool IsExiting
    {
        get { return _isExiting; }
        protected internal set { _isExiting = value; }
    }

    public TimeSpan TransitionOnTime
    {
        get { return _transitionOnTime; }
        protected set { _transitionOnTime = value; }
    }

    public TimeSpan TransitionOffTime
    {
        get { return _transitionOffTime; }
        protected set { _transitionOffTime = value; }
    }

    public IList&amp;lt;ScreenControl&amp;gt; Controls
    {
        get { return _controls; }
    }

    //Loads the content of each control.  We&#39;re getting the
    //content manager from ScreenManager.Game but we can override this.
    public virtual void LoadContent() 
    {
        ContentManager content = ScreenManager.Game.Content;
        foreach (ScreenControl control in _controls)
        {
            control.LoadContent(content);
        }
    }

    public virtual void UnloadContent() { }

    //This helper method determines how to move the controls while
    //we&#39;re transitioning in or out and can be overridden for different behavior.
    //A control can also determine its own transition behavior since this Matrix
    //is passed along in the Update, HandleInput and Draw methods and the
    //ScreenControl can use it or not.
    protected virtual Matrix CalculateTransitionOffset()
    {
        float transitionOffset = (float)Math.Pow(TransitionPosition, 2);
        Vector2 positionTranslation;
        if (_state == ScreenState.TransitionOn)
        {
            positionTranslation = new Vector2(-256 * transitionOffset, 0);
        }
        else if (_state == ScreenState.TransitionOff)
        {
            positionTranslation = new Vector2(512 * transitionOffset, 0);
        }
        else
        {
            positionTranslation = Vector2.Zero;
        }
        Matrix transform = Matrix.CreateTranslation(new Vector3(positionTranslation, 0));
        return transform;
    }

    //This helper method increments the _transitionPosition the appropriate
    //amount and then returns true if it&#39;s still transitioning
    //or false if it&#39;s done.
    bool UpdateTransition(
        GameTime gameTime,
        TimeSpan time,
        int direction)
    {
        float transitionDelta;
        if (time == TimeSpan.Zero)
        {
            transitionDelta = 1;
        }
        else
        {
            transitionDelta =
                (float)(gameTime.ElapsedGameTime.TotalMilliseconds / time.TotalMilliseconds);
        }

        _transitionPosition += transitionDelta * direction;

        if ((direction &amp;lt; 0 &amp;amp;&amp;amp; _transitionPosition &amp;lt;= 0) ||
            (direction &amp;gt; 0 &amp;amp;&amp;amp; _transitionPosition &amp;gt;= 1))
        {
            _transitionPosition = MathHelper.Clamp(
                _transitionPosition, 0f, 1f);
            return false;
        }

        return true;
    }

    //This updates the transition state as well as the
    //the controls.
    //if a screen is exiting it transitions off and then removes itself
    //from the ScreenManager and if it&#39;s covered by another screen
    //then it transitions off to hide.
    //otherwise, it&#39;s either active or transitioning on.
    public virtual void Update(
        GameTime gameTime,
        bool otherScreenHasFocus,
        bool coveredByOtherScreen)
    {
        _otherScreenHasFocus = otherScreenHasFocus;
        if (_isExiting)
        {
            _state = ScreenState.TransitionOff;
            if (!UpdateTransition(gameTime, _transitionOffTime, 1))
            {
                ScreenManager.RemoveScreen(this);
            }
        }
        else if (coveredByOtherScreen)
        {
            if (UpdateTransition(gameTime, _transitionOffTime, 1))
            {
                _state = ScreenState.TransitionOff;
            }
            else
            {
                _state = ScreenState.Hidden;
            }
        }
        else
        {
            if (UpdateTransition(gameTime, _transitionOnTime, -1))
            {
                _state = ScreenState.TransitionOn;
            }
            else
            {
                _state = ScreenState.Active;
            }
        }

        foreach (ScreenControl control in _controls)
        {
            Matrix transform = CalculateTransitionOffset();
            control.Update(gameTime, transform);
        }
    }

    public virtual void HandleInput(InputState input)
    {
        foreach (ScreenControl control in _controls)
        {
            Matrix transform = CalculateTransitionOffset();
            control.HandleInput(input, transform);
        }
    }

    public virtual void Draw(GameTime gameTime)
    {
        SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
        Matrix transform = CalculateTransitionOffset();

        spriteBatch.Begin();
        foreach (ScreenControl control in _controls)
        {
            control.Draw(
                gameTime,
                transform,
                TransitionAlpha);
        }
        spriteBatch.End();
    }

    public void ExitScreen()
    {
        if (_transitionOffTime == TimeSpan.Zero)
        {
            ScreenManager.RemoveScreen(this);
        }
        else
        {
            _isExiting = true;
        }
    }
}
&lt;/pre&gt;
Since we&#39;ll be using the mouse for this tutorial, let&#39;s make a Cursor class and add an image to draw for a mouse cursor.&lt;br /&gt;
Here&#39;s a cursor image.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhRq2CdHBzLGPIwC3O3ysScTzu0IV24WYmM_7XIdGKF5P9g7dJylYvBWPNBhdztUOB8llO7MhMN4fDWBfYjZUBYT-vUpiaUZEiz3emOzSRZF7w2qciMjLX1IG-PkOljxWUDvQC2Gr1iSp4/s1600/cursor_texture.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhRq2CdHBzLGPIwC3O3ysScTzu0IV24WYmM_7XIdGKF5P9g7dJylYvBWPNBhdztUOB8llO7MhMN4fDWBfYjZUBYT-vUpiaUZEiz3emOzSRZF7w2qciMjLX1IG-PkOljxWUDvQC2Gr1iSp4/s1600/cursor_texture.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
And the Cursor class:&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class Cursor
{
    Texture2D _texture;
    Vector2 _position;

    public Texture2D Texture
    {
        get { return _texture; }
        set { _texture = value; }
    }

    public void LoadContent(ContentManager content)
    {
        if (_texture == null)
        {
            _texture = content.Load&lt;texture2d&gt;(&quot;cursor_texture&quot;);
        }
    }

    public void Update(InputState input)
    {
        _position = new Vector2(
            (float)input.CurrentMouseState.X,
            (float)input.CurrentMouseState.Y);

    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(
            _texture,
            _position,
            Color.White);
    }
}
&lt;/texture2d&gt;&lt;/pre&gt;
Now let&#39;s move on to the ScreenManager which as the name suggests, will manage a collection of screens.  This class will inherit from DrawableGameComponent so it will contain a Game object passed in through the constructor.  It will also override some virtual functions for loading content, updating and drawing.&lt;br /&gt;
At this point we&#39;re also going to need a few more assets to load.  Go ahead and right click on the content project and select Add -&amp;gt; New Item... and then in the dialogue that appears select Sprite Font and give it a name.  I named mine &quot;menu_font.spritefont&quot;.  While we&#39;re here let&#39;s add an image to use as a background.  Here&#39;s some ugly blue ellipses.
&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglouOhgxObuPhpu6f6JaOR1V2psjE4n_NEyUcqPyxvozXhSyeKpzw8qfssYsNt0E_QMmIf3ns7J7D21HG5d0TqtCuGtZmb_gmmZSNVMbk_NEOabU9svc_ihjAApKAEmCJWLYaETxBmIPo/s1600/blue_ellipses.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglouOhgxObuPhpu6f6JaOR1V2psjE4n_NEyUcqPyxvozXhSyeKpzw8qfssYsNt0E_QMmIf3ns7J7D21HG5d0TqtCuGtZmb_gmmZSNVMbk_NEOabU9svc_ihjAApKAEmCJWLYaETxBmIPo/s640/blue_ellipses.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
And a button texture for later.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjvrjQK_TSAiFS-9K67tEKRX4YGRv2N4xnvvLbSTXFd4QbvRknwElmx0BPNfPibIiizNTA6iohEseRMtbbfO5NWy1Ad3BJRXAeoNSezGLbxxPbyj1ou8Oo30jGo3nxanxlyXfgCceqAZq8/s1600/button_texture.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjvrjQK_TSAiFS-9K67tEKRX4YGRv2N4xnvvLbSTXFd4QbvRknwElmx0BPNfPibIiizNTA6iohEseRMtbbfO5NWy1Ad3BJRXAeoNSezGLbxxPbyj1ou8Oo30jGo3nxanxlyXfgCceqAZq8/s1600/button_texture.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class ScreenManager : DrawableGameComponent
{
    List&amp;lt;GameScreen&amp;gt; _screens = new List&amp;lt;GameScreen&amp;gt;();
    List&amp;lt;GameScreen&amp;gt; _screensToUpdate = new List&amp;lt;GameScreen&amp;gt;();
    InputState _input = new InputState();
    SpriteBatch _spriteBatch;
    SpriteFont _font;
    Texture2D _blankTexture;
    bool _isInitialized = false;
    Cursor _cursor = new Cursor();

    public SpriteBatch SpriteBatch
    {
        get { return _spriteBatch; }
    }

    public SpriteFont Font
    {
        get { return _font; }
    }

    public ScreenManager(Game game)
        : base(game) { }


    public override void Initialize()
    {
        base.Initialize();
        //Now we have a GraphicsDevice initialized in the Game class
        //and we set _isInitialized to true.
        _isInitialized = true;
    }

    protected override void LoadContent()
    {
        ContentManager content = Game.Content;
        _spriteBatch = new SpriteBatch(Game.GraphicsDevice);

        _font = content.Load&amp;lt;SpriteFont&amp;gt;(&quot;menu_font&quot;);

        //We have a 1 by 1 white texture we can use for
        //different effects like fading to black.            
        _blankTexture = new Texture2D(Game.GraphicsDevice, 1, 1);
        Color[] colorData = { Color.White };
        _blankTexture.SetData&amp;lt;Color&amp;gt;(colorData);

        _cursor.LoadContent(content);
        foreach (GameScreen screen in _screens)
        {
            screen.LoadContent();
        }
    }

    protected override void UnloadContent()
    {
        foreach (GameScreen screen in _screens)
        {
            screen.UnloadContent();
        }
    }

    public override void Update(GameTime gameTime)
    {
        _input.Update();
        
        _cursor.Update(_input);

        //Here we populate a temporary list to update.
        _screensToUpdate.Clear();
        foreach (GameScreen screen in _screens)
        {
            _screensToUpdate.Add(screen);
        }

        //We&#39;ll need a couple of booleans to keep track
        //of which screens are covered by other screens
        //or accepting input.
        bool otherScreenHasFocus = !Game.IsActive;
        bool coveredByOtherScreen = false;

        //We iterate through the list backwards, popping a screen off the top,
        //updating it and determining whether or not to accept input
        //or cover screens below it.
        while (_screensToUpdate.Count &amp;gt; 0)
        {
            GameScreen screen = _screensToUpdate[_screensToUpdate.Count - 1];
            _screensToUpdate.RemoveAt(_screensToUpdate.Count - 1);

            screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            if (screen.ScreenState == ScreenState.TransitionOn ||
                screen.ScreenState == ScreenState.Active)
            {
                if (!otherScreenHasFocus)
                {
                    screen.HandleInput(_input);
                    otherScreenHasFocus = true;
                }
                if (!screen.IsPopup)
                {
                    coveredByOtherScreen = true;
                }
            }
        }
    }

    public override void Draw(GameTime gameTime)
    {
        foreach (GameScreen screen in _screens)
        {
            if (screen.ScreenState != ScreenState.Hidden)
            {
                screen.Draw(gameTime);
            }
        }
        
        SpriteBatch.Begin();
        _cursor.Draw(SpriteBatch);
        SpriteBatch.End();
    }

    //If the game has initialized we can unload or load content.
    public void RemoveScreen(GameScreen screen)
    {
        if (_isInitialized)
        {
            screen.UnloadContent();
        }
        _screens.Remove(screen);
        _screensToUpdate.Remove(screen);
    }

    //Here we set the screen&#39;s ScreenManager, which player is
    //controlling the screen, and load its content if appropriate.
    public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer)
    {
        screen.ScreenManager = this;
        screen.ControllingPlayer = controllingPlayer;
        screen.IsExiting = false;
        _screens.Add(screen);
        if (_isInitialized)
        {
            screen.LoadContent();
        }
    }

    //We want access to the screens in the collection but
    //not the collection itself.
    public GameScreen[] GetScreens()
    {
        return _screens.ToArray();
    }

    //A helper method for fading to black.
    public void FadeBackBufferToBlack(float alpha)
    {
        Viewport viewport = GraphicsDevice.Viewport;
        _spriteBatch.Begin();
        _spriteBatch.Draw(
            _blankTexture,
            new Rectangle(
                0, 0,
                viewport.Width, viewport.Height),
            Color.Black * alpha);
        _spriteBatch.End();
    }
}
&lt;/pre&gt;
Now we have a basic framework that we can build off of.  Let&#39;s start by making a couple new classes, a ScreenControl for displaying a texture which we can use in a BackgroundScreen.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class TextureDisplay : ScreenControl
{
    int _width;
    int _height;
    Texture2D _texture;

    public Texture2D Texture
    {
        get { return _texture; }
        set { _texture = value; }
    }

    public override int Width
    {
        get { return _width; }
        set { _width = value; }
    }

    public override int Height
    {
        get { return _height; }
        set { _height = value; }
    }

    public TextureDisplay(GameScreen screen)
        : base(screen)
    {
    }

    public override void LoadContent(ContentManager content)
    {
        if (_texture == null)
        {
            _texture = content.Load&lt;texture2d&gt;(&quot;blue_ellipses&quot;);
        }
        Viewport viewport = Screen.ScreenManager.GraphicsDevice.Viewport;
        if (_width &amp;lt;= 0)
        {
            _width = viewport.Width;
        }
        if (_height &amp;lt;= 0)
        {
            _height = viewport.Height;
        }
    }

    public override void Draw(GameTime gameTime, Matrix positionTransform, float alpha)
    {
        SpriteBatch spriteBatch = Screen.ScreenManager.SpriteBatch;
        spriteBatch.Draw(
            _texture,
            CalculateControlRectangle(positionTransform),
            Color.White * alpha);
    }
}
&lt;/texture2d&gt;&lt;/pre&gt;
Now we&#39;ll make our BackgroundScreen which will contain a single TextureDisplay control.  This screen won&#39;t slide in or out so we&#39;ll override the CalculateTransitionOffset to return the identity matrix.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class BackgroundScreen : GameScreen
{
    public BackgroundScreen()
    {
        TransitionOnTime = TimeSpan.FromSeconds(.5d);
        TransitionOffTime = TimeSpan.FromSeconds(.5d);
        TextureDisplay background = new TextureDisplay(this);
        Controls.Add(background);
    }

    public override void Update(
        GameTime gameTime,
        bool otherScreenHasFocus,
        bool coveredByOtherScreen)
    {
        //The background screen never hides so it&#39;s never covered.
        base.Update(gameTime, otherScreenHasFocus, false);
    }

    protected override Matrix CalculateTransitionOffset()
    {
        return Matrix.Identity;
    }
}
&lt;/pre&gt;
We can test this out now.  Here&#39;s my Game1 class:&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    ScreenManager screenManager;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = &quot;Content&quot;;

        screenManager = new ScreenManager(this);
        screenManager.AddScreen(new BackgroundScreen(), null);

        Components.Add(screenManager);
    }

    protected override void Initialize()
    {        
        base.Initialize();
    }

      
    protected override void Update(GameTime gameTime)
    {           
        base.Update(gameTime);
    }

      
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);           
        base.Draw(gameTime);
    }
}
&lt;/pre&gt;
Which looks like this when we run it:&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgarC5559_U08AvWTmLRnBCR0R3HCKxtSGmRZgnS2AbKF3UeWThh38tRoC5w91dg1k3mFpBJnFUmmXQi9SlixplmzVLR1tprPaYA4m5mjvbNyOpjoSFcV1kooprZmQPJVEA6erVRoExkCQ/s1600/game_state_output_01.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;402&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgarC5559_U08AvWTmLRnBCR0R3HCKxtSGmRZgnS2AbKF3UeWThh38tRoC5w91dg1k3mFpBJnFUmmXQi9SlixplmzVLR1tprPaYA4m5mjvbNyOpjoSFcV1kooprZmQPJVEA6erVRoExkCQ/s640/game_state_output_01.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
Before we can handle events, we need to make an EventArgs class that holds a PlayerIndex so we know which player trigger the event.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class PlayerIndexEventArgs : EventArgs
{
    PlayerIndex _playerIndex;

    public PlayerIndex PlayerIndex
    {
    get { return _playerIndex; }
    }

    public PlayerIndexEventArgs(PlayerIndex playerIndex)
    {
        _playerIndex = playerIndex;
    }
}
&lt;/pre&gt;
Let&#39;s continue by making two more ScreenControl classes:  a ScreenLabel class and a GameButton class.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class ScreenLabel : ScreenControl
{
    string _text;

    public string Text
    {
        get { return _text; }
        set { _text = value; }
    }

    public override int Width
    {
        get
        {
            return (int)Screen.ScreenManager.Font.MeasureString(_text).X;
        }
        set { }
    }

    public override int Height
    {
        get
        {
            return Screen.ScreenManager.Font.LineSpacing;
        }
        set { }
    }

    public ScreenLabel(GameScreen screen, string text)
        : base(screen)
    {
        _text = text;
    }

    //Instead of using the default positionTransform we&#39;ll make the
    //labels move up and down during transition.
    Matrix CalculateLabelTransform()
    {
        float transitionOffset = (float)Math.Pow(Screen.TransitionPosition, 2);
        Vector2 translation = new Vector2(0f, -transitionOffset * 100);
        Matrix labelTransform = Matrix.CreateTranslation(new Vector3(translation, 0f));
        return labelTransform;
    }

    public override void Draw(GameTime gameTime, Matrix positionTransform, float alpha)
    {
        SpriteBatch spriteBatch = Screen.ScreenManager.SpriteBatch;
        SpriteFont font = Screen.ScreenManager.Font;

        Matrix labelTransform = CalculateLabelTransform();

        Vector2 drawPosition = Vector2.Transform(Position, labelTransform);
        Vector2 labelOrigin = font.MeasureString(_text) / 2;
        Color labelColor = new Color(192, 192, 192) * alpha;
        float labelScale = 1.25f;
            
        spriteBatch.DrawString(
            font,
            _text,
            drawPosition,
            labelColor,
            0f,
            labelOrigin,
            labelScale,
            SpriteEffects.None,
            0f);
    }
}
&lt;/pre&gt;
And now the GameButton class.  This will contain a Clicked event which will be fired whenever the user LeftClicks within the control&#39;s bounds.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class GameButton : ScreenControl
{
    int _width = 150;
    int _height = 50;
    Texture2D _buttonTexture;
    string _text;
        
    public event EventHandler&amp;lt;PlayerIndexEventArgs&amp;gt; Clicked;

    public Texture2D ButtonTexture
    {
        get { return _buttonTexture; }
        set { _buttonTexture = value; }
    }

    public string Text
    {
        get { return _text; }
        set { _text = value; }
    }

    public override int Width
    {
        get { return _width; }
        set { _width = value; }
    }

    public override int Height
    {
        get { return _height; }
        set { _height = value; }
    }

    public GameButton(GameScreen screen, string text)
        : base(screen)
    {
        _text = text;
    }

    public override void LoadContent(ContentManager content)
    {
        if (_buttonTexture == null)
        {
            _buttonTexture = content.Load&amp;lt;Texture2D&amp;gt;(&quot;button_texture&quot;);
        }
    }

    public override void HandleInput(InputState input, Matrix positionTransform)
    {
        Point mousePosition = new Point(
            input.CurrentMouseState.X,
            input.CurrentMouseState.Y);
        Rectangle buttonRectangle = CalculateControlRectangle(positionTransform);
        
        if (input.IsMouseLeftClicked() &amp;amp;&amp;amp;
            buttonRectangle.Contains(mousePosition))
        {
            OnClick(PlayerIndex.One);
        }
    }

    public override void Draw(GameTime gameTime, Matrix positionTransform, float alpha)
    {
        SpriteBatch spriteBatch = Screen.ScreenManager.SpriteBatch;
        SpriteFont font = Screen.ScreenManager.Font;
            
        //We need to position the button text in the center
        //of the button.
        Rectangle buttonRectangle = CalculateControlRectangle(positionTransform);
        Vector2 buttonPosition = Vector2.Transform(Position, positionTransform);
        Vector2 textDimensions = font.MeasureString(_text);
        Vector2 buttonDimensions = new Vector2(
            (int)buttonRectangle.Width, 
            (int)buttonRectangle.Height);
        Vector2 textPosition = buttonPosition + buttonDimensions / 2f - textDimensions / 2f;


        spriteBatch.Draw(
            _buttonTexture,
            buttonRectangle,
            Color.White * alpha);

        spriteBatch.DrawString(
            font,
            _text,
            textPosition,
            Color.White * alpha);
    }

    protected void OnClick(PlayerIndex playerIndex)
    {
        if (Clicked != null)
        {
            Clicked(this, new PlayerIndexEventArgs(playerIndex));
        }
    }
}
&lt;/pre&gt;
Now we can use both of these new ScreenControls in making our MenuScreen and MainMenuScreen classes.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;abstract class MenuScreen : GameScreen
{
    ScreenLabel _menuTitle;

    public MenuScreen(string title)
    {
        TransitionOnTime = TimeSpan.FromSeconds(.5);
        TransitionOffTime = TimeSpan.FromSeconds(.5);

        _menuTitle = new ScreenLabel(
            this,
            title);
        Controls.Add(_menuTitle);
    }

    public override void LoadContent()
    {
        base.LoadContent();
        Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
        _menuTitle.Position = new Vector2(viewport.Width / 2, 80f);
    }

    protected virtual void OnCancel(PlayerIndex playerIndex)
    {
        ExitScreen();
    }

    //This let&#39;s us hook the OnCancel method to control events.
    protected void OnCancel(object sender, PlayerIndexEventArgs e)
    {
        OnCancel(e.PlayerIndex);
    }
}
&lt;/pre&gt;
And finally our MainMenuScreen:&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class MainMenuScreen : MenuScreen
{
    GameButton _exit;

    public MainMenuScreen()
        : base(&quot;Main Menu&quot;)
    {
        _exit = new GameButton(this, &quot;Exit&quot;);
        _exit.Clicked += OnCancel;
        Controls.Add(_exit);
    }

    public override void LoadContent()
    {
        base.LoadContent();
        Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
        _exit.Position = new Vector2(
            (int)viewport.Width / 2 - _exit.Width / 2,
            160f);
    }

    protected override void OnCancel(PlayerIndex playerIndex)
    {
        ScreenManager.Game.Exit();
    }
}
&lt;/pre&gt;
Now we can test it out!  Change your Game1 class to look this this:&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    ScreenManager screenManager;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = &quot;Content&quot;;
        screenManager = new ScreenManager(this);
        screenManager.AddScreen(new BackgroundScreen(), null);
        screenManager.AddScreen(new MainMenuScreen(), null);

        Components.Add(screenManager);
    }

    protected override void Initialize()
    {        
        base.Initialize();
    }

      
    protected override void Update(GameTime gameTime)
    {           
        base.Update(gameTime);
    }

      
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);           
        base.Draw(gameTime);
    }
}
&lt;/pre&gt;
And running this should produce a Main menu that transitions in.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgR1_wFx-DgSfUDdD_aPM4dymkNKVlZiWlZF-xhqNjj7ChRsgN83tm3RJB_eWWQ4Vza8VI-2nCApZusA7zuNtrjjQireR-CmWYhJIolCTv_1y4XyovNB6-Lh1m_8BRjv78yEchekHYklu4/s1600/game_state_output_02.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;408&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgR1_wFx-DgSfUDdD_aPM4dymkNKVlZiWlZF-xhqNjj7ChRsgN83tm3RJB_eWWQ4Vza8VI-2nCApZusA7zuNtrjjQireR-CmWYhJIolCTv_1y4XyovNB6-Lh1m_8BRjv78yEchekHYklu4/s640/game_state_output_02.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
I&#39;m going to leave it at that for this article but will probably pick it up again in a future one.&lt;/br&gt;
Thanks for reading!</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/3764465217041544826/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2012/01/game-state-management.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/3764465217041544826'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/3764465217041544826'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2012/01/game-state-management.html' title='Game State Management'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhRq2CdHBzLGPIwC3O3ysScTzu0IV24WYmM_7XIdGKF5P9g7dJylYvBWPNBhdztUOB8llO7MhMN4fDWBfYjZUBYT-vUpiaUZEiz3emOzSRZF7w2qciMjLX1IG-PkOljxWUDvQC2Gr1iSp4/s72-c/cursor_texture.png" height="72" width="72"/><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-6524382191693270528</id><published>2011-12-23T07:11:00.000-08:00</published><updated>2012-03-04T12:36:36.373-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><title type='text'>The Iterator Pattern</title><content type='html'>It doesn&#39;t take long in one&#39;s c# education before one discovers the &#39;foreach&#39; loop.  What they may not know is that this is actually the Iterator pattern built into the language through the IEnumerator and IEnumerable interfaces.&lt;/br&gt;
In this article I&#39;ll go over the pattern and show you how to build an iterator from scratch.  While you may never implement this exact pattern in any of your projects it&#39;s good to know how it&#39;s done and will hopefully help you understand how to extend the built-in iteration system within the c# language.&lt;/br&gt;
Ignoring our &#39;foreach&#39; capabilities for the moment let&#39;s see what the problem is.
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
//Here&#39;s a simple class that can be kept in
//some sort of collection.  We don&#39;t know what kind of
//collection but we&#39;d like to go through each Item and 
//print out the description.
class Item
{
    string _description;

    public string Description
    {
        get { return _description; }
    }

    public Item(string description)
    {
        _description = description;
    }
}

class Program
{
    static void Main(string[] args)
    {
        List&amp;lt;Item&amp;gt; itemList = new List&amp;lt;Item&amp;gt;();
        
        int maxArraySize = 3;
        Item[] itemArray = new Item[3];
        
        //populate the collections.
        for (int i = 0; i &lt; maxArraySize; i++)
        {
            Item ithItem = new Item(&quot;Item&quot; + i.ToString());

            itemArray[i] = ithItem;
            itemList.Add(ithItem);
        }
        
        //Iterate over the List...
        for (int i = 0; i &lt; itemList.Count; i++)
        {
            Console.WriteLine(itemList[i].Description);
        }
        
        //Iterate over the Array...
        for (int = 0; i &lt; itemArray.Length; i++)
        {
            Console.WriteLine(itemArray[i].Description);
        }
    }
}
&lt;/pre&gt;
&lt;/br&gt;
Again, temporarily forgetting about the &#39;foreach&#39; loop (we&#39;ll get to it), this is a mess with no obvious solution.  For every type of collection we have we&#39;d need to loop over it in a different way.  The List has a Length property while arrays have a Count property and there&#39;s no telling how some other collection may be looped through.&lt;/br&gt;
Let&#39;s make a simple Store interface to help illustrate.  Some stores may want use Arrays, and some may want to use Lists or any other type of collection at all, but they all need to be able to print out the description of their inventory.  A Store can be thought of here as an Item collection.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
interface IStore
{
    void PrintInventory();
}

public class ListStore : IStore
{
    List&amp;lt;Item&amp;gt; _inventory;

    public ListStore()
    {
        _inventory.Add(new Item(&quot;Soap&quot;));
        _inventory.Add(new Item(&quot;Fan&quot;));
        _inventory.Add(new Item(&quot;Fish Tank&quot;));
    }

    public void PrintInventory()
    {
        //Here&#39;s the problem...
        for (int i = 0; i = _inventory.Count; i++)
        {
            Console.WriteLine(_inventory[i].Description);
        }
    }
}

public class ArrayStore : IStore
{
    const int maxSize = 3;
    Item[] _inventory;

    public ListStore()
    {
        _inventory = new Item[maxSize];

        _inventory[0] = new Item(&quot;Shoes&quot;);
        _inventory[1] = new Item(&quot;Duct Tape&quot;);
        _inventory[2] = new Item(&quot;Venti Cappuccino&quot;);
    }

    public void PrintInventory()
    {
        //Here&#39;s the problem...
        //Duplicating code at all or with slight differences
        //should make your refactoring senses tingle!
        for (int i = 0; i = itemList.Count; i++)
        {
            Console.WriteLine(itemList[i].Description);
        }

    }
}
&lt;/pre&gt;
What&#39;s changing here is the particulars of the iteration.  We&#39;d like to encapsulate iteration and the Iterator pattern does just that by introducing an Iterator interface that will allow us to control how we loop through any collection in any way we want.&lt;/br&gt;
It&#39;s not too tricky so let&#39;s take a look.
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
interface IIterator
{
    //This will tell us if there is a
    //next element in a collection...
    bool HasNext();

    //And this will return the next element.
    object Next();
}

//Let&#39;s see how these iterators are implemented.
//first for a List...
class ListIterator : IIterator
{
    List&amp;lt;Item&amp;gt; _items;

    //_position keeps track of where we
    //are in the iteration of the list.
    int _position = 0;

    public ListIterator(List&amp;lt;Item&amp;gt; items)
    {
        _items = items;
    }

    public object Next()
    {
        Item item = _items[_position];
        _position++;
        return item;
    }

    public bool HasNext()
    {
        if (_position &gt;= items.Count)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

//And now for the array...
class ArrayIterator : IIterator
{
    Item[] _items;
    int _position = 0;

    public ListIterator(Item[] items)
    {
        _items = items;
    }

    public object Next()
    {
        Item item = _items[_position];

        //Increment our position...
        _position++;
        return item;
    }

    public bool HasNext()
    {
        if (_position &gt;= items.Length)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}
&lt;/pre&gt;
Now we need to make some small changes to the Store interface...&lt;/br&gt;

&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
interface IStore
{
    //All we need is a method to retrieve
    //the appropriate iterator.
    IIterator GetIterator();
}

public class ListStore : IStore
{
    List&amp;lt;Item&amp;gt; _inventory;

    public ListStore()
    {
        _inventory.Add(new Item(&quot;Soap&quot;));
        _inventory.Add(new Item(&quot;Fan&quot;));
        _inventory.Add(new Item(&quot;Fish Tank&quot;));
    }

    public void GetIterator()
    {
        //this iterator is passed a list item
        //to loop through.
        return new ListIterator(_list);
    }
}

public class ArrayStore : IStore
{
    const int maxSize = 3;
    Item[] _inventory;

    public ListStore()
    {
        _inventory = new Item[maxSize];

        _inventory[0] = new Item(&quot;Shoes&quot;);
        _inventory[1] = new Item(&quot;Duct Tape&quot;);
        _inventory[2] = new Item(&quot;Venti Cappuccino&quot;);
    }

    public void GetIterator()
    {
        return new ArrayIterator(_inventory);
    }
}
&lt;/pre&gt;
Now we can loop through each element in a collection regardless of the type, as long as the class associated with the collection returns the correct Iterator type.&lt;/br&gt;
Let&#39;s see this in action.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class Program
{
    static void Main(string[] args)
    {
        IStore listStore = new ListStore();
        IStore arrayStore = new ArrayStore();
        
        IIterator listStoreIterator = listStore.GetIterator();
        IIterator arrayStoreIterator = arrayStore.GetIterator();
        
        //Now it doesn&#39;t matter what type of
        //collection our stores use in their implementation
        //as long as they know their iterator!   
        PrintInventory(listStoreIterator);
        PrintInventory(arrayStoreIterator);
    }

    //we could have also kept this in the store class and
    //done the iteration internally.
    void PrintInventory(IIterator iterator)
    {
        while (iterator.HasNext())
        {
            Item storeItem = (Item)iterator.Next();
            Console.WriteLine(storeItem.Description);
        }
    }
}
&lt;/pre&gt;
This is, as I may have mentioned before, a very simplified example with a simple version of the pattern and is not the only way to implement this or any pattern.  Just for one example we could have used generics in the iterator&#39;s Next() method to return an exact type instead of an object type.&lt;/br&gt;
We could iterate through a collection in any way as well:  backwards, skipping every other one or anything, really.&lt;/br&gt;
This is basically what c# uses when you use a foreach loop, except they use an IEnumerator interface instead of our Iterator and the IEnumerable interface for returning the appropriate iterator or enumerator, ie. the GetIterator() method in our IStore interface.  The actual &#39;foreach&#39; keyword is &lt;a href=&quot;http://en.wikipedia.org/wiki/Syntactic_sugar&quot;&gt;syntactic sugar&lt;/a&gt; for making the code easier to read or write but is basically using something like our while loop.&lt;/br&gt;
In actual c# programming you&#39;ll never actually need to make an iterator from scratch since there&#39;s such a nice one built in with such simple syntax, but I thought it might be illuminating to see how it&#39;s actually done.&lt;/br&gt;
Because this is an article about design patterns and not about all the neat features of c# I won&#39;t go into how to extend IEnumerable or IEnumerator here but here are some links for doing just that.&lt;/br&gt;
&lt;/br&gt;
Further reading:&lt;/br&gt;
&lt;/br&gt;
&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/aa288462(v=vs.71).aspx&quot;&gt;MSDN.com&lt;/a&gt;&lt;/br&gt;
&lt;a href=&quot;http://codebetter.com/davidhayden/2005/03/08/implementing-ienumerable-and-ienumerator-on-your-custom-objects/&quot;&gt;codebetter.com&lt;/a&gt;&lt;/br&gt;
&lt;a href=&quot;http://codebetter.com/davidhayden/2006/10/05/c-2-0-iterators-and-yield-keyword-custom-collection-enumerators/&quot;&gt;this article&lt;/a&gt; shows us how to code the same behavior &lt;i&gt;without&lt;/i&gt; using a seperate iterator interface, the iteration is done in the collection class using the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/9k7k7cf0(v=vs.80).aspx&quot;&gt;yield&lt;/a&gt; keyword.&lt;/br&gt;</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/6524382191693270528/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/12/iterator-pattern.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/6524382191693270528'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/6524382191693270528'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/12/iterator-pattern.html' title='The Iterator Pattern'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-2312447712628478466</id><published>2011-12-13T10:59:00.001-08:00</published><updated>2012-03-04T12:36:58.546-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><title type='text'>The Composite Pattern</title><content type='html'>The Composite pattern defines a &lt;a href=&quot;http://en.wikipedia.org/wiki/Tree_(data_structure)&quot;&gt;tree structure&lt;/a&gt;.  A tree structure is a hierarchical composition of &lt;i&gt;nodes&lt;/i&gt;, kind of a nested collection; a node can be composed of other nodes or not.  Nodes that contain other nodes are called parent-nodes while the nodes they contain are not surprisingly called child-nodes.  Some nodes are not or cannot be a parent to other nodes.  These are called leaf-nodes.  One benefit of the Composite pattern is that we can treat the entire tree, a branch (or sub-tree), or a single node equally since they&#39;re all the same data type, ie. nodes.&lt;br /&gt;
Graphically, the structure resembles a tree hence the name.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi42mSPad_7ayOAS-o445iDJhdE9MuGI12wEmWtVu7aFCrdx5jigUnHOkka8IZmU1Cyn1WMQYIr0GoqXOH1uhOW_ZHsUbW2-U_aHJGnDFIJq8brx5XgMIQJqdTEsMxjOnW8WDE3qan_Rt4/s1600/tree_01.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;300&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi42mSPad_7ayOAS-o445iDJhdE9MuGI12wEmWtVu7aFCrdx5jigUnHOkka8IZmU1Cyn1WMQYIr0GoqXOH1uhOW_ZHsUbW2-U_aHJGnDFIJq8brx5XgMIQJqdTEsMxjOnW8WDE3qan_Rt4/s400/tree_01.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
An obvious example would the be folders or directories on your hard drive, which can contain other folders, which can contain others and so on.  Files would be our leaf-nodes since they cannot contain further folders.  While searching for a file, your computer visits each folder and each file within each folder in a certain order until the desired file is found.  The process of visiting each node is called &lt;a href=&quot;http://en.wikipedia.org/wiki/Binary_tree_sort&quot;&gt;tree traversal&lt;/a&gt;.&lt;br /&gt;
There are many uses for tree structures ranging from &lt;a href=&quot;http://en.wikipedia.org/wiki/Bounding_volume_hierarchy&quot;&gt;collision detection&lt;/a&gt; to &lt;a href=&quot;http://en.wikipedia.org/wiki/Binary_tree_sort&quot;&gt;list sorting algorithms&lt;/a&gt;.&lt;br /&gt;
In this article we will use the Composite pattern to set up a tree structure and learn how to traverse it in different ways.&lt;br /&gt;
Let&#39;s take a quick look at the class diagram.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjsxK7oiwJrvwbaLMiA8eJGhHTR0g6k7gJmXLy3zAlWvgdmeyv0k6y2hdMJUa2vgcWVkibCYbEknlCq3KIVeH54erozMYw52253jsleSuwIxq0MuRVgnWc-Rt2TGzSz9jk979-KDNnBHK0/s1600/composite_pattern.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;360&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjsxK7oiwJrvwbaLMiA8eJGhHTR0g6k7gJmXLy3zAlWvgdmeyv0k6y2hdMJUa2vgcWVkibCYbEknlCq3KIVeH54erozMYw52253jsleSuwIxq0MuRVgnWc-Rt2TGzSz9jk979-KDNnBHK0/s640/composite_pattern.jpg&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
As you can see, the Node which defines the interface that our client class will be working with contains methods for adding, removing and retrieving nodes.  A leaf-node cannot contain other nodes but must still inherit from the Node interface so these methods are superfluous, moreover, there may be methods or properties that apply only to a leaf node and not a component node.  While this does break the &quot;one class, one responsibility&quot; paradigm, we get the benefit of being able to treat every part of the tree the same:  as a Node.  This can make for somewhat dangerous code if the client tries accessing something that does not apply to the object but there are ways to handle it and the ability to treat each part of the tree uniformly can be worth the added overhead.&lt;br /&gt;
For our example we&#39;ll build a mock folder tree with &quot;folders&quot; and &quot;files&quot;.  The folders will have a name and be able to contain either other folders or files.  The files will have a name and a &quot;description&quot; string field but will be unable to contain other nodes.  Likewise, our folders will have no description field.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
//The interface all nodes will implement.
interface IDirectoryNode
{
    string Name { get; }
    string Description { get; set; }
    void AddNode(IDirectoryNode node);
    void RemoveNode(IDirectoryNode node);
    IDirectoryNode[] GetNodes();
}

//Our Composite node class.
class Folder : IDirectoryNode
{
    string _name;
    List&amp;lt;IDirectoryNode&amp;gt; _nodes = new List&amp;lt;IDirectoryNode&amp;gt;();

    string Name
    {
        get { return _name; }
    }

    string Description
    {
        //This is one way of handling this.
        //we return a null description and the
        //setter does nothing.  We could have
        //thrown an exception among other solutions.
        get { return null; }
        set { }
    }

    public Folder(string name)
    {
        _name = name;
    }

    public void AddNode(IDirectoryNode node)
    {
        _nodes.Add(node);
    }

    public void RemoveNode(IDirectoryNode node)
    {
        _nodes.Remove(node);
    }

    public IDirectoryNode[] GetNodes()
    {
        return _nodes.ToArray();
    }
}

//Now for the leaf nodes.
class File : IDirectoryNode
{
    string _name;
    string _description;

    string Name
    {
        get { return _name; }
    }

    string Description
    {
        get { return _description; }
        set { _description = value; }
    }

    public File(string name, string description)
    {
        _name = name;
        _description = description;
    }

    //These do nothing.
    public void AddNode(IDirectoryNode node) { }
    public void RemoveNode(IDirectoryNode node) { }

    public IDirectoryNode[] GetNodes()
    {
        return null;
    }
}
&lt;/pre&gt;
This is good is the sense that we can create Folders and Files and build our tree but there&#39;s not much we can do with it from there.  We need a ways to traverse the tree.  There are two ways to do this:  with a &lt;a href=&quot;http://en.wikipedia.org/wiki/Depth-first_search&quot;&gt;depth-first&lt;/a&gt; search where we start at a node and visit all of its children before backtracking or a &lt;a href=&quot;http://en.wikipedia.org/wiki/Breadth-first_search&quot;&gt;breadth-first&lt;/a&gt; search where we visit all the nodes on the same level before exploring their children.&lt;br /&gt;
We will implement both as a way to search for names and descriptions.&lt;br /&gt;
First we&#39;ll make methods that perform a depth-first search and return a list of nodes that match what we&#39;re looking for.  We&#39;ll be using recursion in this example but there are iterative ways to do it as well.  Let&#39;s add these new search methods to our interface and classes.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;interface IDirectoryNode
{
    string Name { get; }
    string Description { get; set; }
    void AddNode(IDirectoryNode node);
    void RemoveNode(IDirectoryNode node);
    IDirectoryNode[] GetNodes();
    List&amp;lt;IDirectoryNode&amp;gt; SearchForNames(string name);
    List&amp;lt;IDirectoryNode&amp;gt; SearchForDescriptions(string descriptions);
}

class Folder : IDirectoryNode
{
    string _name;
    List&amp;amp;lt;IDirectoryNode&amp;amp;gt; _nodes = new List&amp;amp;lt;IDirectoryNode&amp;amp;gt;();

    string Name
    {
        get { return _name; }
    }

    string Description
    {
        get { return null; }
        set { }
    }

    public Folder(string name)
    {
        _name = name;
    }

    public void AddNode(IDirectoryNode node)
    {
        _nodes.Add(node);
    }

    public void RemoveNode(IDirectoryNode node)
    {
        _nodes.Remove(node);
    }

    public IDirectoryNode[] GetNodes()
    {
        return _nodes.ToArray();
    }

    public List&amp;lt;IDirectoryNode&amp;gt; SearchForNames(string name)
    {
        List&amp;lt;IDirectoryNode&amp;gt; results = new List&amp;lt;IDirectoryNode&amp;gt;();
        foreach (IDirectoryNode node in _nodes)
        {
            string nodeName = node.Name;

            //Some debugging to make sure we&#39;re traversing
            //the tree in the correct order.
            Console.WriteLine(
                &quot;Visiting &quot; + nodeName + &quot; &quot; + &quot;the &quot; + node.ToString());

            if (nodeName == name)
            {
                results.Add(node);
            }

            //Here is where we recurse down into the tree.
            results.AddRange(node.SearchForNames(name));
        }
        return results;
    }

    public List&amp;lt;IDirectoryNode&amp;gt; SearchForDescriptions(string description)
    {
        List&amp;lt;IDirectoryNode&amp;gt; results = new List&amp;lt;IDirectoryNode&amp;gt;();

        foreach (IDirectoryNode node in _nodes)
        {
            string nodeDescription = node.Description;

            //Some debugging to make sure we&#39;re traversing
            //the tree in the correct order.
            Console.WriteLine(
                &quot;Visiting &quot; + node.Name + &quot; &quot; + &quot;the &quot; + node.ToString());

            if (nodeDescription != null &amp;amp;&amp;amp;
                nodeDescription == description)
            {
                results.Add(node);
            }

            results.AddRange(node.SearchForDescriptions(description));
        }

        return results;
    }
}

class File : IDirectoryNode
{
    string _name;
    string _description;

    string Name
    {
        get { return _name; }
    }

    string Description
    {
        get { return _description; }
        set { _description = value; }
    }

    public File(string name, string description)
    {
        _name = name;
        _description = description;
    }

    //These do nothing.
    public void AddNode(IDirectoryNode node) { }
    public void RemoveNode(IDirectoryNode node) { }

    public IDirectoryNode[] GetNodes()
    {
        return null;
    }

    //These are not applicable so we just
    //return an empty list.
    public List&amp;lt;IDirectoryNode&amp;gt; SearchForNames(string name)
    {
        return new List&amp;lt;IDirectoryNode&amp;gt;();
    }

    public List&amp;lt;IDirectoryNode&amp;gt; SearchForDescriptions(string description)
    {
        return new List&amp;lt;IDirectoryNode&amp;gt;();
    }
}
&lt;/pre&gt;
Let&#39;s test this out by building a tree and searching for some things.&lt;br /&gt;

&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class Program
{
    static void Main(string[] args)
    {
        //Building our tree...
        IDirectoryNode documentsFolder = new Folder(&amp;quot;Documents&amp;quot;);
        IDirectoryNode gamesFolder = new Folder(&amp;quot;Games&amp;quot;);
        IDirectoryNode musicFolder = new Folder(&amp;quot;Music&amp;quot;);
        IDirectoryNode someGame = new File(&amp;quot;Fun Time Game&amp;quot;, &amp;quot;Whooo, fun!&amp;quot;);
        IDirectoryNode someSong = new File(&amp;quot;Happy Song&amp;quot;, &amp;quot;La la la&amp;quot;);
        IDirectoryNode textDocument = new File(&amp;quot;Journal&amp;quot;, &amp;quot;I had a good day!&amp;quot;);
        IDirectoryNode textDocumentTwo = new File(&amp;quot;Journal&amp;quot;, &amp;quot;I had a bad day!&amp;quot;);

        documentsFolder.AddNode(gamesFolder);
        documentsFolder.AddNode(musicFolder);
        documentsFolder.AddNode(textDocument);
        gamesFolder.AddNode(someGame);
        musicFolder.AddNode(someSong);
        musicFolder.AddNode(textDocumentTwo);

        //Now we can do searches.
        List&amp;lt;idirectorynode&amp;gt; nameResults = new List&amp;lt;idirectorynode&amp;gt;();
        nameResults = 
            documentsFolder.SearchForNames(&amp;quot;Journal&amp;quot;);

        foreach (IDirectoryNode node in nameResults)
        {
            Console.WriteLine(node.Name);
        }

        Console.WriteLine();

        List&amp;lt;idirectorynode&amp;gt; descriptionResults = 
            documentsFolder.SearchForDescriptions(&amp;quot;La la la&amp;quot;);

        foreach (IDirectoryNode node in descriptionResults)
        {
           Console.WriteLine(node.Name);
        }

        Console.ReadLine();
   }
}
&lt;/pre&gt;

&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgN9mr9stmRFRQx7P8xzvclQWt9pg2-16UrGovipugolxeaDejjI3JbdLQCGPxq-pmEseHzwlA4QOoebkBznD5HWCMnfY2d7AjNqJ6J1HclplP9gnIjPN3uuz2-4rSv-0HCnYsyRvCtldE/s1600/composite_output.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;296&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgN9mr9stmRFRQx7P8xzvclQWt9pg2-16UrGovipugolxeaDejjI3JbdLQCGPxq-pmEseHzwlA4QOoebkBznD5HWCMnfY2d7AjNqJ6J1HclplP9gnIjPN3uuz2-4rSv-0HCnYsyRvCtldE/s640/composite_output.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
As you can see, each child is being completely explored before moving on to the next.&lt;br /&gt;
Now let&#39;s try to make the breadth-depth search.&lt;br /&gt;
We&#39;ll be using a queue to keep track of the nodes we still need to explore.  Once a node in the queue has been explored, it&#39;s removed from line and its children are added.  This is repeated until the queue is empty.&lt;br /&gt;
This image from &lt;a href=&quot;http://www.wikipedia.org/&quot;&gt;wikipedia&lt;/a&gt; illustrates the algorithm beautifully.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;http://upload.wikimedia.org/wikipedia/commons/4/46/Animated_BFS.gif&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;373&quot; src=&quot;http://upload.wikimedia.org/wikipedia/commons/4/46/Animated_BFS.gif&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
The grey nodes are the ones currently enqueued and the black nodes are the ones being visited.&lt;br /&gt;
For the sake of brevity I will write out just search methods.  The interface needs the new stubs as well.&lt;br /&gt;

&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;//The breadth-first Folder search implementation.
public List&amp;lt;IDirectoryNode&amp;gt; BreadthFirstNameSearch(string name)
{
    List&amp;lt;IDirectoryNode&amp;gt; result = new List&amp;lt;IDirectoryNode&amp;gt;();
    Queue&amp;lt;IDirectoryNode&amp;gt; searchQueue = new Queue&amp;lt;IDirectoryNode&amp;gt;();

    foreach (IDirectoryNode node in _nodes)
    {
        searchQueue.Enqueue(node);
    }

    while (searchQueue.Count != 0)
    {
        IDirectoryNode currentNode = searchQueue.Dequeue();

        Console.WriteLine(
            &quot;Examining &quot; + currentNode.ToString() + &quot;, &quot; + currentNode.Name);

        if (currentNode.Name == name)
        {
            result.Add(currentNode);                   
        }
        foreach (IDirectoryNode node in currentNode.GetNodes())
        {
            searchQueue.Enqueue(node);
        }
    }

    return result;
}

public List&amp;lt;IDirectoryNode&amp;gt; BreadthFirstDescriptionSearch(string description)
{
    List&amp;lt;IDirectoryNode&amp;gt; result = new List&amp;lt;IDirectoryNode&amp;gt;();
    Queue&amp;lt;IDirectoryNode&amp;gt; searchQueue = new Queue&amp;lt;IDirectoryNode&amp;gt;();

    foreach (IDirectoryNode node in _nodes)
    {
        searchQueue.Enqueue(node);
    }

    while (searchQueue.Count != 0)
    {
        IDirectoryNode currentNode = searchQueue.Dequeue();

        Console.WriteLine(
            &quot;Examining &quot; + currentNode.ToString() + &quot;, &quot; + currentNode.Name);


        if (currentNode.Description != null &amp;amp;&amp;amp;
            currentNode.Description == description)
        {
            result.Add(currentNode);                   
        }

        foreach (IDirectoryNode node in currentNode.GetNodes())
        {
            searchQueue.Enqueue(node);
        }
    }

    return result;
}
&lt;/pre&gt;
Since we cannot search files their implementations simply return empty lists.&lt;br /&gt;
If we had used a stack instead of a queue this would have resulting in a depth-first search.

Testing this out:&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class Program
{
    static void Main(string[] args)
    {
        IDirectoryNode documentsFolder = new Folder(&quot;Documents&quot;);
        IDirectoryNode gamesFolder = new Folder(&quot;Games&quot;);
        IDirectoryNode musicFolder = new Folder(&quot;Music&quot;);
        IDirectoryNode someGame = new File(&quot;Fun Time Game&quot;, &quot;Whooo, fun!&quot;);
        IDirectoryNode someSong = new File(&quot;Happy Song&quot;, &quot;La la la&quot;);
        IDirectoryNode textDocument = new File(&quot;Journal&quot;, &quot;I had a good day!&quot;);
        IDirectoryNode textDocumentTwo = new File(&quot;Journal&quot;, &quot;I had a bad day!&quot;);

        documentsFolder.AddNode(gamesFolder);
        documentsFolder.AddNode(musicFolder);
        documentsFolder.AddNode(textDocument);
        gamesFolder.AddNode(someGame);
        musicFolder.AddNode(someSong);
        musicFolder.AddNode(textDocumentTwo);

        List&amp;lt;IDirectoryNode&amp;gt; nameResults = new List&amp;lt;IDirectoryNode&amp;gt;();
        nameResults = 
            documentsFolder.BreadthFirstNameSearch(&quot;Journal&quot;);

        foreach (IDirectoryNode node in nameResults)
        {
            Console.WriteLine(node.Name);
        }

        Console.WriteLine();

        List&amp;lt;IDirectoryNode&amp;gt; descriptionResults = 
            documentsFolder.BreadthFirstDescriptionSearch(&quot;La la la&quot;);

        foreach (IDirectoryNode node in descriptionResults)
        {
            Console.WriteLine(node.Name);
        }

        Console.ReadLine();
    }
}
&lt;/pre&gt;
&lt;/br&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTLtFcEBPImHwGarJAG4Dr6_RVRuQfTmQcFk2lHt6CkMz92kYneOdcrBwSdnbk-tALjKvpIWwjUVRpgexLLixA2rrN8pzOONk0DnS8ftS4XK0jsWCA9o9E2_J1cSVrccbwC7qRcvHTH8U/s1600/composite_output.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;292&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTLtFcEBPImHwGarJAG4Dr6_RVRuQfTmQcFk2lHt6CkMz92kYneOdcrBwSdnbk-tALjKvpIWwjUVRpgexLLixA2rrN8pzOONk0DnS8ftS4XK0jsWCA9o9E2_J1cSVrccbwC7qRcvHTH8U/s640/composite_output.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/br&gt;
Notice the different order in which each node is visited.&lt;/br&gt;
This is just one very simple way to do this, there are more sophisticated and generalized ways of going about this but the algorithms themselves are the same or very similar.&lt;/br&gt;
&lt;/br&gt;
And this concludes my Design Pattern series (for now)!  Next I&#39;ll start focusing more on collision algorithms and game physics.&lt;/br&gt;
I hope you&#39;ve enjoyed reading them as much as I have writing them!&lt;/br&gt;
Feel free to leave comments, questions, corrections or what have you.
Thanks!</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/2312447712628478466/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/12/composite-pattern.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/2312447712628478466'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/2312447712628478466'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/12/composite-pattern.html' title='The Composite Pattern'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi42mSPad_7ayOAS-o445iDJhdE9MuGI12wEmWtVu7aFCrdx5jigUnHOkka8IZmU1Cyn1WMQYIr0GoqXOH1uhOW_ZHsUbW2-U_aHJGnDFIJq8brx5XgMIQJqdTEsMxjOnW8WDE3qan_Rt4/s72-c/tree_01.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-8967028622940634230</id><published>2011-12-13T10:42:00.000-08:00</published><updated>2012-03-04T12:37:52.475-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><title type='text'>The Command Pattern</title><content type='html'>The Command pattern is way to separate a request for an action to be performed from the object that actually performs the action.  It encapsulates method invocation allowing one to &lt;i&gt;parameterize&lt;/i&gt; or change the object making the invocation on the fly.&lt;br /&gt;
It&#39;s also really neat.&lt;br /&gt;
First let&#39;s look at a very simple situation where we may need something like this.&lt;br /&gt;
Let&#39;s say we have two types of objects, a glass bottle and I don&#39;t know, a wooden box.  If we drop the glass bottle it shatters instantly and is gone.  The box however can be dropped a few times before breaking.&lt;br /&gt;
Let&#39;s see how two simple versions of these classes may be set up.
&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class Bottle
{
    bool _broken = false;

    public void Break()
    {
        if (_broken)
        {
            Console.WriteLine(&quot;The bottle is already broken&quot;);
        }
        else
        {
            _broken = true;
            Console.WriteLine(&quot;The bottle shatters&quot;);
        }
    }
}

class Box
{
    bool _broken = false;
    int _hitPoints = 3;

    public void Hit()
    {
        if (_broken)
        {
            Console.WriteLine(&quot;The box is broken irreparably.&quot;)
        }
        else
        {
            _hitPoints--;
            if (_hitPoints &amp;lt;= 0)
            {
                _broken = true;
                Console.WriteLine(&quot;The box breaks.&quot;)
            }
        }
    }
}
&lt;/pre&gt;
&lt;br /&gt;
The methods Hit() and Break() are clearly fairly different from one another other besides the fact that they are both void and parameterless and they are both probably going to called during very similar situations.&lt;br /&gt;
So how would a client class have to deal with this?  We can set up a very simple situation to demonstrate the problems that arise.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class Program
{        
    static void Main(string[] args)
    {
        Bottle bottle = new Bottle();
        Box box = new Box();
        string input = &quot;&quot;;

        while (input.ToLower() != &quot;q&quot;)
        {
            Console.WriteLine(
                &quot;Press B to drop the (B)ottle, O to drop the B(o)x or Q to (Q)uit.&quot;);
            input = Console.ReadLine();

            if (input.ToLower() == &quot;b&quot;)
            {
                bottle.Break();
            }
            else if (input.ToLower() == &quot;o&quot;)
            {
                box.Drop();
            }               
        }
    }
}
&lt;/pre&gt;
&lt;br /&gt;
It works now but this clearly will not do.&lt;br /&gt;
The above code is pretty bad on a number of levels.  For starters the more objects added that can be dropped, the bulkier and just awful our client class becomes.&lt;br /&gt;
Secondly the client class (in this over simplified case it&#39;s the Program class) has too many responsibilities:  accepting and interpreting user input and responding to the input (that problem specifically I&#39;m not actually going over in this article but it&#39;s something to think about).  A general design guideline is:  one class, one responsibility.  Moreover, in some cases our client class may not even have access to Bottles and Boxes as they may be hidden.&lt;br /&gt;
The Command pattern helps by introducing a new type of object called a command object which will contain a single method, Execute().&lt;br /&gt;
It&#39;s not an easy pattern to grasp at first (it wasn&#39;t for me anyway) but it&#39;s usefulness became apparent once I did.&lt;br /&gt;
Before we dive into the code, let&#39;s look at a real world analogy that mirrors how the command pattern works.&lt;br /&gt;
In a cafe we can can order many different types of beverages and each have a different procedure for making it.  We give our drink order to the chashier who writes down the specifics of the drink we want.  The slip encapsulates our drink order.  It is then passed off to the barrista who interprets what&#39;s written on the slip and makes your drink.&lt;br /&gt;
You, the customer, know how to order a drink so you create a command (your order) and pass it off to the chashier.  The chashier in turn takes the command you created and passes it to the barrista who makes the drink.  Most real life cafe cashiers, of course, must also need to know how to prepare a drink, but for our purposes they do not and have completely separate responsibilities.&lt;br /&gt;
Now let&#39;s look at the various pieces of the pattern and see how they fit into the cafe scenario.&lt;br /&gt;
The Command pattern has a client class which is responsible for creating our command objects (the customer), the client then passes the command to the &lt;i&gt;invoker&lt;/i&gt;.  The invoker contains one or more references to a command objects which the client sets.  Now the invoker can invoke one of these commands at any time, which is like having the barrista make the drinks.  Since the invoker can call these methods at any time, we can even set up ques of commands to be executed in a certain order.&lt;br /&gt;
Moving back to our Box/Bottle issue, let&#39;s take a look at some code now to hopefully help gel the whole idea.&lt;br /&gt;
Starting with our command interface and objects:&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;interface ICommand
{
    void Execute();
}

class BottleDropCommand : ICommand
{
    Bottle _bottle;

    public BottleDropCommand(Bottle bottle)
    {
        _bottle = bottle;
    }

    public void Execute()
    {
        _bottle.Break();
    }
}

class BoxDropCommand : ICommand
{
    Box _box;

    public BoxDropCommand(Box box)
    {
        _box = box;
    }

    public void Execute()
    {
        _box.Drop();
    }
}
&lt;/pre&gt;
&lt;br /&gt;
Now we need our invoker, a sort of item dropping interface to work with.  This will hold two ICommand objects that we can execute at any time.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class SimpleItemDropper
{
    //We have two ICommand&#39;s at the moment but this can be extended
    //deal with any amount.
    ICommand _commandOne;
    ICommand _commandTwo

    public void SetCommandOne(ICommand command)
    {
        _commandOne = command;
    }

    public void SetCommandTwo(ICommand command)
    {
        _commandTwo = cammand;
    }
    
    //The item dropper doesn&#39;t care if it&#39;s a box or a bottle, it just
    //executes the set command!
    public void ExecuteOne()
    {
        _commandOne.Execute();
    }

    public void ExecuteTwo()
    {
        _commandTwo.Execute();
    }
}
&lt;/pre&gt;
&lt;br /&gt;
Now our client class becomes:&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class Program
{        
    static void Main(string[] args)
    {
        Bottle bottle = new Bottle();
        Box box = new Box();
        SimpleItemDropper itemDropper = new SimpleItemDropper();

        ICommand dropBottle = new BottleDropCommand(bottle);
        ICommand dropBox = new BoxDropCommand(box);

        itemDropper.SetCommandOne(dropBottle);
        itemDropper.SetCommandTwo(dropBox);

        itemDropper.ExecuteOne();
        itemDropper.ExecuteOne();
        itemDropper.ExecuteTwo();
        itemDropper.ExecuteTwo();
        itemDropper.ExecuteTwo();
        itemDropper.ExecuteTwo();
        itemDropper.ExecuteTwo();
        
        Console.ReadLine();
    }
}
&lt;/pre&gt;
Our output should look something like this:
&lt;/br&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgBiDyExFqyo6uzL40KrVZ0TsSMjXxnN51WoTeOuE5HVnY5mWAsaw-lbcigi2Ru7jCACs3fn9JrO5JBfQwRIh4vPhZIeMNX3d5nRHeRcBiaZjDpp_h2QYeLNc395SbvJopm1VbSePr2fyo/s1600/command_tutorial_output.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;296&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgBiDyExFqyo6uzL40KrVZ0TsSMjXxnN51WoTeOuE5HVnY5mWAsaw-lbcigi2Ru7jCACs3fn9JrO5JBfQwRIh4vPhZIeMNX3d5nRHeRcBiaZjDpp_h2QYeLNc395SbvJopm1VbSePr2fyo/s640/command_tutorial_output.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/br&gt;
And that&#39;s the Command pattern, a great way to&lt;/br&gt; 
* encapsulate method invocation&lt;/br&gt;
* separate the invocation of a method from the object receiving the invocation request.&lt;/br&gt;
&lt;/br&gt;
There are many more great uses of this pattern as it can do some very clever things.  I suggest investigating further and more importantly experimenting with the pattern yourself.
This is a very simple (and useless) example and the pattern can be tweaked and extended to your needs (just like any pattern!) but I&#39;ve successfully conveyed how powerful this pattern is.&lt;/br&gt;
Thanks for reading!</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/8967028622940634230/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/12/command-pattern.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/8967028622940634230'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/8967028622940634230'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/12/command-pattern.html' title='The Command Pattern'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgBiDyExFqyo6uzL40KrVZ0TsSMjXxnN51WoTeOuE5HVnY5mWAsaw-lbcigi2Ru7jCACs3fn9JrO5JBfQwRIh4vPhZIeMNX3d5nRHeRcBiaZjDpp_h2QYeLNc395SbvJopm1VbSePr2fyo/s72-c/command_tutorial_output.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-2467891671941393184</id><published>2011-12-09T08:54:00.001-08:00</published><updated>2012-03-04T12:38:13.533-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><title type='text'>The Facade Pattern</title><content type='html'>The Facade pattern is an incredibly simple pattern.  In fact, there&#39;s a good chance you&#39;ve implemented it in your projects before without being aware that you were using a design pattern.&lt;/br&gt;
This is a short and simple article, but it is a very useful pattern.
The Facade pattern simplifies an interface.&lt;/br&gt;
A system can be made up of many classes, with complicated interdependencies, each with their own unique interface.&lt;/br&gt;
The Facade pattern is a way to simplify how the client interacts with these objects.&lt;/br&gt;
Let&#39;s say we have a bunch a classes that control various appliances in the house.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class KitchenLight
{
    public void On()
    {
        Console.WriteLine(&quot;Kitchen light on.&quot;);
    }
    
    public void Off()
    {
        Console.WriteLine(&quot;Kitchen light off.&quot;);
    }
}

class LivingRoomLight
{
    public void On()
    {
        Console.WriteLine(&quot;Living room light on.&quot;);
    }

    public void Off()
    {
        Console.WriteLine(&quot;Living room light off.&quot;);
    }
}

class TV
{
    int _channel;

    public int Channel
    {
        get { return _channel; }
    }

    public void On()
    {
        Console.WriteLine(&quot;TV on.&quot;);
    }

    public void Off()
    {
        Console.WriteLine(&quot;TV off.&quot;);
    }

    public void ChangeChannel(int channel)
    {
        _channel = channel;
    }
}

class DVD
{
    string _name;
    
    public string Name
    {
        get { return _name; }
    }

    public DVD(string name)
    {
        _name = name;
    }
}

class DVDPlayer
{
    TV _tv;
    DVD _dvd;

    public DVDPlayer(TV tv)
    {
        _tv = tv;
    }

    public void On()
    {
        Console.WriteLine(&quot;DVD on.&quot;);
    }

    public void Off()
    {
        Console.WriteLine(&quot;DVD off.&quot;);
    }

    public void PlayMovie()
    {
        if (_tv.Channel == 4)
        {
            if (_dvd != null)
            {
                Console.WriteLine(&quot;Playing &quot; + _dvd.Name);
            }
            else
            {
                Console.WriteLine(&quot;No disc in player.&quot;);
            }
        }
        else
        {
            Console.WriteLine(&quot;TV must be on channel 4.&quot;);
        }
    }

    public void InsertDVD(DVD dvd)
    {
        Console.WriteLine(&quot;Inserting &quot; + _dvd.Name);
        _dvd = dvd;
    }    
}
&lt;/pre&gt;
Seems simple but now what if we want to watch a movie?  From our client class we&#39;d have to....&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class Program
{
    static void Main(string[] args)
    {
        KitchenLight kitchenLight = new KitchenLight();
        LivingRoomLight livingRoomLight = new LivingRoomLight();
        TV tv = new TV();
        DVDPlayer dvdPlayer = new DVDPlayer(tv);
        DVD dvd = new DVD(&quot;Memento&quot;);

        //We&#39;d have to do all this!
        kitchenLight.Off();
        tv.On();
        tv.ChangeChannel(4);
        dvdPlayer.On();
        dvdPlayer.InsertDVD(dvd);
        livingRoomLight.Off();
        dvdPlayer.PlayMovie();
    }
}
&lt;/pre&gt;
That&#39;s a lot just to watch a dvd.  And when we&#39;re done, we&#39;ll have to do the whole thing again in reverse.&lt;/br&gt;
And, oh no!  We just got an XBox and a new game!&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class XBoxGame
{
    string _name;

    public string Name
    {
        get { return _name; }
    }

    public XBoxGame(string name)
    {
        _name = name;
    }
}

class XBox
{
    TV _tv;
    XBoxGame _game;

    public DVDPlayer(TV tv)
    {
        _tv = tv;
    }

    public void On()
    {
        Console.WriteLine(&quot;XBox on.&quot;);
    }

    public void Off()
    {
        Console.WriteLine(&quot;XBox off.&quot;);
    }

    public void PlayGame()
    {
        if (_tv.Channel == 4)
        {
            if (_game != null)
            {
                Console.WriteLine(&quot;Playing &quot; + _game.Name);
            }
            else
            {
                Console.WriteLine(&quot;No game in console.&quot;);
            }
        }
        else
        {
            Console.WriteLine(&quot;TV must be on channel 4.&quot;);
        }
    }

    public void InsertGame(XBoxGame game)
    {
        Console.WriteLine(&quot;Inserting &quot; + _game.Name);
        _game = game;
    }    
}
&lt;/pre&gt;
This is getting ridiculous.&lt;/br&gt;
Luckily the facade pattern can help.  A facade is basically a class that holds all these interconnected classes and knows how to interact with them.&lt;/br&gt;
Let&#39;s see how.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class HomeApplianceFacade
{
    TV _tv;
    DVDPlayer _dvdPlayer;
    KitchenLight _kitchenLight;
    LivingRoomLight _livingRoomLight;
    XBox _xbox;

    public HomeApplianceFacade(
        TV tv,
        DVDPlayer dvdPlayer,
        KitchenLight kitchenLight,
        LivingRoomLight livingRoomLight,
        XBox xbox)
    {
        _tv = tv;
        _dvdPlayer = dvdPlayer;
        _kitchenLight = kitchenLight;
        _livingRoomLight = livingRoomLight;
        _xbox = xbox;
    }

    public void WatchMovie(DVD dvd)
    {
        kitchenLight.Off();
        tv.On();
        tv.ChangeChannel(4);
        dvdPlayer.On();
        dvdPlayer.InsertDVD(dvd);
        livingRoomLight.Off();
        dvdPlayer.PlayMovie();
    }

    public void FinishedMovie()
    {
        _livingRoomLight.On();
        _dvdPlayer.Off();
        _tv.Off();
        _kitchenLight.On();
    }

    public void PlayGame(XBoxGame game)
    {
        _kitchenLight.Off();
        _tv.On();
        _tv.ChangeChannel(4);
        _xBox.On();
        _xBox.InsertGame(game);
        _livingRoomLight.Off();
        _xBox.PlayGame();
    }

    public void FinishedPlayingGame()
    {
        _livingRoomLight.On();
        _xBox.Off();
        _tv.Off();
        _kitchenLight.On();

    }
}
&lt;/pre&gt;
Now we have a few methods that deal with all the low level classes correctly so we don&#39;t have to deal with it every time.&lt;/br&gt;
When we want to watch a movie or something we deal directly with the Facade we&#39;ve created.  We can still access the low level stuff if we want to, but the simplified interface is there if we need it.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class Program
{
    static void Main(string[] args)
    {
        //We still have to &#39;install&#39; our system.
        KitchenLight kitchenLight = new KitchenLight();
        LivingRoomLight livingRoomLight = new LivingRoomLight();
        TV tv = new TV();
        DVDPlayer dvdPlayer = new DVDPlayer(tv);

        //But now we have a facade to handle all the complicated stuff.
        HomeApplianceFacade applianceFacade =
            new HomeApplianceFacade(tv, dvdPlayer, kitchenLight, livingRoomLight, xBox);

        //Our simplified interface.
        applianceFacade.WatchMovie(new DVD(&quot;Memento&quot;));
        applianceFacade.FinishedMovie();
        applianceFacade.PlayGame(new XBoxGame(&quot;Skyrim&quot;));
        applianceFacade.FinishedPlayingGame();
    }
}
&lt;/pre&gt;
And that&#39;s pretty much it!  The Facade pattern; a great way to create a unified interface to simplify a complicated subsystem.&lt;/br&gt;
&lt;/br&gt;
Thanks, as always for reading and I hope you enjoyed the article.&lt;/br&gt;</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/2467891671941393184/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/12/facade-pattern.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/2467891671941393184'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/2467891671941393184'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/12/facade-pattern.html' title='The Facade Pattern'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-6789832723112156319</id><published>2011-12-04T20:47:00.001-08:00</published><updated>2012-03-04T12:38:36.525-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Game Physics"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><category scheme="http://www.blogger.com/atom/ns#" term="XNA"/><title type='text'>Intersection Testing in 2D</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
Whether or not you plan on making a game with a fancy physics engine you&#39;ll more than likely still have to check for collisions at some point.  In games, a collision is generated when two or more pieces of geometry are intersecting.  Testing to see if two geometrical figures are in intersection (or sometimes called interpenetration) can be a complicated and expensive task.&lt;br /&gt;
&lt;br /&gt;
In this article I will go over several common shapes in 2 dimensions and investigate how we can test a pair of them for intersection.  We will also discuss a general method for testing shapes of a certain class.&lt;br /&gt;
Responding to the intersections (and finding them fast) is beyond the scope of this article.  This article is concerned only with checking for intersection but is still a pretty large subject.&lt;br /&gt;
&lt;br /&gt;
If you&#39;re a little shaky on your mathematics, then I suggest that you refresh yourself thoroughly at least.  A good understanding of high school math as well as a lot of college level stuff is integral in the development of games.  There&#39;s no way around it.&lt;br /&gt;
That said, I am not trying to scare you so I will try to be as gentle as possible.  The more you do it the easier it gets.&lt;br /&gt;
&lt;br /&gt;
We&#39;ll go over the 2D shapes covered briefly then investigate how to test for an intersection between pairs of them.&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;









The Circle&lt;/h2&gt;
&lt;br /&gt;
A circle is the set of points in the plane that are the same distance from a common point called its &lt;i&gt;center&lt;/i&gt;.  This distance from a point in the set to the center is its &lt;i&gt;radius&lt;/i&gt;.&lt;br /&gt;
We can denote the center of a circle by a point in space with its x and y values, or by a &lt;i&gt;vector&lt;/i&gt; and its radius by a &lt;i&gt;real number&lt;/i&gt;.  Although we&#39;ll be working with floats or doubles instead of the infinitude of the reals.&lt;br /&gt;
Now we can represent a circle by the equation:&lt;br /&gt;
&lt;div class=&quot;latexparse&quot;&gt;
$(x-c_x)^2+(y-c_y)^2=r^2$&lt;/div&gt;
Where,&lt;br /&gt;
&lt;div class=&quot;latexparse&quot;&gt;
$C = (c_x, c_y)$&lt;/div&gt;
is the circle&#39;s center point with its x and y components and r is the radius.&lt;br /&gt;
Every pair of reals, x and y that satisfy this equation for a given real number, r and a point C, is a point on the (unique) circle of radius, r centered at, C.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2PpAlrF8iFA6b9xhP0_kt4mCTZnD75EgGsuTFjUoDlkRtLOft_mTD4ItwUcnHMzgCWlOCILuWJeEIZyCB3LTaeEjCu4O-uNFK6AVH3OUKfcjdmDJJJqvDlCjtcLbDU7H2D2iqD9lv0kc/s1600/circle.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em; text-align: center;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;200&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2PpAlrF8iFA6b9xhP0_kt4mCTZnD75EgGsuTFjUoDlkRtLOft_mTD4ItwUcnHMzgCWlOCILuWJeEIZyCB3LTaeEjCu4O-uNFK6AVH3OUKfcjdmDJJJqvDlCjtcLbDU7H2D2iqD9lv0kc/s200/circle.png&quot; width=&quot;200&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2PpAlrF8iFA6b9xhP0_kt4mCTZnD75EgGsuTFjUoDlkRtLOft_mTD4ItwUcnHMzgCWlOCILuWJeEIZyCB3LTaeEjCu4O-uNFK6AVH3OUKfcjdmDJJJqvDlCjtcLbDU7H2D2iqD9lv0kc/s1600/circle.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;br /&gt;&lt;/a&gt;&lt;/div&gt;
We can represent a circle simply by storing its position and radius into memory.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class Circle
{
    public Vector2 Center;
    public float Radius;
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;h2&gt;










Rectangle&lt;/h2&gt;
&lt;br /&gt;
We&#39;ll be dealing with two kinds of rectangles here, &lt;i&gt;axis-aligned&lt;/i&gt;, often called &lt;i&gt;bounding boxes&lt;/i&gt; and non-axis-aligned.  When we&#39;re referring to the axis-aligned situation we&#39;ll specifically say so, otherwise we&#39;ll just say &#39;rectangle&#39; or &#39;box&#39;.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwfIFuJjsgH8oqaMdvm-icdhWOKHkZ_82byvG4nw_zlL_AqZ9x2-xrFBlgu0IBPBVj6F_hXOG3aQq2m1tP9tLnLor-7aTuQjB3caXWvu5ATmz7KxVFxlOAc8oVc33ietuEwA1prZtImug/s1600/axis_aligned_and_non_boxes.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwfIFuJjsgH8oqaMdvm-icdhWOKHkZ_82byvG4nw_zlL_AqZ9x2-xrFBlgu0IBPBVj6F_hXOG3aQq2m1tP9tLnLor-7aTuQjB3caXWvu5ATmz7KxVFxlOAc8oVc33ietuEwA1prZtImug/s320/axis_aligned_and_non_boxes.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Axis-aligned boxes have each of their edges parallel to the coordinate axis while the regular boxes do not.&lt;br /&gt;
The built-in Rectangle structure that comes with XNA is axis-aligned.&lt;br /&gt;
Many calculations become much simpler when we&#39;re dealing with rectangles that are axis-aligned but we&#39;ll be looking at both cases.&lt;br /&gt;
An axis-aligned box simply has a location (usually referring to the upper-left corner), a width and a height.  No other information is needed to describe the bounding box.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class AxisAlignedBox
{
    public Vector2 Position;
    public float Width;
    public float Height;
}
&lt;/pre&gt;
In the other case we need to store a position, a width, a height and an &lt;i&gt;angle&lt;/i&gt; of rotation.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOKyadCtmaHFR5yE4yANlQ_pMa5d9WEcF_kXKDsSIQFPyDAqR82APQH25-2mVIjJL8en5Db77ot4HWE3MYvHOEm31fyaB9rYS_KXI33_5YW5IpO4d861VJ5FnfTaygR6LHSd1R3DlyFfA/s1600/rotated_rectangle.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;443&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOKyadCtmaHFR5yE4yANlQ_pMa5d9WEcF_kXKDsSIQFPyDAqR82APQH25-2mVIjJL8en5Db77ot4HWE3MYvHOEm31fyaB9rYS_KXI33_5YW5IpO4d861VJ5FnfTaygR6LHSd1R3DlyFfA/s640/rotated_rectangle.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Here, P is the position and,&lt;br /&gt;
&lt;div class=&quot;latexparse&quot;&gt;
$\theta$
&lt;/div&gt;
(pronounced &#39;theta&#39;) is the angle.  A positive angle is measured counter-clockwise.&lt;br /&gt;
In XNA, by default the origin is the upper-left hand corner of the sprite we&#39;re rotating but we&#39;ll normally be rotating a box about it&#39;s center or perhaps it&#39;s center of mass.  We&#39;ll see how to deal with these things later on.&lt;br /&gt;
&lt;/br&gt;
&lt;h2&gt;










Other Polygons&lt;/h2&gt;
&lt;br /&gt;
There are &lt;a href=&quot;http://en.wikipedia.org/wiki/N-gon%22&quot;&gt;many different polygons&lt;/a&gt; and the only ones we&#39;ll look at in any depth are the &lt;a href=&quot;http://en.wikipedia.org/wiki/Convex_polyhedra&quot;&gt;convex polygons&lt;/a&gt;.  This is where it get very complicated very quickly and we&#39;ll briefly discuss a general method of testing.&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;










Circle-circle test&lt;/h2&gt;
&lt;br /&gt;
Two circles in the plane don&#39;t intersect if the distance between their centers is greater than the sum of their radii.  That is,&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;latexparse&quot;&gt;
$d(c1, c2) = \sqrt{(c1_x-c2_x)^2+(c1_y-c2_y)^2} &amp;gt; r1+r2$&lt;/div&gt;
&lt;br /&gt;
d(c1, c2) is the distance between the centers and c1 and c2 are the centers subscripted by their x or y component.&lt;br /&gt;
&lt;br /&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhnVLczXWq4gsqlMnXZHQfLDeDzTo2MTtTQ6X79W87LDzzlAnHHDcMm6mNW7cXHi9x_BKC6KUU4ogYMotMtRVwqQpiFvq24eam03BemRi2wFm4nMjC09bPv4BkedEAHEc7oOMORwk78OL8/s1600/circlesnotintersect.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;205&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhnVLczXWq4gsqlMnXZHQfLDeDzTo2MTtTQ6X79W87LDzzlAnHHDcMm6mNW7cXHi9x_BKC6KUU4ogYMotMtRVwqQpiFvq24eam03BemRi2wFm4nMjC09bPv4BkedEAHEc7oOMORwk78OL8/s400/circlesnotintersect.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;The distance from center to center is larger than their combined radii. &amp;nbsp;No intersection.&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj33SL8_QL4DNtGApwBqPDu1HzeK-zfewe2nOTeEId38eOGUs0VF4O9INrbOdP05dUEXS6jfPB_QcEPl_yoSSOX80p21aYL_P9wM_g4U3VSvYjf_AuIBeoLKERa0U6os_yc5CPaetgZDfU/s1600/circlesintersect.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;263&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj33SL8_QL4DNtGApwBqPDu1HzeK-zfewe2nOTeEId38eOGUs0VF4O9INrbOdP05dUEXS6jfPB_QcEPl_yoSSOX80p21aYL_P9wM_g4U3VSvYjf_AuIBeoLKERa0U6os_yc5CPaetgZDfU/s400/circlesintersect.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;The distance between their centers is smaller than the sum of their radii, hence, they intersect.&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;br /&gt;
To avoid expensive square root computations we usually compare the square of the distance to the square of the sum of the radii since the inequality remains true.&lt;br /&gt;
&lt;div class=&quot;latexparse&quot;&gt;
$(c1_x-c2_x)^2+(c1_y-c2_y)^2 &amp;gt;(r1+r2)^2$
&lt;/div&gt;
the above is true if the circles don&#39;t touch.&lt;br /&gt;
Adding this to our Circle class,
&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class Circle
{
    public Vector2 Center;
    public float Radius;

    //Returns true if this circle intersects another
    //or they are &#39;just touching&#39;.
    public bool Intersects(Circle circle)
    {
        Vector2 center1 = Center;
        Vector2 center2 = circle.Center;
        float radius1 = Radius;
        float radius2 = circle.Radius;

        float distanceSquared = 
            (float)Math.Pow((center1.X - center2.X), 2) +
            (float)Math.Pow((center1.Y - center2.Y), 2);
        float sumOfRadiiSquared = (float)Math.Pow(radius1 + radius2, 2);
        
        if (distanceSquared &amp;lt;= sumOfRadiiSquared)
        {
            return true;
        }
        else
        {
            return false;
        } 
    }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;h2&gt;










Box-box test (axis aligned)&lt;/h2&gt;
&lt;br /&gt;
The test for two axis-aligned boxes is fairly straight forward.  We&#39;ll need to add a few properties to our class first though,
&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class AxisAlignedBox
{
    public Vector2 Position;
    public float Width;
    public float Height;

    //y value of uppermost side.
    public float Top
    {
        get { return Position.Y; }
    }

    //y value of lowest side.
    public float Bottom
    {
        get { return Position.Y + Height; }
    }

    //x value of left most side.
    public float Left
    {
        get { return Position.X; }
    }
    
    //x value of right most side.
    public float Right
    {
        get { return Position.X + Width; }
    }
}
&lt;/pre&gt;
The basic idea is that is if the rectangles intersect, then the top side of one (or the bottom side) will be within the bounds set by the top and bottom sides of the other rectangle.  Likewise the left side of one (or the right side) will be within the bounds set by the left and right sides of the other rectangle.&lt;br /&gt;
Take a look at this picture.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgrG_is4fKXedckUtGhNvuFksIbNugsUqcPmeYeg3G4yTAxzJb-1dAjY0QZ5dHfO4MwScASb7LA-DRZ_57lPweaG2e_HURn54oaqx4m3syCU_sUPz2_k2UlZheqWhyRmsSX1sZ4lwzKL_Y/s1600/rectangle_intersections_01.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;338&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgrG_is4fKXedckUtGhNvuFksIbNugsUqcPmeYeg3G4yTAxzJb-1dAjY0QZ5dHfO4MwScASb7LA-DRZ_57lPweaG2e_HURn54oaqx4m3syCU_sUPz2_k2UlZheqWhyRmsSX1sZ4lwzKL_Y/s400/rectangle_intersections_01.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
Here, we are testing three different rectangles against the shaded rectangle we&#39;ll call, R.&lt;br /&gt;
The bottom side of A is below the top side of R and above the bottom side of R, ie. the bottom side of A is within the bounds set by the top and bottom sides of R. &amp;nbsp;Both the left and right sides of A are within the left-right bounds of R.  Even though the top side of A is not within the top-bottom bounds, it still intersects.&lt;br /&gt;
For B, the top side is within the top and bottom bounds of R and the left side is within R&#39;s left and right bounds.&lt;br /&gt;
C, while its right side is within the left-right bounds of R, neither it&#39;s top nor its bottom sides are within the proper top-bottom bounds of R and it doesn&#39;t intersect.&lt;br /&gt;
Take a look at the follow case, though.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgeC7fCdZukVyn9wUIVvB6o3Sqd_LoXuLF4O_bCrhHYBAgflWlScPFUCyrTvzEVVti0XIvu3K7sOrQYpQteV8IzXbimxBCNcdarPiSHzlhCv-mj3O7t5-x4-Qlgbc3HggJ8MW9sFd0v79Q/s1600/rectangle_intersections_02.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;337&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgeC7fCdZukVyn9wUIVvB6o3Sqd_LoXuLF4O_bCrhHYBAgflWlScPFUCyrTvzEVVti0XIvu3K7sOrQYpQteV8IzXbimxBCNcdarPiSHzlhCv-mj3O7t5-x4-Qlgbc3HggJ8MW9sFd0v79Q/s400/rectangle_intersections_02.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Rectangle D clearly intersects, but neither it&#39;s top nor bottom is within the top-bottom range of R. &amp;nbsp;However, both the top and bottom of R are in D&#39;s top-bottom range.&lt;br /&gt;
So, roughly in logical terms,&lt;br /&gt;
(bottom OR top is within top-bottom bounds of one OR the same with the other) AND&lt;br /&gt;
(left OR right is within left-right bounds of one OR the same with the other).&lt;br /&gt;
We&#39;re pretty much ready to write our algorithm.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class AxisAlignedBox
{
    public Vector2 Position;
    public float Width;
    public float Height;

    //y value of uppermost side.
    public float Top
    {
        get { return Position.Y; }
    }

    //y value of lowest side.
    public float Bottom
    {
        get { return Position.Y + Height; }
    }

    //x value of left most side.
    public float Left
    {
        get { return Position.X; }
    }
    
    //x value of right most side.
    public float Right
    {
        get { return Position.X + Width; }
    }

    public bool Intersects(AxisAlignedBox box)
    {
        bool areBottomsInBounds =
            (Bottom &amp;gt;= box.Top &amp;amp;&amp;amp; Bottom &amp;lt;= box.Bottom) ||
            (box.Bottom &amp;gt;= Top &amp;amp;&amp;amp; box.Bottom &amp;lt;= Bottom);

        bool areTopsInBounds =
            (Top &amp;gt;= box.Top &amp;amp;&amp;amp; Top &amp;lt;= box.Bottom) ||
            (box.Top &amp;gt;= Top &amp;amp;&amp;amp; box.Top &amp;lt;= Bottom);

        bool areLeftsInBounds =
            (Left &amp;gt;= box.Left &amp;amp;&amp;amp; Left &amp;lt;= box.Right) ||
            (box.Left &amp;gt;= Left &amp;amp;&amp;amp; box.Right &amp;lt;= Right);

        bool areRightsInBounds =
            (Right &amp;gt;= box.Left &amp;amp;&amp;amp; Right &amp;lt;= box.Right) ||
            (box.Right &amp;gt;= Left &amp;amp;&amp;amp; box.Right &amp;lt;= Right);

        bool intersects = (areBottomsInBounds || areTopsInBounds) &amp;amp;&amp;amp;
            (areLeftsInBounds || areRightsInBounds);


        return intersects;
    }
}
&lt;/pre&gt;
Another, way to do this which will also be enlightening later on is to note that for rectangle A in the above illustration, the distance from the top of A to the bottom of R is less than the sum of the height of A and the height of R, while at the same time, the distance between the left of A and the right of R is less than the sum of the width of A and width of R.  In general, the distance between the uppermost and lowermost points is less than the sum of the heights and the distance between the leftmost and rightmost points is less than the sum of the widths.&lt;br /&gt;
The code for the other method,&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class AxisAlignedBox
{
    public Vector2 Position;
    public float Width;
    public float Height;

    //y value of uppermost side.
    public float Top
    {
        get { return Position.Y; }
    }

    //y value of lowest side.
    public float Bottom
    {
        get { return Position.Y + Height; }
    }

    //x value of left most side.
    public float Left
    {
        get { return Position.X; }
    }
    
    //x value of right most side.
    public float Right
    {
        get { return Position.X + Width; }
    }

    public bool Intersects(AxisAlignedBox box)
    {
        //The nested Max calls find the maximum of four different values.
        //Similarly with the nested Min values we find the minimum of more than two values.
        float horizontalDistance = Math.Max(Right, 
                                       Math.Max(box.Right, 
                                           Math.Max(Left, box.Left))) - 
                                   Math.Min(Right, 
                                       Math.Min(box.Right, 
                                           Math.Min(Left, box.Left)));
        float verticalDistance =  Math.Max(Top, 
                                      Math.Max(box.Top, 
                                          Math.Max(Bottom, box.Bottom))) - 
                                  Math.Min(Top, 
                                      Math.Min(box.Top, 
                                          Math.Min(Bottom, box.Bottom)));

        bool intersects = (float)Math.Abs(horizontalDistance) &amp;lt;= Width + box.Width &amp;amp;&amp;amp;
                          (float)Math.Abs(verticalDistance) &amp;lt;= Height + box.Height
     
        return intersects;       
    }
}
&lt;/pre&gt;
&lt;h2&gt;Box-box test (general) &lt;/h2&gt;
Before continuing further we need to talk about an important mathematical theorem called &lt;a href=&quot;http://en.wikipedia.org/wiki/Separating_axis_theoremhttp://en.wikipedia.org/wiki/Separating_axis_theorem&quot;&gt;the separating axis theorem&lt;/a&gt;.  We&#39;ve already used a result of this theorem in the last example and it will end up being the basis for many other intersection problems in the future.  We&#39;ll go into the theorem in some depth, what it implies and how we can use it to test for intersections.&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;











The Separating Axis Theorem&lt;/h2&gt;
&lt;br /&gt;
The separating axis theorem states that two &lt;a href=&quot;http://en.wikipedia.org/wiki/Convex_polyhedra&quot;&gt;convex polygons&lt;/a&gt; do &lt;i&gt;not&lt;/i&gt; intersect if and only if there exists a line such that when we project the shapes onto that line, the projections do not overlap.  The line we project onto is called the &lt;i&gt;axis of separation&lt;/i&gt;.&lt;br /&gt;
&lt;br /&gt;
First let&#39;s clear up the term &quot;projection onto a line&quot;.&lt;br /&gt;
The term, &lt;a href=&quot;http://en.wikipedia.org/wiki/Projection_(mathematics)&quot;&gt;projection&lt;/a&gt; &lt;a href=&quot;http://en.wikipedia.org/wiki/Projection_(linear_algebra)&quot;&gt;seems&lt;/a&gt;  &lt;a href=&quot;http://en.wikipedia.org/wiki/Map_projection&quot;&gt;a little&lt;/a&gt; &lt;a href=&quot;http://en.wikipedia.org/wiki/Graphical_projection&quot;&gt;overloaded&lt;/a&gt; with definitions but they are all closely related.&lt;br /&gt;
In our case, we can say informally that we&#39;re &#39;casting a shadow&#39; of the object onto a line.&lt;br /&gt;
This picture illustrates three shapes being projected onto an arbitrary line, the x-axis and the y axis.&lt;br /&gt;
&lt;table align=&quot;center&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;tr-caption-container&quot; style=&quot;margin-left: auto; margin-right: auto; text-align: center;&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjihTD6hgAva7pI5ElxkujnEmrVHJbrOxqQ5n2Z6kA-wnKIuS-UxUUZlGu1ALvDd34QXgo0xEHGae4a8xEOIIAEMF0r22z7C3ZmXqHStE7lIUFbBOIUF3HjxTI8gfbMesyTs2EC_xmY9rQ/s1600/axis_projection.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: auto; margin-right: auto;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;480&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjihTD6hgAva7pI5ElxkujnEmrVHJbrOxqQ5n2Z6kA-wnKIuS-UxUUZlGu1ALvDd34QXgo0xEHGae4a8xEOIIAEMF0r22z7C3ZmXqHStE7lIUFbBOIUF3HjxTI8gfbMesyTs2EC_xmY9rQ/s640/axis_projection.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class=&quot;tr-caption&quot; style=&quot;text-align: center;&quot;&gt;Here we see three shapes being projected onto three lines: &amp;nbsp;The x and y axis and an arbitrary line, L.&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
The projections are regions of the line.  Notice shape C is an axis-aligned box; its x and y projections are the same left-right and top-bottom bounds that we used earlier.  In fact, the term in the conditional that states the box we&#39;re testing must have its bottom OR top side within the top-bottom bound of the other box is analogous to saying that the boxes&#39; projections onto the y-axis overlap (look at the illustration from the axis aligned box-box section to make sure you see why).&lt;br /&gt;
None of these shapes intersect so according to the theorem, there exists a line such that the shapes projections onto that line are separate.  Here we see two:  the x-axis and the line, L.&lt;br /&gt;
This theorem says a lot about when shapes don&#39;t intersect but what can we say about when they do?  Well, we simply have to negate the theorem to see that two convex polygons intersect if and only if there does not exit a line with said properties.  That is, no matter how many lines you project your polyhedra onto, the projections will always overlap.&lt;br /&gt;
This poses a problem since there are infinitely many lines we could check.&lt;br /&gt;
Luckily in the case of convex polygons there are only a few axis we need to check.&lt;br /&gt;
Notice in the axis-aligned box-box method, we only checked the projections of two lines:  the x and the y axis.  Since both boxes were aligned to those axis those were the only two we had to check.&lt;br /&gt;
For a convex polygon, it is sufficient to check the shapes against the axis determined by the normals of each edge (&lt;a href=&quot;http://www.metanetsoftware.com/technique/tutorialA.html#section1&quot;&gt;source&lt;/a&gt;).  If we come across projections that don&#39;t overlap we have an early out which will speed up the calculation and if we get through them all and all the projections overlap, then the shapes intersect.&lt;br /&gt;
Once we have projections (or the length of them) we can check to see if they overlap similarly to the axis aligned case above.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOehQX6GHn0NzznCdqEqImHdWl-AYv608oXalBNivNVUF3rzaWmimrrG_STnCUoyjs81oRz_OEKy3C7v5j9UoA-605yHqAN6sSkV3bQnq5Mtsduwys7yLEFwyDwBZfbv0QtkYJ-X1PZd0/s1600/projections.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;576&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOehQX6GHn0NzznCdqEqImHdWl-AYv608oXalBNivNVUF3rzaWmimrrG_STnCUoyjs81oRz_OEKy3C7v5j9UoA-605yHqAN6sSkV3bQnq5Mtsduwys7yLEFwyDwBZfbv0QtkYJ-X1PZd0/s640/projections.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
Before we checked the total distance between the uppermost or lowermost points against the sum of the widths or heights depending.&lt;br /&gt;
Now we&#39;re checking the distance between the extreme points of the projections along the axis and testing that against the sum of the lengths of the projections.
But how do we project these polygons against an axis and find these lengths to begin with?&lt;br /&gt;
&lt;br /&gt;
To start, we&#39;ll need to know about &lt;a href=&quot;http://en.wikipedia.org/wiki/Vector_projection&quot;&gt;vector projection&lt;/a&gt;.&lt;br /&gt;
&lt;div class=&quot;latexparse&quot;&gt;
The projection of $\bar{a}$ onto $\bar{b}$ is,
&lt;/div&gt;
&lt;div class=&quot;latexparse&quot;&gt;
$(\bar{a}\cdot\bar{b})\bar{b}=(|\bar{a}|\cos{\theta})\bar{b}$
&lt;/div&gt;
&lt;div class=&quot;latexparse&quot;&gt;
This can be thought of as the &quot;$\bar{b}$ component of $\bar{a}$&quot;.  It&#39;s in the direction of $\bar{b}$ with a magnitude that varies between $|\bar{a}|$ (when $\bar{a}$ is parallel to $\bar{b}$) and 0 (when $\bar{a}$ is normal to $\bar{b}$).
&lt;/div&gt;
We also need to tweak our Box class a bit.  A lot of the math becomes easier when we keep track of the box&#39;s center, its &lt;i&gt;half-height&lt;/i&gt; and its &lt;i&gt;half-width&lt;/i&gt;.  These are similar to a circle&#39;s radius except they&#39;re vector quantities.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpCOFK_8R3exlwGPMMy45ABGpKhPI2lWcyQKvL1jcZddfuSnL-ZV7VWOGWwhZrvbMRFBs9PkLrJaxkhgGlkF1Jb9zTtbFfywrCvVEWv9yODtuSt7K-kFsMAQt-Pn3zh6j2_vzZFxMtl3Y/s1600/rectangle_halfsize.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;185&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpCOFK_8R3exlwGPMMy45ABGpKhPI2lWcyQKvL1jcZddfuSnL-ZV7VWOGWwhZrvbMRFBs9PkLrJaxkhgGlkF1Jb9zTtbFfywrCvVEWv9yODtuSt7K-kFsMAQt-Pn3zh6j2_vzZFxMtl3Y/s400/rectangle_halfsize.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class Box
{
    //Pseudo-code...
    public Vector2 Center;
    public Vector2 HalfHeight;
    public Vector2 HalfWidth;
    public float Angle;
}
&lt;/pre&gt;
Now to measure a projection along a certain axis, take a look at the following illustration,&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVGhOP04Wlr6pzy8drqWwlZDbEHY5SieopBu67i8D0ivco2waSjMznnVxUrxVDe67ST1wq6hQZM4t25PYgHBKDk09DTzsaLZoXy2HFu4Odp6Qfi4Lxt5ZjtzUfN38affotgVcugyQlyEw/s1600/projection_length.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;480&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVGhOP04Wlr6pzy8drqWwlZDbEHY5SieopBu67i8D0ivco2waSjMznnVxUrxVDe67ST1wq6hQZM4t25PYgHBKDk09DTzsaLZoXy2HFu4Odp6Qfi4Lxt5ZjtzUfN38affotgVcugyQlyEw/s640/projection_length.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
The half-width and half-height projections give us a handy way to measure a shape along an axis.  As for the total distance we need only to project the distance between centers onto the axis and find that length.  This give us half the total distance.  So we can check the length of the projected vectors against that.&lt;br /&gt;
&lt;br /&gt;
To sum up the algorithm we&#39;ve been piecing together so far:&lt;br /&gt;
1.  Get the normals of each box, removing duplicates and normals in the opposite direction.&lt;br /&gt;
For each normal:&lt;br /&gt;
2.  Project both of the boxes&#39; half-widths and half-heights onto it and find the sum of their lengths (note: &lt;i&gt;not&lt;/i&gt; the length of their sum, since the projections point in opposite directions they tend to cancel eachother).  We&#39;ll call these H1 and H2 for each box.&lt;br /&gt;
3.  Project the difference vector of the boxes&#39; centers onto the normal and find its length, we&#39;ll call it D.&lt;br /&gt;
4.  if D &amp;gt; H1 + H2, then there&#39;s no overlap, hence no intersection.  Otherwise:&lt;br /&gt;
5.  if there&#39;s more normals get the next normal and repeat.  Otherwise, all projections overlap and we have an intersection!&lt;br /&gt;
And now we&#39;re ready to take a look at our new Box class with the interection method.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class Box
{
    public Vector2 Center;
    //We store these as floats for now,
    //we only need the vector versions during
    //intersection testing.
    public float HalfWidth;
    public float HalfHeight;
    public float Angle;

    public bool Intersects(Box box)
    {
        //Transform the half measures
        Vector2 halfWidthVectOne = Vector2.Transform(
            HalfWidth * Vector2.UnitX, Matrix.CreateRotationZ(Angle));
        Vector2 halfHeightVectOne = Vector2.Transform(
            HalfHeight * Vector2.UnitY, Matrix.CreateRotationZ(Angle));
        Vector2 halfWidthVectTwo = Vector2.Transform(
            box.HalfWidth * Vector2.UnitX, Matrix.CreateRotationZ(box.Angle));
        Vector2 halfHeightVectTwo = Vector2.Transform(
            box.HalfHeight * Vector2.UnitY, Matrix.CreateRotationZ(box.Angle));
            
        //They&#39;ll work as normals too.
        Vector2[] normals = new Vector2[4];
        normals[0] = halfWidthVectOne;
        normals[1] = halfWidthVectTwo;
        normals[2] = halfHeightVectOne;
        normals[3] = halfHeightVectTwo;

        for (int i = 0; i &amp;lt; 4; i++)
        {
            normals[i].Normalize();

            //Project the half measures onto the normal...
            Vector2 projectedHWOne =
                Vector2.Dot(halfWidthVectOne, normals[i]) * normals[i];
            Vector2 projectedHHOne =
                Vector2.Dot(halfHeightVectOne, normals[i]) * normals[i];
            Vector2 projectedHWTwo =
                Vector2.Dot(halfWidthVectTwo, normals[i]) * normals[i];
            Vector2 projectedHHTwo =
                Vector2.Dot(halfHeightVectTwo, normals[i]) * normals[i];

            //Calculate the half lengths along the separation axis.
            float halfLengthOne = projectedHWOne.Length() + projectedHHOne.Length();
            float halfLengthTwo = projectedHWTwo.Length() + projectedHHTwo.Length();

            //Find the distance between object centers along the separation axis.
            Vector2 difference = (Center - box.Center);
            Vector2 projectedDiff =
                Vector2.Dot(difference, normals[i]) * normals[i];
            float projectedDistance = projectedDiff.Length();
            
            //Test for early out.
            if (projectedDistance &amp;gt; halfLengthOne + halfLengthTwo)
            {
                return false;
            }
        }
        //We tested every normal axis,
        //we must be in intersection!
        return true;
    }
}
&lt;/pre&gt;
This test secretly assumes that the rotation is about the center point.  Otherwise, we&#39;d need to transform the centers to account for the rotation about a different point.  If we were dealing with an origin that was located in the upper-left corner of the box, for example, we&#39;d translate the position by the rotated half-measures to get the correct center.&lt;/br&gt;
Also, while we were able to remove a few normals because we knew they were boxes (the ones in the opposite direction as another), we did not go through and test for duplicates.  For larger polygons with more normals it may be faster to filter out the duplicate normals.&lt;/br&gt;
&lt;/br&gt;
&lt;h2&gt;Circle-box test&lt;/h2&gt;
&lt;/br&gt;
For convex polygons there are a finite, if not very large number of normals to check.  For a circle one could say there are an infinite amount of normals to check.  On the plus side, if we can find a sufficient amount of normals to check, the projection is always the same.&lt;/br&gt;
Using the same &lt;a href=&quot;http://www.metanetsoftware.com/technique/tutorialA.html#section3&quot;&gt;source&lt;/a&gt;, we&#39;re going to implement the &#39;naive&#39; axis test where we test against every axis determined by the circles center and a vertex on the box.&lt;/br&gt;
Ideally we would only need to check against the one determined by the closest vertex.&lt;/br&gt;
Adding a new method to our Box class,&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public bool Intersects(Circle circle)
{
    //Transform the half measures
    Vector2 halfWidthVect = Vector2.Transform(
        HalfWidth * Vector2.UnitX, Matrix.CreateRotationZ(Angle));
    Vector2 halfHeightVect = Vector2.Transform(
        HalfHeight * Vector2.UnitY, Matrix.CreateRotationZ(Angle));

    Vector2[] normals = new Vector2[6];
    normals[0] = halfHeightVect;
    normals[1] = halfWidthVect;
    normals[2] = circle.Center - (Center + halfHeightVect);
    normals[3] = circle.Center - (Center - halfHeightVect);
    normals[4] = circle.Center - (Center + halfWidthVect);
    normals[5] = circle.Center - (Center - halfWidthVect);

    for (int i = 0; i &lt; 6; i++)
    {
        normals[i].Normalize();
        Vector2 projectedHalfWidth =
            Vector2.Dot(halfWidthVect, normals[i]) * normals[i];
        Vector2 projectedHalfHeight =
            Vector2.Dot(halfHeightVect, normals[i]) * normals[i];

        float halfLength = projectedHalfHeight.Length() + projectedHalfWidth.Length();

        Vector2 difference = Center - circle.Center;
        Vector2 projectedDifference =
            Vector2.Dot(difference, normals[i]) * normals[i];
        float projectedDistance = projectedDifference.Length();

        if (projectedDistance &gt; halfLength + circle.Radius)
        {
            return false;
        }
    }
    return true;
}
&lt;/pre&gt;
I also added a method in the Circle class,
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public bool Intersects(Box box)
{
    return box.Intersects(this);
}
&lt;/pre&gt;
When I tested this I needed to set the box&#39;s origin properly:&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    Color color = circle.Intersects(rotatedBoxTwo)||circle.Intersects(rotatedBoxOne) ? 
        Color.Red : Color.White;


    spriteBatch.Begin();

    Vector2 scaleOne = new Vector2(
        rotatedBoxOne.Width / (float)boxTexture.Width,
        rotatedBoxOne.Height / (float)boxTexture.Height);
    Vector2 scaleTwo = new Vector2(
        rotatedBoxTwo.Width / (float)boxTexture.Width,
        rotatedBoxTwo.Height / (float)boxTexture.Height);

    float circleScale = 2f* circle.Radius / (float)circleTexture.Width;

    //Remembering the origin is in texture coordinates, we must scale it down.
    spriteBatch.Draw(
        boxTexture,
        rotatedBoxOne.Center,
        null,
        color,
        rotatedBoxOne.Angle,
        new Vector2(rotatedBoxOne.HalfWidth, rotatedBoxOne.HalfHeight) / scaleOne,
        scaleOne,
        SpriteEffects.None,
        0f);

    spriteBatch.Draw(
        boxTexture,
        rotatedBoxTwo.Center,
        null,
        color,
        rotatedBoxTwo.Angle,
        new Vector2(rotatedBoxTwo.HalfWidth, rotatedBoxTwo.HalfHeight) / scaleTwo,
        scaleTwo,
        SpriteEffects.None,
        0f);

    spriteBatch.Draw(
        circleTexture,
        circle.Center,
        null,
        color,
        0f,
        new Vector2(circle.Radius, circle.Radius) / circleScale,
        circleScale,
        SpriteEffects.None,
        0f);
                
    spriteBatch.End();

    base.Draw(gameTime);
}
&lt;/pre&gt;
I hope this cleared a lot of stuff up about intersections between shapes.  Again, if you&#39;re intersested, check out &lt;a href=&quot;http://www.metanetsoftware.com/technique/tutorialA.html#section0&quot;&gt;this page&lt;/a&gt; for more information.  There&#39;s algorithms about some convex shapes too.&lt;/br&gt;
Thanks for reading!</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/6789832723112156319/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/12/intersection-testing.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/6789832723112156319'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/6789832723112156319'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/12/intersection-testing.html' title='Intersection Testing in 2D'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2PpAlrF8iFA6b9xhP0_kt4mCTZnD75EgGsuTFjUoDlkRtLOft_mTD4ItwUcnHMzgCWlOCILuWJeEIZyCB3LTaeEjCu4O-uNFK6AVH3OUKfcjdmDJJJqvDlCjtcLbDU7H2D2iqD9lv0kc/s72-c/circle.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-8294693956634611273</id><published>2011-12-03T05:33:00.001-08:00</published><updated>2012-03-04T12:38:52.531-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><title type='text'>The Adapter Pattern</title><content type='html'>In this post we&#39;ll the talking about the Adapter Pattern.&lt;br /&gt;
The Adapter pattern, in short, makes one class look like another.  We&#39;ve all seen adapters in the real world:  many electrical plugs in the U.S. have three prongs while many of the older outlets or extension cords only have two slots for it.  We&#39;d still like to be able to use them, after all there&#39;s still a plug, an outlet and they both are made for running an electrical current through it.&lt;br /&gt;
&lt;br /&gt;
To get around this we can buy an adapter for the plug.  It&#39;s got three slots on one side and two prongs in the other.  We simply plug it into the adapter and the outlet will accept it.&lt;br /&gt;
&lt;br /&gt;
Let&#39;s say there&#39;s a client class that expects a certain type of object to work but we want to use an object of a type that, while similar, just doesn&#39;t fit.  All we have to do is write an adapter for it and pass our client the adapter in place of our original class and we&#39;re set.  The adapter sits in between the client and the vendor class and acts as sort of a translator between the two.&lt;br /&gt;
&lt;br /&gt;
Let&#39;s take a look at some simple classes to illustrate.  Going back to car examples...&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;//First we&#39;ll need a Vehicle interface.
interface Vehicle
{
    void TurnOn();
    void TurnOff();
    void Drive();
    void FillGasTank();
}

class Car : Vehicle
{
    public void TurnOn()
    {
        Console.WriteLine(&quot;Starting ignition.&quot;)
    }

    public void TurnOff()
    {
        Console.WriteLine(&quot;Shutting off engine.&quot;)
    }

    public void Drive()
    {
        Console.WriteLine(&quot;Vroom!&quot;);
    }

    public void Break()
    {
        Console.WriteLine(&quot;Screetch!&quot;);
    }

    public void FillGasTank()
    {
        Console.WriteLine(&quot;Filling tank.&quot;);
    }
}
&lt;/pre&gt;
Now let&#39;s say we have a client class with methods that accepts vehicles.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class VehicleTester
{
    public void TestVehicle(Vehicle vehicle)
    {
        vehicle.TurnOn();
        vehicle.Drive();
        vehicle.Break();
        vehicle.FillGasTank();
        vehicle.TurnOff();
    }
}
&lt;/pre&gt;
Seems like a fine vehicle tester but let&#39;s take a look at another class, a LawnMower.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class LawnMower
{
    public void TurnOn()
    {
        Console.WriteLine(&quot;Pulling cord to start engine.&quot;)
    }

    public void TurnOff()
    {
        Console.WriteLine(&quot;Push off button&quot;);
    }

    public void Push()
    {
        Console.WriteLine(&quot;Pushing mower around.&quot;);
    }

    public void FillGasTank()
    {
        Console.WriteLine(&quot;Filling the tank&quot;);
    }
}
&lt;/pre&gt;
We would like to be able to test our new LawnMower with the tester we&#39;ve already implemented but we shouldn&#39;t inherit from Vehicle.  It&#39;s not exactly a vehicle and there&#39;s no Break method.&lt;br /&gt;
We could write a separate TestMower method, but that&#39;s more coding and there will be code duplication.  And if we come up with similar classes in the future that we&#39;d like to test, the code will become messy and confusing quickly as we add these tester methods.&lt;br /&gt;
&lt;br /&gt;
We can fix this by making a class called an &lt;i&gt;adapter&lt;/i&gt; which will inherit from the target interface and hold a reference to the object we are adapting.  In the adapter&#39;s overridden methods, we simply call the corresponding methods on the adaptee.&lt;br /&gt;
Let&#39;s look at the adapter code to help illustrate.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;//The adapter inherits the Vehicle class so that our 
//VehicleTester class method will accept it as a parameter
class LawnMowerAdapter : Vehicle
{
    //The adapter contains a LawnMower reference.
    LawnMower _mower;

    //The constructor is passed a LawnMower to adapt.
    public LawnMowerAdapter(LawnMower mower)
    {
        _mower = mower
    }

    //The adapter must implement all the Vehicle methods
    //and there we&#39;ll call the appropriate methods on the mower.
    public void TurnOn()
    {
        _mower.TurnOn();
    }

    public void TurnOff()
    {
        _mower.TurnOff();
    }

    public void Drive()
    {
        _mower.Push()
    }

    public void Break()
    {
        //Traditional lawn mowers don&#39;t have a break, you just stop pushing.
        //This method can be left blank.
        //One could code some logic for stopping however this would
        //increase the coupling between Adapter and LawnMower. 
    }

    public void FillGasTank()
    {
        _mower.FillGasTank();
    }
}
&lt;/pre&gt;
Now if we have a VehicleTester that we&#39;d like to use to test our LawnMower, we have a neat way to do that.  With an adapter.&lt;br /&gt;
We first create the adapter giving it the mower we want to test, then we pass the adapter object off to the VehicleTester&#39;s TestVehicle method, who accepts it happily since the adapter implements the Vehicle interface.  It tests the Mower with no problems or even the knowledge that it&#39;s really dealing with a LawnMower (wrapped in an adapter).&lt;br /&gt;
&lt;br /&gt;
The adapter links the client, the VehicleTester, to the adaptee, the LawnnMower.  It does this by tricking the client into thinking that it&#39;s dealing with the target when it&#39;s really just calling methods on the adaptee.&lt;br /&gt;
&lt;br /&gt;
Which methods being called is completely up the adapter.  It acts as a translator for the client.&lt;br /&gt;
&lt;br /&gt;
Let&#39;s see this in action&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public class Program
{
    public void Main(string[] args)
    {
        VehicleTester tester = new VehicleTester();

        //Create the car.
        Car car = new Car();
        
        //Test the car.
        tester.TestVehicle(car);

        //We now create the LawnMower.
        LawnMower mower = new LawnMower();

        //Although we&#39;d like to we can&#39;t do this:
        //tester.TestVehicle(mower);
        
        //so we create an adapter object.
        //passing the mower to its constructer.
        LawnMowerAdapter adapter = new LawnMowerAdapter(mower);

        //Now we can test it via the adapter.
        tester.TestVehicle(adapter);
    }
}
&lt;/pre&gt;
Now the console should print something like this out:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;
Starting ignition.&lt;br /&gt;
Vroom!&lt;br /&gt;
Screetch!&lt;br /&gt;
Filling tank.&lt;br /&gt;
Shutting off engine.&lt;br /&gt;
Pulling cord to start engine.&lt;br /&gt;
Pushing mower around.&lt;br /&gt;
Filling the tank.&lt;br /&gt;
Push off button.&lt;br /&gt;   
&lt;/b&gt;
&lt;/br&gt;
Perfect!&lt;/br&gt;
The Adapter pattern, turning one class into another.&lt;br /&gt;&lt;/br&gt;
We&#39;ll wrap up with a quick look at the class diagram.&lt;br /&gt;&lt;/br&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhL7-YuWMMzsr5oulzXEPd-4XerIByTJDjZHA5G3VRHIf9hbCiss43VvI6vGaRVcckrXAhAeA5EkUDLGb4UPTnp1kkJVB-apnwUaGNJVoFx_MjLIj9sbSJiz02VbP7e9j_e4Ei8_4i0b4A/s1600/adapter_pattern.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;380&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhL7-YuWMMzsr5oulzXEPd-4XerIByTJDjZHA5G3VRHIf9hbCiss43VvI6vGaRVcckrXAhAeA5EkUDLGb4UPTnp1kkJVB-apnwUaGNJVoFx_MjLIj9sbSJiz02VbP7e9j_e4Ei8_4i0b4A/s640/adapter_pattern.jpg&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;/br&gt;
That&#39;s all for now.  Hope you enjoyed learning about the adapter pattern and thanks for reading.</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/8294693956634611273/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/12/adapter-pattern.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/8294693956634611273'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/8294693956634611273'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/12/adapter-pattern.html' title='The Adapter Pattern'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhL7-YuWMMzsr5oulzXEPd-4XerIByTJDjZHA5G3VRHIf9hbCiss43VvI6vGaRVcckrXAhAeA5EkUDLGb4UPTnp1kkJVB-apnwUaGNJVoFx_MjLIj9sbSJiz02VbP7e9j_e4Ei8_4i0b4A/s72-c/adapter_pattern.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-6593228490706730887</id><published>2011-12-01T07:05:00.001-08:00</published><updated>2012-03-04T12:39:12.004-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><title type='text'>The Template Method Pattern</title><content type='html'>The Template Method patter is a simple but very widely used pattern.  In fact, if you ever used the XNA framework, you took advantage of the fact that XNA implements a variation of the Template Method pattern perhaps without even being aware of it!&lt;/br&gt;
The Template Method pattern allows us to encapsulate algorithms while also being able to delegate some of the steps of the algorithm to subclasses&lt;/br&gt;
Before we see how though, let&#39;s look at a simple example.&lt;/br&gt;
&lt;/br&gt;
Many of us love our pets or plants and we have to take care of them.  One of the responsibilities is feeding them.&lt;/br&gt;
An algorithm for feeding a dog may simply involve getting a can of dog food, opening the can and scooping the contents into a bowl.&lt;/br&gt;
Feeding a cat could be quite similar.  One could get a can of cat food, open the can and scoop it into a bowl.&lt;/br&gt;
&lt;/br&gt;
Let&#39;s build some pet-owner classes and see how this might work.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class DogOwner
{
    public void FeedDog()
    {
        CallDogOver();
        GetDogFood();
        GetCanOpener();
        OpenCan();
        FillBowl();
    }

    void CallDogOver()
    {
        Console.WriteLine(&quot;Calling dog&#39;s name.&quot;)
    }

    void GetDogFood()
    {
        Console.WriteLine(&quot;Getting a can of dog food.&quot;);
    }
    
    void GetCanOpener()
    {
        Console.WriteLine(&quot;Getting a can opener&quot;);
    }

    void OpenCan()
    {
        Console.WriteLine(&quot;Opening can.&quot;);
    }
    
    void FillBowl()
    {
        Console.WriteLine(&quot;Empty can into bowl.&quot;);
    }
}

class CatOwner
{
    public void FeedCat()
    {
        //These two methods have different implementations
        //Depending on the pet!
        CallCatOver();
        GetCatFood();
        //All of these methods are the same as
        //the DogOwner&#39;s...
        GetCanOpener();
        OpenCan();
        FillBowl();
    }

    void CallCatOver()
    {
        Console.WriteLine(&quot;Making a ticking noise to get the cat&#39;s attention.&quot;);
    }

    void GetCanOpener()
    {
        Console.WriteLine(&quot;Getting a can opener&quot;);
    }

    void GetCatFood()
    {
        Console.WriteLine(&quot;Getting a can of cat food.&quot;);
    }

    void OpenCan()
    {
        Console.WriteLine(&quot;Opening can.&quot;);
    }
    
    void FillBowl()
    {
        Console.WriteLine(&quot;Empty can into bowl.&quot;);
    }
}
&lt;/pre&gt;
A big red flag that a design needs to be reworked is &lt;i&gt;code duplication&lt;/i&gt;.  For the methods that are the same regardless of pet, we&#39;re copying the exact same code into the methods; both involve getting a can opener, opening the can and pouring the contents into a bowl and we should to do something about this duplication.&lt;/br&gt;
Even the methods that have different implementations are similar:  we still get the pet&#39;s attention and retrieve some sort of food.&lt;/br&gt;
What we&#39;d like is a framework that allows us to avoid code duplication while also allowing for different implementations on some of the methods in the algorithm.  The Template Method pattern allows us to do just that.&lt;/br&gt;
&lt;/br&gt;
Following one of our guidelines to program to an interface (or abstract class), let&#39;s rework this a little and code an abstract PetOwner class like so,&lt;br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
abstract class PetOwner
{
    //This is called the Template Method.
    public void FeedPet()
    {
        //These are the steps in the algorithm.
        CallPet();
        GetCanOfFood();
        GetCanOpener();
        OpenCan();
        FillBowl();
    }

    //We delegate the implementation of these methods to
    //any class that inherits from it.
    protected abstract void CallPet();
    protected abstract void GetCanOfFood();

    void GetCanOpener()
    {
        Console.WriteLine(&quot;Getting a can opener&quot;);
    }

    void OpenCan()
    {
        Console.WriteLine(&quot;Opening can.&quot;);
    }
    
    void FillBowl()
    {
        Console.WriteLine(&quot;Empty can into bowl.&quot;);
    }
}
&lt;/pre&gt;
Now any class that inherits from PetOwner must implement both the CallPet and GetCanOfFood methods.  The subclasses will be responsible for handling these.&lt;/br&gt;
&lt;/br&gt;
Let&#39;s code our DogOwner and CatOwner classes now.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class DogOwner : PetOwner
{
    protected override CallPet()
    {
        Console.WriteLine(&quot;Calling the dog&#39;s name.&quot;);
    }

    protected override GetCanOfFood()
    {
        Console.WriteLine(&quot;Getting dog food.&quot;);
    }
}

class CatOwner : PetOwner
{
    protected override CallPet()
    {
        Console.WriteLine(&quot;Making a ticking noise to get the cat&#39;s attention.&quot;);
    }

    protected override GetCanOfFood()
    {
        Console.WriteLine(&quot;Getting cat food.&quot;);
    }
}
&lt;/pre&gt;
This seems to be working out well!  But what about a gerbil? (for our example gerbil food now comes in tin cans.  No analogy is perfect after all!)  One doesn&#39;t need to get their attention to eat, one simply fills their bowl.  But there&#39;s still enough similarities so that we should be able to feed a gerbil with our design.&lt;/br&gt;
&lt;/br&gt;
We can do this by making what&#39;s called a &lt;i&gt;hook&lt;/i&gt;.  A hook is simply a &lt;i&gt;virtual&lt;/i&gt; method that by default does nothing but subclasses can &lt;i&gt;hook&lt;/i&gt; into it and implement their own behavior if they want to.&lt;/br&gt;
Changing the PetOwner class just a little:&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
abstract class PetOwner
{
    public void FeedPet()
    {
        CallPet();
        GetCanOfFood();
        GetCanOpener();
        OpenCan();
        FillBowl();
    }

    //CallPet is now a hook method.
    protected virtual void CallPet() { }
    protected abstract void GetCanOfFood();

    void GetCanOpener()
    {
        Console.WriteLine(&quot;Getting a can opener&quot;);
    }

    void OpenCan()
    {
        Console.WriteLine(&quot;Opening can.&quot;);
    }
    
    void FillBowl()
    {
        Console.WriteLine(&quot;Empty can into bowl.&quot;);
    }
}
&lt;/pre&gt;
Now CallPet is virtual and by default does nothing.  We don&#39;t have to change our CatOwner or DogOwner classes at all but in our GerbilOwner class we simply do not have to override it.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class GerbilOwner : PetOwner
{
    protected override GetCanOfFood()
    {
        Console.WriteLine(&quot;Getting gerbil food.&quot;);
    }
}
&lt;/pre&gt;
We don&#39;t need to override the hook method since it&#39;s in a cage, probably, and knows exactly when you&#39;re about to feed it.&lt;/br&gt;
&lt;/br&gt;
Let&#39;s add one more hook to this example so that we can pet the animal after feeding.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
abstract class PetOwner
{
    public void FeedPet()
    {
        CallPet();
        GetCanOfFood();
        GetCanOpener();
        OpenCan();
        FillBowl();
        PetAnimal();
    }

    //hooks can be overriden if desired.
    protected virtual void CallPet() { }
    protected virtual void PetAnimal() { }

    //abstract methods must be implemented
    protected abstract void GetCanOfFood();

    void GetCanOpener()
    {
        Console.WriteLine(&quot;Getting a can opener&quot;);
    }

    void OpenCan()
    {
        Console.WriteLine(&quot;Opening can.&quot;);
    }
    
    void FillBowl()
    {
        Console.WriteLine(&quot;Empty can into bowl.&quot;);
    }
}
&lt;/pre&gt;
Now our pet owner classes can pet their animals after feeding if they want to.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class DogOwner : PetOwner
{
    protected override CallPet()
    {
        Console.WriteLine(&quot;Calling the dog&#39;s name.&quot;);
    }

    protected override GetCanOfFood()
    {
        Console.WriteLine(&quot;Getting dog food.&quot;);
    }

    protected override PetAnimal()
    {
        Console.WriteLine(&quot;Petting dog on the the head and scratches behind the ears.&quot;);
    }
}

//A fish doesn&#39;t need to be called
//And petting one isn&#39;t pleasant for you or the fish...
class FishOwner
{
    //Again, for our limited example, fish food comes in cans. (gross)
    protected override GetCanOfFood()
    {
        Console.WriteLine(&quot;Getting gerbil food.&quot;);
    }
}
&lt;/pre&gt;
The Template Method pattern is arguably the simplest and most widely used pattern around.  I mentioned how XNA uses it?  Well maybe it&#39;s apparent to you how by now but let&#39;s consider this.&lt;/br&gt;
When you make a new Game project, we automatically get a Game1 class which contains methods for loading content, Updating and Drawing.&lt;/br&gt;
Underneath the hood there is an algorithm that first calls Initialize() and LoadContent(), and then a game loop which cycles through the Update() and Draw() methods until the game exits.&lt;/br&gt;
The pseudo code might look something very similar to this:&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class Game
{
    public void Run()
    {
        Initialize();
        LoadContent();

        //do game loop until we exit the game.
        Update();
        Draw();
    }

    //In this version of the Template Method they&#39;re all hooks!
    virtual void Initialize() { }
    virtual void LoadContent() { }
    virtual void Update() { }
    virtual void Draw() { }
}
&lt;/pre&gt;
The same thing applies to GameComponent and DrawableGameComponent.&lt;/br&gt;
The methods you see when you first start a game aren&#39;t the only hook methods your game can hook into as well, just put your cursor somewhere in the class (but outside a method).  And type in &#39;override&#39;.  You&#39;ll see a whole slew of things you can override and handle in your own way.  Many have default behaviors (called using the base keyword) so watch out for that if you start getting bugs.&lt;/br&gt;
&lt;/br&gt;
That covers the Template Method pattern, a simple but powerful pattern that encapsulates the steps of an algorithm while being able to delegate some of those steps in the algorithm to subclasses.&lt;/br&gt;
There are, of course, many variations of the pattern that may not even quite resemble what I&#39;ve shown you but the idea and purpose is always the same&lt;/br&gt;
&lt;/br&gt;
Hope you enjoyed the article!</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/6593228490706730887/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/12/template-method-pattern.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/6593228490706730887'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/6593228490706730887'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/12/template-method-pattern.html' title='The Template Method Pattern'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-2535666441929068592</id><published>2011-11-29T15:53:00.001-08:00</published><updated>2012-03-04T12:39:37.206-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><title type='text'>The Abstract Factory Pattern</title><content type='html'>In our last tutorial we talked about &lt;a href=&quot;http://programyourfaceoff.blogspot.com/2011/11/factory-method-pattern.html&quot;&gt;the factory method pattern&lt;/a&gt; which is a useful way to separate out our object creation and delegate the creation specifics to creator subclasses.&lt;br /&gt;
Let&#39;s take a look at another possible Car class.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;abstract class Car
{
    //A car is made up of parts like an engine and wheels.
    Engine _engine;
    Wheel[] _wheels = new Wheel[4];

    //methods...
}
&lt;/pre&gt;
Here we have a Car class complete with parts.  The Engine and Wheel classes would also be abstract since their types could vary.  We may want a Car with a HybridEngine or special PunctureProofWheels.  Different Car subclasses like Toyota or Honda could have options for different Wheels or Engines and we want to encapsulate both the creation of Cars and its parts while keeping the whole thing flexible for extension.&lt;br /&gt;
This may seem daunting but there is a fairly simple pattern that can help called the Abstract Factory pattern.&lt;br /&gt;
In this pattern we&#39;ll make Factory interface for creating families of products like different Wheels and Engines.&lt;br /&gt;
So let&#39;s jump right in and make a CarPartFactory class.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;interface CarPartFactory
{
    Engine CreateEngine();
    Wheel[] CreateWheels();
}
&lt;/pre&gt;
Any factory class that inherits from CarPartFactory will be responsible for which concrete parts we create.  Let&#39;s make a couple to see how.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class StandardCarPartFactory : CarPartFactory
{
    public Engine CreateEngine()
    {
        return new CombustionEngine();
    }

    public Wheel[] CreateWheels()
    {
        Wheel[] wheels = new Wheel[4];
        for (int i = 0; i &amp;lt; wheels.Length; i++)
        {
            wheels[i] = new StandardCarWheel();
        }
        return wheels;
    }
}

class HybridCarPartFactory : CarPartFactory
{
    public Engine CreateEngine()
    {
        return new HybridEngine();
    }

    public Wheel[] CreateWheels()
    {
        Wheel[] wheels = new Wheel[4];
        for (int i = 0; i &amp;lt; wheels.Length; i++)
        {
            //Pucture proof wheels come standard with the hybrid.
            wheels[i] = new PunctureProofWheels();
        }
        return wheels;
    }
}
&lt;/pre&gt;
We need to make Engine and Wheel classes as well.  In this example they are very simple and the ones I wrote just print out that they are being made and what type so I&#39;ll leave them out.&lt;br /&gt;
Each Car object with be passed a CarPartFactory in its construction that will set the chosen wheels and engine.&lt;br /&gt;
Let&#39;s rework our Car class a bit.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;abstract class Car
{
    protected Engine _engine;
    protected Wheel[] _wheels = new Wheel[4];
       
    //This is where we&#39;ll call the factory methods to make its parts.
    public abstract void ConstructCar();

    public void Paint()
    {
        Console.WriteLine(&quot;Painting car...&quot;);
    }

    public void ApplyNewCarSmell()
    {
        Console.WriteLine(&quot;Applying new car smell...&quot;);
    }
}

class Toyota : Car
{
    //Each Car has a factory reference.
    CarPartFactory _factory;
        
    public Toyota(CarPartFactory factory)
    {
        _factory = factory;
        Console.WriteLine(&quot;New Toyota created.&quot;);
    }

    public override void ConstructCar()
    {
        //The factory creates the correct engine and wheels.
        _engine = _factory.CreateEngine();
        _wheels = _factory.CreateWheels();
    }
}

//The Honda class looks very similar.
&lt;/pre&gt;
That takes care of the Cars and the part creators.  We still need our old CarLot method for creating cars and choosing the correct factory.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;//This should look familiar.  It&#39;s the old Factory Method pattern!
abstract class CarLot
{
    public Car BuyCar(string type)
    {
        Car product = CreateCar(type);

        product.ConstructCar();
        product.Paint();
        product.ApplyNewCarSmell();

        return product;
    }
    //factory method...
    protected abstract Car CreateCar(string type);
}

class ToyotaCarLot : CarLot
{
    protected override Car CreateCar(string type)
    {
        CarPartFactory factory;
        //Except now the &#39;string type&#39; parameter declares a factory for creating parts.
        if (type == &quot;Hybrid&quot;)
        {
            factory = new HybridCarPartFactory();
        }
        else if (type == &quot;Standard&quot;)
        {
            factory = new StandardCarPartFactory();
        }
        else
        {
            factory = new StandardCarPartFactory();
        }
        //And we get a Toyota...
        Car car = new Toyota(factory);
        return car;
    }
}

class HondaCarLot : CarLot
{
    protected override Car CreateCar(string type)
    {
        CarPartFactory factory;
        if (type == &quot;Hybrid&quot;)
        {
            factory = new HybridCarPartFactory();
        }
        else if (type == &quot;Standard&quot;)
        {
            factory = new StandardCarPartFactory();
        }
        else
        {
            factory = new StandardCarPartFactory();
        }
        Car product = new Honda(factory);
        return product;
    }
}
&lt;/pre&gt;
Both lots have a Standard and Hybrid options but the ToyotaCarLot return Toyotas and the HondaCarLot returns Hondas.&lt;br /&gt;
Let&#39;s test it out and buy some cars.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class Program
{
    static void Main(string[] args)
    {
        CarLot _hondaLot = new HondaCarLot();
        CarLot _toyotaLot = new ToyotaCarLot();
        Car myHybrid = _hondaLot.BuyCar(&quot;Hybrid&quot;);
        Car myStandard = _toyotaLot.BuyCar(&quot;Standard&quot;);
        Console.ReadLine();
    }
}
&lt;/pre&gt;
Running this should print out this result.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSUqdKFxl6bESVHzsubi7y4nAFK92owqo25hOzTKqF5WwEBJtyTTzMAkqJIp8cy6zVHUKYWmoOn_1oVx3bY_1z1sikLD7pgvzkLMsQBAki33sDlYbeca9F1Xwtlf7gSvrqlrgLIShM_WY/s1600/abstractfactoryoutput.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;299&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSUqdKFxl6bESVHzsubi7y4nAFK92owqo25hOzTKqF5WwEBJtyTTzMAkqJIp8cy6zVHUKYWmoOn_1oVx3bY_1z1sikLD7pgvzkLMsQBAki33sDlYbeca9F1Xwtlf7gSvrqlrgLIShM_WY/s640/abstractfactoryoutput.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
That&#39;s the Abstract Factory pattern!  It encapsulates the creation of families of objects and allows for easy extension of any interface we&#39;d like, cars or parts.&lt;/br&gt;</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/2535666441929068592/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/abstract-factory-pattern.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/2535666441929068592'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/2535666441929068592'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/abstract-factory-pattern.html' title='The Abstract Factory Pattern'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSUqdKFxl6bESVHzsubi7y4nAFK92owqo25hOzTKqF5WwEBJtyTTzMAkqJIp8cy6zVHUKYWmoOn_1oVx3bY_1z1sikLD7pgvzkLMsQBAki33sDlYbeca9F1Xwtlf7gSvrqlrgLIShM_WY/s72-c/abstractfactoryoutput.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-7684615466679061214</id><published>2011-11-29T09:06:00.001-08:00</published><updated>2012-03-04T12:41:27.787-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><title type='text'>The Factory Method Pattern</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
There are a couple rules of thumb for design and refactoring that are pretty useful.  The first, as one might put it, is to &lt;i&gt;stay abstract&lt;/i&gt;.  That is, program to interfaces or abstract classes and have your objects deal with them, rather than concrete classes.  This is because we want &lt;i&gt;extendability&lt;/i&gt; in our designs.  If we stick to dealing with interfaces, we can pass along any class that inherits from that interface without issue.&lt;br /&gt;
Another important paradigm is to separate what &lt;i&gt;changes&lt;/i&gt; from what &lt;i&gt;stays the same&lt;/i&gt; and encapsulate what changes.&lt;br /&gt;
We&#39;ve seen both of these at work in every pattern so far.  In the &lt;a href=&quot;http://programyourfaceoff.blogspot.com/2011/11/strategy-pattern.html&quot;&gt;strategy pattern&lt;/a&gt; we encapsulated object behavior to allow it to change flexibly during runtime.&lt;br /&gt;
Now we&#39;re going to look at object creation and apply the same principles.&lt;br /&gt;
Taking the car example again, let&#39;s say before a car can be shipped out it needs to be prepared.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public abstract class Car
{
    //Each type of car handles these differently.
    public abstract void ConstructCar();
    public abstract void Paint();   
    public abstract void ApplyGloss();

    public void ApplyNewCarSmell()
    {
        //They really do this!
        Console.WriteLine(&quot;Spraying new car smell into car...&quot;);
    }
}
&lt;/pre&gt;
Every car that comes off the lot has to have these methods called on it before it&#39;s ready.&lt;br /&gt;
So often times when we get to creating the cars we get code that looks like this:&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public Car BuyCar(string type)
{
    Car myCar;

    if (type == &quot;Honda&quot;)
    {
        myCar = new Honda();
    }
    else if (type == &quot;ElCamino&quot;)
    {
        myCar = new ElCamino();
    }
    else if (type == &quot;Toyota&quot;)
    {
        myCar = new Toyota();
    }
    //etc...

    //prepare the car for purchase.
    myCar.ConstructCar();
    myCar.Paint();
    myCar.ApplyGloss();
    myCar.ApplyNewCarSmell();

    return myCar;
}
&lt;/pre&gt;
This clearly gets out of hand but what we can see is that the type of car varies but the initialization of the car is the same.&lt;br /&gt;
Each type of car knows how to paint itself and apply gloss, and spraying new car smell is the same for every car.&lt;br /&gt;
So we should try to separate out the creation and encapsulate it.&lt;br /&gt;
Let&#39;s do this by creating a class that handles Car creation.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public class SimpleCarFactory
{
    public Car CreateCar(string type)
    {
        Car myCar;

        if (type == &quot;Honda&quot;)
        {
            myCar = new Honda();
        }
        else if (type == &quot;ElCamino&quot;)
        {
            myCar = new ElCamino();
        }
        else if (type == &quot;Toyota&quot;)
        {
            myCar = new Toyota();
        }
        //etc...
        
        return myCar;
    }
}
&lt;/pre&gt;
Now let&#39;s create a client class to buy cars from.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public class CarLot
{
    //Contains a reference to a factory object.
    SimpleCarFactory _carFactory;
    
    public CarLot(SimpleCarFactory carFactory)
    {
        _carFactory = carFactory;
    }

    public Car BuyCar(string type)
    {
        //Delegates creation to the factory object.
        Car product = _carFactory.CreateCar(type);

        //This is the same...
        product.ConstructCar();
        product.Paint();
        product.ApplyGloss();
        product.ApplyNewCarSmell();
        
        return product;
    }
}
&lt;/pre&gt;
This is called a Simple Factory.  It&#39;s commonly used but isn&#39;t technically considered a design pattern.&lt;br /&gt;
What we would ideally like is a higher level of abstraction in the Creator class.  There may be different CarLots that prepare there cars differently.  Maybe certain brands of paint aren&#39;t available in certain regions or worse the steering wheel is on a different side!&lt;br /&gt;
&lt;br /&gt;
This conveniently brings us to the Factory Method Pattern.  Let&#39;s change our CarLot class a little:&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public abstract class CarLot
{
    public Car BuyCar(string type)
    {
        //Now this calls a method from within our CarLot.
        Console.WriteLine(&quot;Creating your &quot; + GetType().ToString());
        Car product = CreateCar(type);

        product.ConstructCar();
        product.Paint();
        product.ApplyGloss();
        product.ApplyNewCarSmell();
        
        return product;
    }

    //Each CarLot handles their own Car creation.
    protected abstract Car CreateCar(string type);
}
&lt;/pre&gt;
And make two different lots, a Unitited States CarLot and a United Kingdoms CarLot.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public class USCarLot : CarLot
{
    protected override Car CreateCar(string type)
    {
        Car product;
        if (type == &quot;Honda&quot;)
        {
            //We have new subclasses for US Cars now.
            product = new USHonda();
        }
        else if (type == &quot;Toyota&quot;)
        {
            product = new USToyota();
        }
        //etc...
        else
        {
            return null
        }
        return product;
    }
}

public class UKCarLot : CarLot
{
    protected override Car CreateCar(string type)
    {
        Car product;
        if (type == &quot;Honda&quot;)
        {
            //And new subclasses for UK Cars now.
            product = new UKHonda();
        }
        else if (type == &quot;Toyota&quot;)
        {
            product = new UKToyota();
        }
        //etc...
        else
        {
            return null
        }

        return product;
    }
}
&lt;/pre&gt;
Now for the cars.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public class USHonda : Car
{
    public override ConstructCar()
    {
        Console.WriteLine(&quot;Steering wheel goes on the left.&quot;);
    }

    public override Paint()
    {
        Console.WriteLine(&quot;Painting car...&quot;);
    }

    public override ApplyGloss()
    {
        Console.WriteLine(&quot;Applying glossy finish...&quot;);
    }

}

public class UKHonda : Car
{
    public override ConstructCar()
    {
        Console.WriteLine(&quot;Steering wheel goes on the right.&quot;);
    }

    public override Paint()
    {
        Console.WriteLine(&quot;Painting car...&quot;);
    }

    public override ApplyGloss()
    {
        Console.WriteLine(&quot;Applying glossy finish...&quot;);
    }
}

//In our simple example, the Toyota classes look similar...
&lt;/pre&gt;
Now let&#39;s say we want to buy a car.  First we choose a type of CarLot to make, then we choose the type of car we want, finally we call the the CarLot&#39;s BuyCar method passing in the appropriate string.  The type of care that comes out depends on the CarLot that we chose.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class Program
{
    static void Main(string[] args)
    {
        CarLot usCarLot = new USCarLot();
        CarLot ukCarLot = new UKCarLot();

        Car myUSHonda = usCarLot.BuyCar(&quot;Honda&quot;);
        Car myUKHonda = ukCarLot.BuyCar(&quot;Honda&quot;);

        Console.ReadLine();
    }
}
&lt;/pre&gt;
And the output should read:&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;
Creating your USHonda&lt;br /&gt;
Steering wheel goes on the left.&lt;br /&gt;
Painting car...&lt;br /&gt;
Applying glossy finish...&lt;br /&gt;
Creating your UKHonda&lt;br /&gt;
Steering wheel goes on the right.&lt;br /&gt;
Painting car...&lt;br /&gt;
Applying glossy finish...&lt;br /&gt;
&lt;/b&gt;
&lt;br /&gt;
&lt;br /&gt;
That&#39;s the Factory Method pattern and it, like all factories, encapsulates object creation.  It gives us an interface for creating objects while allowing specific instances of that interface to decide which class to instantiate.&lt;br /&gt;
To wrap up, let&#39;s take a look at the class diagram.
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgaX1jZ-JrQegGI0qCbf9AZWiXhzioyBkUyh_Hrt0q69qVgOddP-uk-2o9UQ4cIMcUyNqsuHI6YdKTUQoMrHb3MHQay18k3cR6lQzpSuE70ekNE3laLINDrO1UxbIyJUA-VDHz1uONLzmM/s1600/factory_method_pattern.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;270&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgaX1jZ-JrQegGI0qCbf9AZWiXhzioyBkUyh_Hrt0q69qVgOddP-uk-2o9UQ4cIMcUyNqsuHI6YdKTUQoMrHb3MHQay18k3cR6lQzpSuE70ekNE3laLINDrO1UxbIyJUA-VDHz1uONLzmM/s400/factory_method_pattern.jpg&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
In the Creator we have a &#39;factory method&#39; that all subclasses must implement so the ConcreteCreator actually makes the product and is responsible for which ConcreteProduct to make.&lt;/br&gt;
Each ConcreteProduct must implement the Product interface so that classes dealing with the products all have a common interface they know how to manipulate.&lt;/br&gt;
&lt;/br&gt;
That&#39;s it for this article and thanks for reading!</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/7684615466679061214/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/factory-method-pattern.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/7684615466679061214'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/7684615466679061214'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/factory-method-pattern.html' title='The Factory Method Pattern'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgaX1jZ-JrQegGI0qCbf9AZWiXhzioyBkUyh_Hrt0q69qVgOddP-uk-2o9UQ4cIMcUyNqsuHI6YdKTUQoMrHb3MHQay18k3cR6lQzpSuE70ekNE3laLINDrO1UxbIyJUA-VDHz1uONLzmM/s72-c/factory_method_pattern.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-8745291416262730054</id><published>2011-11-27T08:38:00.001-08:00</published><updated>2012-03-04T12:47:56.566-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Content Pipeline"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><category scheme="http://www.blogger.com/atom/ns#" term="XNA"/><title type='text'>The XML Content Importer</title><content type='html'>A while ago, &lt;a href=&quot;http://programyourfaceoff.blogspot.com/2011/06/content-pipeline-tutorial-00.html&quot;&gt;I wrote a quick rundown&lt;/a&gt; of XNA&#39;s Content Pipeline, the classes needed to extend it and how they work together.  However for the most part, one wouldn&#39;t need to do all that since the built in XML Importer is so powerful.  One can load almost any class through the content pipeline using only XML.&lt;/br&gt;
We&#39;ll go few some examples to illustrate this.&lt;/br&gt;
If you want to follow along with the code, go ahead and make a new XNA Game Project.  I named mine XMLPipelineTutorial.&lt;/br&gt;
Right click on the Content Project, select Add New Item... and select XML file.  I named mine SimpleString.xml because that&#39;s what it will load.  The following XML should appear:&lt;/br&gt;
&lt;/br&gt;
&lt;pre class=&quot;brush:xml&quot; name=&quot;code&quot;&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;
&amp;lt;XnaContent&amp;gt;
  &amp;lt;!-- TODO: replace this Asset with your own XML asset data. --&amp;gt;
  &amp;lt;Asset Type=&amp;quot;System.String&amp;quot;&amp;gt;&amp;lt;/Asset&amp;gt;
&amp;lt;/XnaContent&amp;gt;
&lt;/pre&gt;
The Node named Asset has an attribute called Type which is set to &quot;System.String&quot;.  This is what will be returned when we call the Content Manager&#39;s Load method.&lt;/br&gt;
What we put inside the Asset tags is the actual content&lt;/br&gt;
I&#39;ve changed the XML to look like this:&lt;/br&gt;
&lt;/br&gt;
&lt;pre class=&quot;brush:xml&quot; name=&quot;code&quot;&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;
&amp;lt;XnaContent&amp;gt;
  &amp;lt;Asset Type=&amp;quot;System.String&amp;quot;&amp;gt;
    Hello World!
  &amp;lt;/Asset&amp;gt;
&amp;lt;/XnaContent&amp;gt;
&lt;/pre&gt;
Now in Game1.cs I changed the LoadContent() method so it looks like this:&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);

    string xmlContent = Content.Load&amp;lt;string&amp;gt;(&amp;quot;SimpleString&amp;quot;);
    Console.WriteLine(xmlContent);
}
&lt;/pre&gt;
The line Console.WriteLine(xmlContent) is a little trick I use for debugging games when I don&#39;t want to bother loading a font and drawing it on the screen.  The output appears on the &#39;Output&#39; window which you can find in Visual Studio via Debug -&gt; Windows -&gt; Output.&lt;/br&gt;
Easy enough.  We can load arrays of things:&lt;/br&gt;
&lt;/br&gt;
&lt;pre class=&quot;brush:xml&quot; name=&quot;code&quot;&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;
&amp;lt;XnaContent&amp;gt;
  &amp;lt;!-- TODO: replace this Asset with your own XML asset data. --&amp;gt;
  &amp;lt;Asset Type=&amp;quot;System.Int32[]&amp;quot;&amp;gt;
    4 5 1 6 9 4 10 100032
  &amp;lt;/Asset&amp;gt;
&amp;lt;/XnaContent&amp;gt;
&lt;/pre&gt;
I named this one IntegerArray.xml.&lt;/br&gt;
We can load this just as easily.&lt;/br&gt;
&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);

    string xmlContent = Content.Load&amp;lt;string&amp;gt;(&amp;quot;SimpleString&amp;quot;);
    Console.WriteLine(xmlContent);

    int[] xmlContent2 = Content.Load&amp;lt;int[]&amp;gt;(&amp;quot;IntegerArray&amp;quot;);
    for (int i = 0; i &amp;lt; xmlContent2.Length; i++)
    {
        Console.WriteLine(xmlContent2[i].ToString());
    }
}
&lt;/pre&gt;
This is all very well and good but doesn&#39;t really show off the flexibility.  Let&#39;s import a Dictionary of Vectors keyed by Rectangles just for kicks.&lt;/br&gt;
&lt;/br&gt;
&lt;pre class=&quot;brush:xml&quot; name=&quot;code&quot;&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;
&amp;lt;XnaContent&amp;gt;
  &amp;lt;!-- TODO: replace this Asset with your own XML asset data. --&amp;gt;
  &amp;lt;Asset Type=&amp;quot;System.Collections.Generic.Dictionary[Microsoft.Xna.Framework.Rectangle, 
         Microsoft.Xna.Framework.Vector2]&amp;quot;&amp;gt;
    &amp;lt;Item&amp;gt;
      &amp;lt;Key&amp;gt;0 12 24 5&amp;lt;/Key&amp;gt;
      &amp;lt;Value&amp;gt;5 5.4&amp;lt;/Value&amp;gt;
    &amp;lt;/Item&amp;gt;
    &amp;lt;Item&amp;gt;
      &amp;lt;Key&amp;gt;12 3 6 2&amp;lt;/Key&amp;gt;
      &amp;lt;Value&amp;gt;0 0&amp;lt;/Value&amp;gt;
    &amp;lt;/Item&amp;gt;
  &amp;lt;/Asset&amp;gt;
&amp;lt;/XnaContent&amp;gt;
&lt;/pre&gt;
Each KeyValuePair in the Dictionary is put in between Item nodes.  We could had done this for the simple array but we don&#39;t have to.  Each Key and Value is inside a node of the same name.  The XML importer uses reflection to figure out what&#39;s what (which is why it&#39;s so flexible and powerful).&lt;/br&gt;
The Keys, being rectangles are just a list of int&#39;s representing X, Y, Width and Height respectively and the Values being Vectors are written as two float&#39;s X and Y, respectively.  For some reason the pipeline expects these to be in this format and won&#39;t let me put values between Width/Height tags or X/Y tags.  I suppose for convenience.&lt;/br&gt;
Now to load and test it out.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);

    Dictionary&amp;lt;Rectangle, Vector2&amp;gt; xmlContent = 
        Content.Load&amp;lt;Dictionary&amp;lt;Rectangle, Vector2&amp;gt;&amp;gt;(&amp;quot;VectorRectangleDictionary&amp;quot;);

    foreach (Rectangle rectangle in xmlContent.Keys)
    {
        Console.WriteLine(rectangle.ToString());
    }

    foreach (Vector2 vector in xmlContent.Values)
    {
        Console.WriteLine(vector.ToString());
    }
}
&lt;/pre&gt;
And all is as it should be.&lt;/br&gt;
But these are all classes from preexisting libraries, one might point out, what if I want to load my own class?&lt;/br&gt;
Not a problem!  Since the XML importers uses reflection, we can load any class we want through it.&lt;/br&gt;
To do this though we must add a Game Library Project to keep any classes we want to load.  Then add a reference to that project in the content project.&lt;/br&gt;
We need the Library Project because the content project doesn&#39;t know anything about the XMLPipelineTutorial namespace so it won&#39;t be able to find any types you try to give it and trying to add a reference to it would cause a circular dependency.&lt;/br&gt;
Remember to add a reference to the Game Library not only in the content project but also the main game project.&lt;/br&gt;
Here&#39;s a simple class:&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public class GameItem
{
    public string Name = null;
    public double Value;
}
&lt;/pre&gt;
And here&#39;s an XML file for loading it:&lt;/br&gt;
&lt;pre class=&quot;brush:xml&quot; name=&quot;code&quot;&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;
&amp;lt;XnaContent&amp;gt;
  &amp;lt;Asset Type=&amp;quot;XMLTutorialData.GameItem&amp;quot;&amp;gt;
    &amp;lt;Name&amp;gt;Sword&amp;lt;/Name&amp;gt;
    &amp;lt;Value&amp;gt;350&amp;lt;/Value&amp;gt;
  &amp;lt;/Asset&amp;gt;
&amp;lt;/XnaContent&amp;gt;
&lt;/pre&gt;
Make sure the namespace in the Type attribute match yours.&lt;/br&gt;
Now we can load it just like any other asset&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);

    GameItem item = Content.Load&amp;lt;GameItem&amp;gt;(&amp;quot;Item&amp;quot;);

    Console.WriteLine(item.Name + &amp;quot; &amp;quot; + item.Value.ToString());
}
&lt;/pre&gt;
And you should see, &quot;Sword 350&quot; in the output window.&lt;/br&gt;
There is a subtlety here that&#39;s worth pointing out.  To illustrate I&#39;ve defined another GameItem object and loaded it with the same file.  Here&#39;s the new LoadContent method.  See if you can predict the output before running.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);

    GameItem itemOne = Content.Load&amp;lt;GameItem&amp;gt;(&amp;quot;Item&amp;quot;);
    GameItem itemTwo = Content.Load&amp;lt;GameItem&amp;gt;(&amp;quot;Item&amp;quot;);

    Console.WriteLine(itemOne.Name + &amp;quot; &amp;quot; + itemOne.Value.ToString());
    Console.WriteLine(itemOne.Name + &amp;quot; &amp;quot; + itemOne.Value.ToString());

    //Changed the name of itemOne...
    itemOne.Name = &amp;quot;Boot&amp;quot;;

    //Print out the name of itemTwo.
    Console.WriteLine(itemTwo.Name);
}
&lt;/pre&gt;
What the?!  Changing itemOne&#39;s name changed itemTwo&#39;s name as well!  This is because GameItem is a &lt;i&gt;reference&lt;/i&gt; object.  What we have are two references to the same object.  Go ahead and try this with a &lt;i&gt;value&lt;/i&gt; type like a single integer or a Vector2 object and you won&#39;t get the same behavior.&lt;/br&gt;
&lt;/br&gt;
The importer will by default only deserialize public fields and properties.  If you have private fields you&#39;d like to add you must mark them with a [ContentSerializer] attribute and if you have public fields or properties you&#39;d like ignored by the serializer, you must use the [ContentSerializerIgnor] attribute (excluding readonly fields and properties).&lt;/br&gt;
So let&#39;s change the GameItem class so not everything is public.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public class GameItem
{
    [ContentSerializer]
    string _name = null;
    [ContentSerializer]
    double _value;

    public string Name
    {
        get { return _name; }
    }

    public double Value
    {
        get { return _value; }
    }
}
&lt;/pre&gt;
The Name and Value properties are readonly so they don&#39;t require an attribute to ignore them.&lt;/br&gt;
Here&#39;s the new Item.xml where the node names match the new field names&lt;/br&gt;
&lt;pre class=&quot;brush:xml&quot; name=&quot;code&quot;&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;
&amp;lt;XnaContent&amp;gt;
  &amp;lt;Asset Type=&amp;quot;XMLTutorialData.GameItem&amp;quot;&amp;gt;
    &amp;lt;_name&amp;gt;Sword&amp;lt;/_name&amp;gt;
    &amp;lt;_value&amp;gt;350&amp;lt;/_value&amp;gt;
  &amp;lt;/Asset&amp;gt;
&amp;lt;/XnaContent&amp;gt;
&lt;/pre&gt;
And this works exactly the same as before except the GameItem class is better encapsulated.&lt;/br&gt;
That&#39;s all for now.  The built in XML importer has a lot of features and is quite flexible.  There&#39;s a lot more to explore and perhaps I&#39;ll go into more in future articles.&lt;/br&gt;
&lt;/br&gt;
Update:
I cam across &lt;a href=&quot;http://gamedev.stackexchange.com/questions/11230/how-to-use-xml-files-as-content-files-in-xna&quot;&gt;this question&lt;/a&gt; in StackOverflow where someone&#39;s demonstrated a nice way to print out how exactly the intermediate serializer expects to see your .xml formatted for some specific object.  Definitely worth checking out.</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/8745291416262730054/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/xml-content-importer.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/8745291416262730054'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/8745291416262730054'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/xml-content-importer.html' title='The XML Content Importer'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-6735160866777145059</id><published>2011-11-26T10:30:00.001-08:00</published><updated>2012-03-04T12:48:33.373-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><title type='text'>The State Pattern</title><content type='html'>The State Pattern allows for a class to change its behavior dynamically according to an internal state.&lt;/br&gt;
Let&#39;s say we want to design an Enemy class for a game.  An Enemy object will be behaving differently depending on it&#39;s hit points or other stats, or what&#39;s happening around it in the world.  If its hit points are low then maybe we use a different animation where it limps and if its hit points reach zero it dies. If it&#39;s aware of the Player it may start chasing, attacking, or evading behavior or when nothing in particular is going on perhaps it wanders around or patrols an area.&lt;/br&gt;
&lt;/br&gt;
First let&#39;s try representing the Enemy&#39;s state with an &lt;a href=&quot;http://en.wikipedia.org/wiki/Enumerated_type#C.23&quot;&gt;enumerator&lt;/a&gt; giving it only a couple states at first and throw together a quick Enemy class with some methods.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public enum EnemyState
{
    Idle,
    Dead,
}

public class Enemy
{
    int _hitPoints = 20;
    EnemyState _state = EnemyState.Idle;
    
    public void WanderAround()
    {
        if (_state != EnemyState.Dead)
        {
            _state = EnemyState.Idle;
            Console.WriteLine(&quot;The Enemy aimlessly wanders...&quot;);
        }
        else
        {
            Console.WriteLine(&quot;The Enemy is dead so it can&#39;t wander around.&quot;);
        }
    }

    public void TakeDamage(int damage)
    {
        if (_state != EnemyState.Dead)
        {
            _hitPoints -= damage;
            Console.WriteLine(&quot;Enemy takes &quot; + damage.ToString() + &quot; points of damage&quot;);
            if (_hitPoints &lt;= 0)
            {
                _state = EnemyState.Dead;
                Console.WriteLine(&quot;Enemy is dead!&quot;);
            }
        }
        else
        {
            Console.WriteLine(&quot;Hit points already at zero.&quot;);
        }
    }
    
    public void Attack()
    {
        if (_state != EnemyState.Dead)
        {
            Console.WriteLine(&quot;The Enemy attacks!&quot;);
        }
    }
}
&lt;/pre&gt;
Pretty straight forward.  The methods&#39; behaviors depend on the internal state object, and the state is changed depending on internal conditions, completely hidden from the user.  Seems okay until we need to add new states.  Let&#39;s add an Evading state.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public enum EnemyState
{
    Idle,
    Dead,
    Evading,
}

public class Enemy
{
    int _hitPoints = 20;
    EnemyState _state = EnemyState.Idle;
    
    public void WanderAround()
    {
        if (_state == EnemyState.Dead)
        {
            Console.WriteLine(&quot;The Enemy is dead so it can&#39;t wander around.&quot;);
        }       
        else if (_state == EnemyState.Evading)
        {
            Console.WriteLine(&quot;The Enemy can&#39;t wander around while it&#39;s running away!&quot;);
        }
        else 
        {
            _state = EnemyState.Idle;
            Console.WriteLine(&quot;The Enemy aimlessly wanders...&quot;);
        }
    }

    public void TakeDamage(int damage)
    {
        if (_state != EnemyState.Dead)
        {
            _hitPoints -= damage;
            Console.WriteLine(&quot;Enemy takes &quot; + damage.ToString() + &quot; points of damage&quot;);
            
            if (_hitPoints &lt;= 5)
            {
                //If the enemy&#39;s hit points drops low enough it 
                //becomes scared and runs away.
                _state = EnemyState.Evading;
                Console.WriteLine(&quot;Enemy is running away!&quot;);
            }
            if (_hitPoints &lt;= 0)
            {
                _state = EnemyState.Dead;
                Console.WriteLine(&quot;Enemy is dead!&quot;);
            }
        }
        else
        {
            Console.WriteLine(&quot;Hit points already at zero.&quot;);
        }
    }
    
    //A method to call when the enemy &#39;feels safe&#39;
    //enough to go back to its Idle state.
    public void StopEvading()
    {
        if (_state == EnemyState.Dead)
        {
            Console.WriteLine(&quot;The enemy is dead&quot;);
        }
        else
        {
            _state = EnemyState.Idle;
            //Start wandering aimlessly...
            WanderAround();
        }
    }

    public void Attack()
    {
        if (_state == EnemyState.Dead)
        {
            Console.WriteLine(&quot;The Enemy can&#39;t attack while dead.&quot;);
        }
        else if (_state == EnemyState.Evading)
        {
            Console.WriteLine(&quot;The Enemy won&#39;t attack if it&#39;s running away.&quot;);
        }
        else
        {
            Console.WriteLine(&quot;The Enemy attacks!&quot;);
        }
    }
}
&lt;/pre&gt;
Keeping track of the internal state is starting to become complicated.  Every time we add a new state we need to account for it in every method, and if we want to add a method we need to account for the state how the state effects it and how it may change the state.&lt;/br&gt;
The State Pattern handles this by representing a state as an object itself.  These state objects will handle the enemy&#39;s behavior when it is in the corresponding state.&lt;/br&gt;
Each State class will implement methods to handle requests from the enemy.&lt;/br&gt;
Let&#39;s look at some code.  First we&#39;ll implement a State interface.  This will replace our enum entirely.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public interface EnemyState
{
    void HandleWanderAround();
    void HandleDamage(int hitPoints);
    void HandleStopEvading();
    void HandleAttack();
}
&lt;/pre&gt;
Notice the method stubs are similar but not exactly like the ones in the Enemy class.  The enemy will make requests to its state which will call the appropriate handling method.&lt;/br&gt;
Now let&#39;s rework the Enemy class.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public class Enemy
{
    int _hitPoints = 20;
    EnemyState _state;
    
    public Enemy()
    {
        //We need to initialize the state to something other than null.
        _state = new IdleState(this);
    }

    public void WanderAround()
    {
        _state.HandleWanderAround();
    }

    public void TakeDamage(int damage)
    {
        _hitPoints -= damage;
        _state.HandleDamage(_hitPoints);
    }
   
    public void StopEvading()
    {
        _state.HandleStopEvading();
    }

    public void Attack()
    {
        _state.HandleAttack();
    }

    public EnemyState GetState()
    {
        return _state;
    }

    public void SetState(EnemyState state)
    {
        _state = state;
    }
}
&lt;/pre&gt;
Much more concise, let&#39;s code our IdleState class to see how this works.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public class IdleState : EnemyState
{
    Enemy _enemy;

    public IdleState(Enemy enemy)
    {
        _enemy = enemy;
    }

    public void HandleWanderAround()
    {
        Console.WriteLine(&quot;The enemy wanders around.&quot;);
    }

    public void HandleDamage(int hitPoints)
    {
        if (hitPoints &lt;= 5 &amp;&amp; hitPoints &gt; 0)
        {
            _enemy.SetState(new EvadingState(_enemy));
        }
        if (hitPoints &lt;= 0)
        {
            _enemy.SetState(new DeadState(_enemy));
        }
    }

    public void HandleStopEvading()
    {
        Console.WriteLine(&quot;The enemy isn&#39;t evading.&quot;);     
    }

    public void HandleAttack()
    {
        Console.WriteLine(&quot;The enemy attacks!&quot;);
    }
}
&lt;/pre&gt;
No long string of state checks required since we know that if these methods are being called, then this is the state the enemy is in.  We have a reference to the enemy in case we want to set it&#39;s state from another.&lt;/br&gt;
Let&#39;s finish up with our DeadState and EvadingState classes.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public class EvadingState : EnemyState
{
    Enemy _enemy;

    public EvadingState(Enemy enemy)
    {
        _enemy = enemy;
    }

    public void HandleWanderAround()
    {
        Console.WriteLine(&quot;The enemy can&#39;t wander around if it&#39;s evading!&quot;);
    }

    public void HandleDamage(int hitPoints)
    {
        if (hitPoints &lt;= 0)
        {
            _enemy.SetState(new DeadState(_enemy));
        }
    }

    public void HandleStopEvading()
    {
        _enemy.SetState(new IdleState(_enemy));
        _enemy.WanderAround();   
    }

    public void HandleAttack()
    {
        Console.WriteLine(&quot;The enemy won&#39;t attack if it&#39;s running away.&quot;);
    }
}
&lt;/pre&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public class DeadState : EnemyState
{
    Enemy _enemy;

    public DeadState(Enemy enemy)
    {
        _enemy = enemy;
    }

    public void HandleWanderAround()
    {
        Console.WriteLine(&quot;The enemy can&#39;t wander around if it&#39;s dead!&quot;);
    }

    public void HandleDamage(int hitPoints)
    {
        Console.WriteLine(&quot;The enemy is already dead.&quot;);
    }

    public void HandleStopEvading()
    {
        Console.WriteLine(&quot;The enemy is dead.&quot;);   
    }

    public void HandleAttack()
    {
        Console.WriteLine(&quot;The enemy can&#39;t attack if it&#39;s dead.&quot;);
    }
}
&lt;/pre&gt;
Everything about an enemy&#39;s behavior while it&#39;s in a certain state is encapsulated in these State classes.  We can change State behavior easier because we know where all the code associated with that state is and we can easily add new States without altering much existing code.&lt;/br&gt;
If you&#39;ve noticed a similarity between the State Pattern and the Strategy Pattern, that&#39;s no coincidence; they&#39;re very similar.  However the State Pattern acts more autonomously, switching from one state to the other based on internal criteria, on its own without the user even being aware of it.  The user just calls the Enemy&#39;s methods and get the correct behavior!&lt;/br&gt;
Thanks for reading and I hope you&#39;re enjoying this series on design patterns!</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/6735160866777145059/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/state-pattern.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/6735160866777145059'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/6735160866777145059'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/state-pattern.html' title='The State Pattern'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-4745083318175470588</id><published>2011-11-25T19:00:00.001-08:00</published><updated>2012-03-04T12:48:52.092-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><title type='text'>The Singleton Pattern</title><content type='html'>The Singleton Pattern is a way of making sure that only one instance of a class gets instantiated.  It also sets up a global access point for the object.&lt;br /&gt;
Having a class that we can only have one instance of can be useful if, say, our class held a sort of global library of data.  The Singleton would make sure there&#39;d never be any confusion over the values of our data, ie. they never come up with two conflicting values, and we would also have a way of retrieving things from our global pool of data from anywhere.&lt;br /&gt;
The UML diagram looks very trivial for this pattern because of how simple it is.  However, it does have its subtleties.  Let&#39;s take a look.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjhGEq9Id-yJgz2m0KQ6J9s3HD-xggWIcHUTovadneHr8kd8AskIiCnH3jz1Frp-GOfnOpvy_81T_2c2_i2WXIbb2FL-aN1hLEMgX64l3QQChcbHLlJfVUKOSkhPH0Fgp1sW86_oUPyDaY/s1600/singleton_pattern.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;180&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjhGEq9Id-yJgz2m0KQ6J9s3HD-xggWIcHUTovadneHr8kd8AskIiCnH3jz1Frp-GOfnOpvy_81T_2c2_i2WXIbb2FL-aN1hLEMgX64l3QQChcbHLlJfVUKOSkhPH0Fgp1sW86_oUPyDaY/s320/singleton_pattern.jpg&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
The class contains an instance of itself (the one and only one instance) and a method for retrieving that instance.&lt;br /&gt;
Let&#39;s take a closer look&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public class Singleton
{
    static Singleton _uniqueInstance;
    
    Singleton() { }

    public static Singleton GetInstance()
    {
        if (_uniqueInstance == null)
        {
            _uniqueInstance = new Singleton();
        }
        return _uniqueInstance;
    }
}
&lt;/pre&gt;
Perhaps you&#39;ve noticed the private constructor.  This is the key to the pattern.  With a private constructor, we can only call new Singleton() from within the Singleton class itself.  This allows us to have the class carefully monitor how it&#39;s instantiated through the public static method Singleton.GetInstance(), our global access point to the unique instance.&lt;br /&gt;
The first time we call Singleton.GetInstance(), the method checks to see if _uniqueInstance is null and since it is, it assigns a new Singleton() to _uniqueInstance and returns it.&lt;br /&gt;
The next time we call Singleton.GetInstance() (and every time afterwards), the check for null, returns false and the method returns the one and only one instance.&lt;br /&gt;
&lt;br /&gt;
There is a problem with this set up as is though and maybe you&#39;ve already noticed it.  It isn&#39;t &lt;i&gt;thread safe&lt;/i&gt;.  If two threads were both accessing Singleton.GetInstance(), we could run into problems.  Let&#39;s walk through a possible method call to see why.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Thread 1:&lt;/b&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
if (_uniqueInstance == null) //Thread 1 evaluates this to true
&lt;/pre&gt;
&lt;/br&gt;
&lt;b&gt;Thread 2 gets a turn:&lt;/b&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
if (_uniqueInstance == null) //Thread 2 also evaluates this to true
&lt;/pre&gt;
&lt;/br&gt;
&lt;b&gt;Thread 1:&lt;/b&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
_uniqueInstance = new Singleton(); //Thread 1 creates a new object.
return _uniqueInstance;
&lt;/pre&gt;
&lt;/br&gt;
&lt;b&gt;Thread 2&#39;s turn once again&lt;/b&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
_uniqueInstance = new Singleton(); //Thread 2 calls the constructor again.
return _uniqueInstance;
&lt;/pre&gt;
Oh no!  Since Thread 2 had already evaluated true for the null check, it calls the constructor again and we get a second instance of _uniqueObject completely breaking everything!&lt;/br&gt;
Luckily, there&#39;s a way around this using the lock keyword.&lt;/br&gt;
lock essentially forces a thread to complete a section of code before another thread can get a turn.&lt;/br&gt;
Here&#39;s our new Singleton class:
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public class Singleton
{
    static Singleton _uniqueInstance;
    static readonly object padLock = new object();

    Singleton() { }

    public static Singleton GetInstance()
    {
        lock(padLock)
        {
            if (_uniqueInstance == null)
            {
                _uniqueInstance = new Singleton();
            }
            return _uniqueInstance;
        }
    }
}
&lt;/pre&gt;
&lt;/br&gt;
That&#39;s it!  A simple but powerful way to make sure an object only ever has one instance.&lt;/br&gt;
&lt;/br&gt;
Thanks for reading!</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/4745083318175470588/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/singleton-pattern.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/4745083318175470588'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/4745083318175470588'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/singleton-pattern.html' title='The Singleton Pattern'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjhGEq9Id-yJgz2m0KQ6J9s3HD-xggWIcHUTovadneHr8kd8AskIiCnH3jz1Frp-GOfnOpvy_81T_2c2_i2WXIbb2FL-aN1hLEMgX64l3QQChcbHLlJfVUKOSkhPH0Fgp1sW86_oUPyDaY/s72-c/singleton_pattern.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-8798206093412645603</id><published>2011-11-25T07:11:00.001-08:00</published><updated>2012-03-04T12:51:25.384-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><title type='text'>The Decorator Pattern</title><content type='html'>Subclassing is a powerful way of extending the behavior of a class while keeping what was already there intact.  And is, of course, an integral part of object oriented programming.  It does however have its drawbacks.  I&#39;ll illustrate some with a simple example.&lt;br /&gt;
&lt;br /&gt;
Let&#39;s say you&#39;re in a shop selling a dagger.  Maybe there is a base price for the dagger but what you get for the dagger can rely on many factors.  The type and quality of the dagger for example, and perhaps there&#39;s even an enchantment on it that increases it&#39;s value.&lt;br /&gt;
So, let&#39;s say a dagger class looks something like this:&lt;br /&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;public abstract class Dagger
{
    public abstract double GetValue();
}
&lt;/pre&gt;
Short, yes but this is all we need for our example.&lt;br /&gt;
We&#39;ll make a new class now, BronzeDagger, that will inherit from our Dagger class.&lt;br /&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;public class BronzeDagger : Dagger
{   
    public double GetValue()
    {
        //Return the dagger&#39;s base value.
        return 200d;
    }
}
&lt;/pre&gt;
Seems okay so far... we could continue, easily enough to make more classes for Iron, Silver, etc.&lt;br /&gt;
But what about that enchantment?  If we were to continue in this fashion we&#39;d be forced to make EnchantedBronzeDagger classes and EnchantedSilverDaggerClasses.&lt;br /&gt;
&lt;br /&gt;
Perhaps though, one might suggest that we simply keep track of fields inside the base class like condition and an enchantment type of some kind.  Let&#39;s see what that would look like.&lt;br /&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;public abstract class Dagger
{
    double _conditionFactor = .74d;
    double _enchantmentFactor = 2d;

    public abstract double GetValue();

    public double GetConditionFactor()
    {
        return _conditionFactor;
    }

    public double GetEnchantmentFactor()
    {
        return _enchantmentFactor;
    }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;public class BronzeDagger : Dagger
{
    public double GetValue()
    {
        return 200d * GetCondition() * GetEnchantmentFactor();
    }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;public class SilverDagger : Dagger
{
    public double GetValue()
    {
        return 500d * GetCondition() * GetEnchantmentValue();
    }
}
&lt;/pre&gt;
&lt;br /&gt;
However, as more price altering factors are needed, the amount of code we have to write gets out of hand and we&#39;d be forced to change the base class code each time.&lt;br /&gt;
&lt;br /&gt;
The Decorator Pattern allows us to extend behavior dynamically without subclassing and without altering existing code.&lt;br /&gt;
The basic idea is to encapsulate the extended behavior into their own classes.  We &#39;wrap&#39; these extended behaviors, or &lt;i&gt;decorators&lt;/i&gt; around the class we wish to add to.&lt;br /&gt;
&lt;br /&gt;
Here&#39;s what a UML diagram for the Decorator pattern looks like:&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvgLUFfv3lTH_SF2m4qxnAbfedlgMLrm_OMgSSGcZdUykLWnceEjOEyzdg5JmkLFkY8PJ_0-pnWk5ncvPiDa0HBNl4tcLwcc5DUz1b00SCZ6GcVtNEn6vFLUUalurv-ZPWX2mvDYb_ccE/s1600/decorator_pattern.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;338&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvgLUFfv3lTH_SF2m4qxnAbfedlgMLrm_OMgSSGcZdUykLWnceEjOEyzdg5JmkLFkY8PJ_0-pnWk5ncvPiDa0HBNl4tcLwcc5DUz1b00SCZ6GcVtNEn6vFLUUalurv-ZPWX2mvDYb_ccE/s400/decorator_pattern.jpg&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
The Component would be the object we wish to decorate.  The Decorator class inherits from this base class and also contains a reference to one.  In this diagram it&#39;s the abstract decorator that contains a Component reference which is fine, probably ideal, but for this quick example the Component reference is kept in the ConcreteDecorator classes.  Finally there is a ConcreteComponent which inherits from the Component class as well.&lt;/br&gt;
That&#39;s the set-up, but how we use it will become clearer as we move along.&lt;/br&gt;
&lt;/br&gt;
In our example we&#39;d still have our base abstract Dagger (our Component) class:&lt;br /&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;public abstract class Dagger
{
    public abstract double GetValue();
}
&lt;/pre&gt;
And some subclasses:&lt;br /&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;public class BronzeDagger : Dagger
{
    public double GetValue()
    {
        return 200d;
    }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;public class SilverDagger : Dagger
{
    public double GetValue()
    {
        return 200d;
    }
}
&lt;/pre&gt;
&lt;br /&gt;
Now we&#39;ll make our abstract decorator class.
&lt;br /&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;public abstract class DaggerDecorator : Dagger
{
    public abstract double GetValue();
}
&lt;/pre&gt;
It&#39;s important to note here while decorator class inherits from Dagger we&#39;re not using it in the normal sense.  We&#39;re using it here for the type matching or mirroring.  Let&#39;s make some concrete decorators.
&lt;br /&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;public abstract class EnchantmentDecorator : DaggerDecorator
{
    //We have a reference to the object (or its outer most wrapper)
    //that we&#39;re decorating.
    Dagger _dagger;

    //The constructor gets passed a dagger which can 
    //be a decorator since the types match.
    public EnchantmentDecorator(Dagger dagger)
    {
        _dagger = dagger;
    }

    public double GetValue()
    {
        //This decorator multiplies the value by two.
        return 2 * _dagger.GetValue();
    }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;public abstract class ConditionDecorator : DaggerDecorator
{
    //We have a reference to the object (or its outer most wrapper)
    //that we&#39;re decorating.
    Dagger _dagger;
    
    //The constructor gets passed a dagger which can 
    //be a decorator since the types match.
    public Decorator(Dagger dagger)
    {
        _dagger = dagger;
    }

    public double GetValue()
    {
        return .75d * _dagger.GetValue();
    }
}
&lt;/pre&gt;
Each decorator adds its own contribution to the value by delegating the method call, GetValue().&lt;br /&gt;
Let&#39;s see this in action and create a dagger, decorate it and find its value.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;class Program
{
    static void Main(string[] args)
    {
        //Create a BronzeDagger...
        BronzeDagger _kitchenKnife = new BronzeDagger();

        //Wrap it in an EnchantMentDecorator...
        _kitchenKnife = new EnchantmentDecorator(_kitchenKnife);
        
        //Make a SilverDagger.
        SilverDagger _sting = new SilverDagger();
        //This one gets two decorators.
        _sting = new ConditionDecorator(_sting);
        _sting = new EnchantmentDecorator(_sting);
        
        double stingValue = _sting.GetValue();
        double knifeValue = _kitchenKnife.GetValue();

        Console.WriteLine(stingValue.ToString());
        Console.WriteLine(knifeValue.ToString());
    }
}
&lt;/pre&gt;
When we call _sting.GetValue(), it first calls the EnchantmentDecorator&#39;s GetValue() method, which then calls the ConditionDecorator&#39;s GetValue() which finally calls the original SilverDagger&#39;s GetValue() and each call contributes to the final value in some way.&lt;br /&gt;
In this example, only multiplication was used in calculating the final value, so the order in which I wrapped them and the order that each decorator delegated its behavior didn&#39;t matter.  In more complicated examples these things have to be taken into account.
We can add as many decorators to an object that we want, extending the class&#39;s functionality any time, and the original Dagger class and its subclasses are never altered in the process.  Decorators can even add new methods.&lt;br /&gt;
&lt;br /&gt;
Well, that&#39;s the Decorator Pattern in a nutshell!  I hope you are enjoying this series and thanks for reading!</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/8798206093412645603/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/decorator-pattern.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/8798206093412645603'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/8798206093412645603'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/decorator-pattern.html' title='The Decorator Pattern'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvgLUFfv3lTH_SF2m4qxnAbfedlgMLrm_OMgSSGcZdUykLWnceEjOEyzdg5JmkLFkY8PJ_0-pnWk5ncvPiDa0HBNl4tcLwcc5DUz1b00SCZ6GcVtNEn6vFLUUalurv-ZPWX2mvDYb_ccE/s72-c/decorator_pattern.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-8040689526134076691</id><published>2011-11-23T12:41:00.001-08:00</published><updated>2012-03-04T12:51:45.543-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><title type='text'>The Observer Pattern</title><content type='html'>Often times, objects need to know what other objects are up to.  They may need to be updated of changes and passed new data.&lt;br /&gt;
A common example is the view or UI of a program needs to be aware of the state of the objects.  In a game, the HUD (Heads Up Display) may need to know information like the players hit points, ammo, or score.&lt;br /&gt;
This can be easily achieved through the &lt;a href=&quot;http://en.wikipedia.org/wiki/Observer_pattern&quot;&gt;Observer Pattern&lt;/a&gt;.  The classes that are kept up to date are called &lt;i&gt;observers&lt;/i&gt; and the object being observed is often called the &lt;i&gt;subject&lt;/i&gt;.  The subject usually has a collection of observers as well as methods for adding or removing observers, also called &lt;i&gt;registering&lt;/i&gt; and &lt;i&gt;unregistering&lt;/i&gt; respectively.  There must also be a way of notifying the registered observers of new data when necessary.&lt;br /&gt;
Like many design patterns there are multiple ways doing things and the observer pattern is no exception.  I&#39;ll go into two main ways that observers are notified of change.&lt;br /&gt;
&lt;br /&gt;
Here&#39;s a quick look at a UML diagram for the Observer pattern.&lt;br /&gt;&lt;/br&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhEw856slJGpJxdj0Doah5M9Cdd3lSkgisarPvxZS2YoMAIS-o6r9yS9HsfDOE_mDaTAwKha_iG45Y7btAHskHribDmmYdf5hC0VOQQ3e_3z3G0mV7OcIrSmlEjAidLbhg1xFdN3nl8wQk/s1600/observer_pattern.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;264&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhEw856slJGpJxdj0Doah5M9Cdd3lSkgisarPvxZS2YoMAIS-o6r9yS9HsfDOE_mDaTAwKha_iG45Y7btAHskHribDmmYdf5hC0VOQQ3e_3z3G0mV7OcIrSmlEjAidLbhg1xFdN3nl8wQk/s400/observer_pattern.jpg&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
In our simplified example we&#39;ll stick with the gaming theme where our subject will be a player, and our observer will be the HUD that will be notified of any change to the player&#39;s hit points so that it can be displayed.  There can be any number of observers, but we&#39;ll stick with one for now.  (In fact Observers can register with multiple Subjects, Subjects can, themselves be Observers and vice-versa but we&#39;ll keep things simple for now.)&lt;/br&gt;
&lt;/br&gt;
First we&#39;ll need our observer interface.  It will simply contain a method stub for receiving new data.
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;
public interface IObserver
{
    void Update(double hitPoints);
}
&lt;/pre&gt;
&lt;/br&gt;
Our Subject contains stubs for adding and removing observers and notifying them of changes.&lt;/br&gt;

&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;
public interface ISubject
{
    void RegisterObserver(IObserver observer);
    void UnregisterObserver(IObserver observer);
    void NotifyObservers();
}
&lt;/pre&gt;
&lt;/br&gt;
Let&#39;s code our Player class.  This will inherit from ISubject and will need to contain a collection of observers and data to be observed.&lt;/br&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;
public class Player : ISubject
{
    //Here&#39;s some data that needs to be observed.
    double _hitPoints = 20;

    //We need a collection of observers to notify.
    List&amp;lt;IObserver&amp;gt; _observers = new List&amp;lt;IObserver&amp;gt;();

    //Here&#39;s the method that actually changes the hitpoints.
    public void TakeDamage(double damageTaken)
    {
        _hitPoints -= damageTaken;
        //Once this field has been altered, 
        //we automatically notify its observers.
        StateChanged();
    }
   
    public void StateChanged()
    {
        //The observers are notified whenever the class&#39;s state, 
        //in this case the Player&#39;s hit points changes.
        NotifyObservers();
    }

    public void RegisterObserver(IObserver observer)
    {
        _observers.Add(observer);
    }

    public void UnregisterObserver(IObserver observer)
    {
        _observers.Remove(observer);
    }

    public void NotifyObservers()
    {
        //Here we simply iterate through each registered 
        //observer and pass each one
        //the current hitpoints.
        foreach (IObserver observer in _observers)
        {
            observer.Update(_hitPoints);
        }
    }
}
&lt;/pre&gt;
Notice that whenever the _hitPoints field is changed we call StateChanged() which notifies each observer of the new _hitPoints value.&lt;/br&gt;
&lt;/br&gt;
Now for our concrete observer, the HUD, which will display the Player&#39;s hit points if it&#39;s registered with it.
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class HUD : IObserver
{
    double _hitPointsToDisplay;
    
    //Here is where the observer receives its new data.
    public void Update(double hitPoints)
    {
        _hitPointsToDisplay = hitPoints;
    }

    public void DisplayHitPoints()
    {
        Console.WriteLine(&quot;Hit Points: &quot;);
        Console.WriteLine(_hitPointsToDisplay.ToString());
    }   
}
&lt;/pre&gt;

We can now set up a simple test:
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;
class Program
{
    static void Main(string[] args)
    {
        Player _player = new Player();
        HUD _hud = new HUD();

        //Register the HUD observer.
        _player.RegisterObserver(_hud);

        //Once all the observers are registered we&#39;ll 
        //initialize them with the proper data.
        _player.StateChanged();

        _hud.DisplayHitPoints();

        //The player takes some damage.  Remember that this 
        //method automatically notifies all
        //observers so there&#39;s no reason to call 
        //the NotifyObservers() method again.
        _player.TakeDamage(15.25);

        //The HUD displays the new data.
        _hud.DisplayHitPoints();

        Console.ReadLine();
    }
}
&lt;/pre&gt;
&lt;/br&gt;
And it works as promised.  Every time the Player takes damage (the TakeDamage() method is called), the HUD is notified of the change and we can display it on the screen.&lt;/br&gt;
&lt;/br&gt;
However, there will almost definitely be other data associated with the concrete subject that the observers will need to be aware of.&lt;/br&gt;
The Player may have a Score for example.  So we&#39;ll need to change the classes a bit.&lt;/br&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;
public interface IObserver
{
    void Update(double hitPoints, int score);
}
&lt;/pre&gt;
&lt;/br&gt;
The Player class now has a score field and a method for incrementing it.  Here&#39;s the entire Player class with the new changes.
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;
public class Player : ISubject
{
    //Here&#39;s some data that needs to be observed.
    double _hitPoints = 20;
    int _score = 0;

    //We need a collection of observers to notify.
    List&amp;lt;IObserver&amp;gt; _observers = new List&amp;lt;IObserver&amp;gt;();

    //Here&#39;s the method that actually changes the hitpoints.
    public void TakeDamage(double damageTaken)
   {
        _hitPoints -= damageTaken;
        //Once this field has been altered, we automatically notify its observers.
        StateChanged();
   }

    //This method adds to the player&#39;s score.
    public void AddScore(int score)
    {
        _score += score;
        //And again, we notify observers.
        StateChanged();
    }

    public void RegisterObserver(IObserver observer)
    {
        _observers.Add(observer);
    }

    public void UnregisterObserver(IObserver observer)
    {
        _observers.Remove(observer);
    }

    public void StateChanged()    
    {        
        //The observers are notified whenever the class&#39;s state,
        //in this case the Player&#39;s hit points changes.
        NotifyObservers();
    }

    public void NotifyObservers()
    {
        //Here we simply iterate through each registered 
        //observer and pass each one the current hitpoints.
        foreach (IObserver observer in _observers)
        {
            observer.Update(_hitPoints, _score);
        }
    }
}
&lt;/pre&gt;
&lt;/br&gt;
Finally the HUD needs to be modified to reflect these changes.&lt;/br&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;
class HUD : IObserver
{
    double _hitPointsToDisplay;
    //Here&#39;s the new data that the HUD is interested in keeping up to date with.
    int _scoreToDisplay;

    //Here is where the observer receives its new data.
    public void Update(double hitPoints, int score)
    {
        _hitPointsToDisplay = hitPoints;
        _scoreToDisplay = score;
    }

    public void DisplayHitPoints()
    {
        Console.WriteLine(_hitPointsToDisplay.ToString());
    }

    public void DisplayScore()
    {
        Console.WriteLine(_scoreToDisplay.ToString());
    }
}
&lt;/pre&gt;
&lt;/br&gt;
Here&#39;s the modified program class.&lt;/br&gt;
&lt;pre class=&quot;brush:c&quot; name=&quot;code&quot;&gt;
class Program
{
    static void Main(string[] args)
    {
        Player _player = new Player();
        HUD _hud = new HUD();

        //Register the HUD observer.
        _player.RegisterObserver(_hud);

        //Once all the observers are registered we&#39;ll 
        //initialize them with the proper data.
        //We can also do this in the concrete observers&#39; constructors.
        _player.NotifyObservers();

        //Display initial values.
        _hud.DisplayHitPoints();
        _hud.DisplayScore();

        //The player takes some damage.  Remember that this 
        //method automatically notifies all
        //observers so there&#39;s no reason to call 
        //the NotifyObservers() method again.
        _player.TakeDamage(15.25);

        //The player receives a score for some reason...
        _player.AddScore(5);

        //The HUD displays the new data.
        _hud.DisplayHitPoints();
        _hud.DisplayScore();

        Console.ReadLine();
    }
}
&lt;/pre&gt;
&lt;/br&gt;
We can already see some problems cropping up.  Each piece data we start adding in the player class, we&#39;ll need to modify the all the classes that inherit from IObserver.&lt;/br&gt;
One way to deal with this is to modify the IObserver interface so that it&#39;s Update method stub takes an object as a parameter so one could pass any type of data.  It would then be up to the concrete observer class to interpret the argument, which can be tricky.  I&#39;ve set this example up so that each piece of data is of a different type so we won&#39;t run into a lot of problems.&lt;/br&gt;
&lt;/br&gt;
Here&#39;s our modified IObserver interface.
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public interface IObserver
{
    void Update(object arg);
}
&lt;/pre&gt;
&lt;/br&gt;
The ISubject interface also needs to change.
&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public interface ISubject
{
    void RegisterObserver(IObserver observer);
    void UnregisterObserver(IObserver observer);
    void NotifyObservers(object arg);
}
&lt;/pre&gt;
&lt;/br&gt;
The new HUD will receive data as an object type, interpret it and update the appropriate fields.
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class HUD : IObserver
{
    double _hitPointsToDisplay;
    int _scoreToDisplay;

    //Here is where the observer receives its new data.
    public void Update(object arg)
    {
        //It&#39;s up to the observer to handle the argument passed
        //to it, which can be quite a hassle!
        if (arg is double)
        {
            _hitPointsToDisplay = (double)arg;
        }
        else if (arg is int)
        {
            _scoreToDisplay = (int)arg;
        }
    }

    public void DisplayHitPoints()
    {
        Console.WriteLine(&quot;Hit Points: &quot;);
        Console.WriteLine(_hitPointsToDisplay.ToString());
    }

    public void DisplayScore()
    {
        Console.WriteLine(&quot;Score: &quot;);
        Console.WriteLine(_scoreToDisplay.ToString());
    }
}
&lt;/pre&gt;
&lt;/br&gt;
Now we just need to modify the concrete subject, our Player class, to correctly notify its observers.
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public class Player : ISubject
{
    //Here&#39;s some data that needs to be observed.
    double _hitPoints = 20d;
    int _score = 0;

    //We need a collection of observers to notify.
    List&amp;lt;IObserver&amp;gt; _observers = new List&amp;lt;IObserver&amp;gt;();

    //Here&#39;s the method that actually changes the hitpoints.
    public void TakeDamage(double damageTaken)
    {
        _hitPoints -= damageTaken;
        //Once this field has been altered, we automatically notify its observers.
        NotifyObservers(_hitPoints);
    }

    //This method adds to the player&#39;s score.
    public void AddScore(int score)
    {
        _score += score;
        //And again, we notify observers.
        NotifyObservers(_score);
    }

    public void RegisterObserver(IObserver observer)
    {
        _observers.Add(observer);
    }

    public void UnregisterObserver(IObserver observer)
    {
        _observers.Remove(observer);
    }

    public void NotifyObservers(object arg)
    {
        //Here we simply iterate through each registered observer and pass each one
        //the current hitpoints.
        foreach (IObserver observer in _observers)
        {
            observer.Update(arg);
        }
    }
}
&lt;/pre&gt;
&lt;/br&gt;
I&#39;ve done away with the StateChanged() method and now simply call NotifyObservers(arg) with the appropriate piece of data.&lt;/br&gt;
&lt;/br&gt;
One thing to notice is that the Subject decides what data gets passed to the observers via the Update method.  This is called the &lt;i&gt;push&lt;/i&gt; method of notification since the Subject pushes the data onto its observers.  This may not always be what we want.  There may be an observer that&#39;s interested in some of the data its subject has but not all of it.  Another method, called the &lt;i&gt;pull&lt;/i&gt; method, allows the observers to pick and choose which data to take from its subject.
Implementing it is not difficult and requires only a few changes to our existing code.  I have decided to make the Subject and abstract method so that it can handle the observer collection internally.&lt;/br&gt;
The basic idea of the pull method is that instead of passing specific pieces of data to our observers, we pass the Subject object as the Update&#39;s argument.  As long as the Subject implements some way of getting its data, the observers can decide what to take from its subject and what to ignore.&lt;/br&gt;
&lt;/br&gt;
First let&#39;s modify our new IObserver interface.
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public interface IObserver
{
    void Update(Subject subject, object arg);
}
&lt;/pre&gt;
Now it takes a Subject object as a parameter as well.  We can keep the object arg if we ever want to pass specific data.&lt;/br&gt;
&lt;/br&gt;
Our Subject class is abstract and handles the collection and notification:&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public abstract class Subject
{
    List&amp;lt;IObserver&amp;gt; _observers = new List&amp;lt;IObserver&amp;gt;();

    public void RegisterObserver(IObserver observer)
    {
        _observers.Add(observer);
    }

    void UnregisterObserver(IObserver observer)
    {
        _observers.Remove(observer);
    }

    public void NotifyObservers(object arg)
    {
        foreach (IObserver observer in _observers)
        {
            observer.Update(this, arg);
        }
    }

    public void NotifyObservers()
    {
        NotifyObservers(null);
    }
}
&lt;/pre&gt;
We now have two different NotifyObserver methods.  One can pass a specific piece of data for an observer to deal with and the other passes null for that argument while they both pass along the Subject.&lt;/br&gt;
&lt;/br&gt;
Our Player class no longer needs to handle its observer collection.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public class Player : Subject
{
    //Here&#39;s some data that needs to be observed.
    double _hitPoints = 20d;
    int _score = 0;

    //Here&#39;s the method that actually changes the hitpoints.
    public void TakeDamage(double damageTaken)
    {
        _hitPoints -= damageTaken;
        //Once this field has been altered, we automatically notify its observers.
        NotifyObservers();
    }

    //This method adds to the player&#39;s score.
    public void AddScore(int score)
    {
        _score += score;
        //And again, we notify observers.
        NotifyObservers();
    }

    public double GetHitPoints()
    {
        return _hitPoints;
    }

    public int GetScore()
    {
        return _score;
    }
}
&lt;/pre&gt;
I&#39;m using the pull method here to show how it works but we don&#39;t have to.  Just remember that the object parameter might be null and our Observers have to handle cases like this.  But for this quick example I&#39;ll go ahead and assume we&#39;re simply interested in the Subject argument.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
class HUD : IObserver
{
    double _hitPointsToDisplay;
    int _scoreToDisplay;

    //Here is where the observer receives its new data.
    public void Update(Subject subject, object arg)
    {
        if (subject is Player)
        {
            Player player = subject as Player;
            _hitPointsToDisplay = player.GetHitPoints();
            _scoreToDisplay = player.GetScore();
        }
    }

    public void DisplayHitPoints()
    {
        Console.WriteLine(&amp;quot;Hit Points: &amp;quot;);
        Console.WriteLine(_hitPointsToDisplay.ToString());
    }

    public void DisplayScore()
    {
        Console.WriteLine(&amp;quot;Score: &amp;quot;);
        Console.WriteLine(_scoreToDisplay.ToString());
    }
}
&lt;/pre&gt;
In the Update method we grab only the data we want.  The subject could have many more fields but our HUD is interested only in the hit points and score.&lt;/br&gt;
&lt;/br&gt;
There you have it.  Three different methods of implementing the observer pattern.  Each with their own advantages and drawbacks.  Deciding which method to use depends on the problem at hand and personal preference.  And these are by no means the only ways of doing it, the observer pattern, like most patterns can be tweaked and modified to fit your own needs.&lt;/br&gt;&lt;/br&gt;
I hope you enjoyed the article and thanks for reading!</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/8040689526134076691/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/observer-pattern.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/8040689526134076691'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/8040689526134076691'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/observer-pattern.html' title='The Observer Pattern'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhEw856slJGpJxdj0Doah5M9Cdd3lSkgisarPvxZS2YoMAIS-o6r9yS9HsfDOE_mDaTAwKha_iG45Y7btAHskHribDmmYdf5hC0VOQQ3e_3z3G0mV7OcIrSmlEjAidLbhg1xFdN3nl8wQk/s72-c/observer_pattern.jpg" height="72" width="72"/><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-6056833942860251307</id><published>2011-11-22T15:23:00.001-08:00</published><updated>2012-03-04T12:52:01.302-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><title type='text'>The Strategy Pattern</title><content type='html'>While they can be &lt;a href=&quot;http://en.wikipedia.org/wiki/Law_of_the_instrument&quot;&gt;abused&lt;/a&gt; in &lt;a href=&quot;http://en.wikipedia.org/wiki/Anti-pattern&quot;&gt;various ways&lt;/a&gt;, design patterns are an essential subject to become familiar with, so I&#39;m going to dedicate the next series of articles to design patterns.&lt;br /&gt;
&lt;br /&gt;
First up is the strategy pattern.  This pattern is very useful for changing a class&#39;s behavior at runtime.&lt;br /&gt;
Let&#39;s say we have a class that implements some method.  The method works great but now we&#39;d like to inherit from that class.  The method will be inherited as well and will perform the same function.  Any additional class we inherit from the base class will also come with this method.  But what if one of our subclass&#39; doesn&#39;t implement that method in exactly the same way?  Well we could always make the method virtual and override it so it does something else but what if we want the class to &lt;i&gt;sometimes&lt;/i&gt; perform the method normally and sometimes do it a little different?  Here we would run into some problems.&lt;br /&gt;
&lt;br /&gt;
Let&#39;s take a simple example.  Consider a Car class that implements a Honk() method.  Every subclass of Car will have it&#39;s own specific honk sound.  This is all very well and good, but what if the owner wants to change the honk sound?  What if the owner is a bit eccentric and decides they want a different sound for each day of the week?  This quickly becomes a maintenance nightmare.&lt;br /&gt;
&lt;br /&gt;
A way around this is to create an interface or an abstract class containing a method stub for Honk behavior.  The interface is meant to &lt;a href=&quot;http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)&quot;&gt;encapsulate&lt;/a&gt; honking.  Any concrete strategy class that inherits from the honking interface can implement its Honk method however it wants. The Car class, in turn, will contain a reference to a honking strategy object.  When the Car calls &lt;i&gt;its&lt;/i&gt; honking method, the strategy&#39;s method is called.&lt;br/&gt;
This allows for some flexible car honking behavior because now we can write methods to change one Honk interface for another.  During runtime a car object can change how it honks!&lt;br /&gt;
&lt;br /&gt;
These abstract behavior classes are called &lt;i&gt;strategies&lt;/i&gt;.&lt;br /&gt;
&lt;/br&gt;
Before we get into the code, let&#39;s take a quick look at the UML diagram for this pattern.  You can skip over this image if you&#39;re not familiar with UML as it isn&#39;t necessary to follow the article.  It can also serve as a handy reference for later.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVeD1zamnTFWStAs2lP3m1yWRbcdZ5MjdEXwcR8Xxr8RACApLFaW5W1ont9eMl3w6xcOsOl5XEAiTWylWBzbgVNpuVDlRFnh5jMqpw4ayivaiZfi7mr5Wb6iNpEAlTs8Jd_7tawmi-cec/s1600/Main.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;351&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVeD1zamnTFWStAs2lP3m1yWRbcdZ5MjdEXwcR8Xxr8RACApLFaW5W1ont9eMl3w6xcOsOl5XEAiTWylWBzbgVNpuVDlRFnh5jMqpw4ayivaiZfi7mr5Wb6iNpEAlTs8Jd_7tawmi-cec/s400/Main.jpg&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;

Our Honk strategy would look something like this:
&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public interface IHonk
{
    void Honk();
}
&lt;/pre&gt;
&lt;br /&gt;
Now we can inherit from this interface to make specific honks.  We&#39;ll make a few here now, a NormalHonk, BrokenHonk, and a GodFatherThemeHonk.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public class NormalHonk : IHonk
{
    public void Honk()
    {
        Console.WriteLine(&quot;Honk!&quot;);
    }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public class BrokenHonk : IHonk
{
    public void Honk()
    {
        Console.WriteLine(&quot;fffffffff......&quot;);
    }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public class GodFatherThemeHonk : IHonk
{
    public void Honk()
    {
        Console.WriteLine(&quot;**mandolin music**&quot;);
    }
}
&lt;/pre&gt;
&lt;br /&gt;
Our car class needs a reference to an IHonk object.  The car&#39;s PerformHonk() method will call the Honk() method from the strategies reference.&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;public class Car
{
    IHonk _honkStrategy = new NormalHonk();
    
    public void PerformHonk()
    {
        _honkStrategy.Honk();
    }

    public void SetHonkStrategy(IHonk honkStrategy)
    {
        _honkStrategy = honkStrategy;
    }
}
&lt;/pre&gt;
&lt;br /&gt;
Each car object is initialized with a NormalHonk but we can change this at any time.&lt;br /&gt;
Let&#39;s create a few cars and see how this works in action&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class Program
{
    static void Main(string[] args)
    {
        //Here we initialize a new car, leaving it&#39;s honk strategy
        //at its default.
        Car _honda = new Car();
        
        //Here we&#39;ll make a car and set it&#39;s honk to something else.
        Car _elCamino = new Car();
        _elCamino.SetHonkStrategy(new GodFatherThemeHonk());

        //Each car has it&#39;s own honking behavior...
        _honda.Honk();
        _elCamino.Honk();

        //The Honda&#39;s horn breaks!
        _honda.SetHonkStrategy(new BrokenHonk());
        
        _honda.Honk();

        Console.ReadLine();
    }
}
&lt;/pre&gt;
&lt;br /&gt;
We would also, ideally, make the Car class abstract and inherit from it.&lt;/br&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;
public abstract class Car
{
    IHonk _honkStrategy;
    
    public void PerformHonk()
    {
        _honkStrategy.Honk();
    }

    public void SetHonkStrategy(IHonk honkStrategy)
    {
        _honkStrategy = honkStrategy;
    }
}

public class Honda : Car
{
    public Honda()
    {
        SetHonkStrategy(new NormalHonk());
    }
}

public class ElCamino : Car
{
    public ElCamino()
    {
        SetHonkStrategy(new GodFatherThemeHonk());
    }
}
&lt;/pre&gt;
And our Program class becomes simpler.
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;class Program
{
    static void Main(string[] args)
    {
        Car _honda = new Honda();
        
        Car _elCamino = new ElCamino();
        
        //Each car has it&#39;s own honking behavior...
        _honda.Honk();
        _elCamino.Honk();

        //The Honda&#39;s horn breaks!
        _honda.SetHonkStrategy(new BrokenHonk());
        
        //The El Camino&#39;s owner wants a normal honk.
        _elCamino.SetHonkStrategy(new NormalHonk());
        
        _honda.Honk();
        _elCamino.Honk();

        Console.ReadLine();
    }
}
&lt;/pre&gt;
And that&#39;s the Strategy Pattern.  It&#39;s very simple but extremely effective at changing behavior during runtime.&lt;br /&gt;
Thanks for reading and I hope this was an enlightening look at the Strategy Pattern!</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/6056833942860251307/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/strategy-pattern.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/6056833942860251307'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/6056833942860251307'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/11/strategy-pattern.html' title='The Strategy Pattern'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVeD1zamnTFWStAs2lP3m1yWRbcdZ5MjdEXwcR8Xxr8RACApLFaW5W1ont9eMl3w6xcOsOl5XEAiTWylWBzbgVNpuVDlRFnh5jMqpw4ayivaiZfi7mr5Wb6iNpEAlTs8Jd_7tawmi-cec/s72-c/Main.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5965588490067077786.post-8484950485852499650</id><published>2011-06-26T16:36:00.000-07:00</published><updated>2012-03-04T12:52:22.489-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Content Pipeline"/><category scheme="http://www.blogger.com/atom/ns#" term="Tutorials"/><category scheme="http://www.blogger.com/atom/ns#" term="XNA"/><title type='text'>Content Pipeline Tutorial</title><content type='html'>In this article we&#39;ll be building a &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/bb447745.aspx&quot;&gt;content pipeline&lt;/a&gt; extension.&lt;br /&gt;
The content pipeline is a great system for importing and loading outside art assets into your game.  The files are converted into a binary (.xnb) file format at compile time that the XNA framework can then deserialize at run time.&lt;br /&gt;
The basic process as illustrated in the &lt;a href=&quot;http://i.msdn.microsoft.com/dynimg/IC81954.jpg&quot;&gt;diagram&lt;/a&gt; goes something like this:  the file we wish to load is imported into the content pipeline and the importer returns an some object we can work with like a string or an XmlDocument, then the imported type is passed off to the content processor which turns it into an object of the desired type.  For example, a .png image is imported and then some doubtlessly complicated logic goes through the data within the file and translates it to a Texture2DContent object (which is turned into a Texture2D object at run time).  The object is then passed off to the Content Type Writer which serializes it into the binary .xnb format.  All of this happens during compile-time.  Then finally at run-time the Content Reader deserializes the .xnb file to our loaded type within the Load&lt;T&gt; method call.&lt;br /&gt;
&lt;/br&gt;
First thing&#39;s first.  Let&#39;s create and set up the projects we&#39;ll need.  We&#39;ll need a total of three projects:  An XNA Game project, a Game Library project to hold the types we&#39;ll be loading in as well as our content readers, and a Content Pipeline Extension library which will have the importer, processor and writer.  Go ahead and create a new solution and then add the other projects.&lt;br /&gt;
That finished we now need to add the required references.  In the Game project add a reference to the Game Library project.  The Content Pipeline Extension project also needs a reference to the Game Library project so it can hold references to the types we&#39;ll be loading.  Lastly the Content project where you&#39;ll have your asset files needs a reference to the Content Pipeline Extension library.&lt;br /&gt;
Now let&#39;s make our type to be loaded in.  We&#39;ll make a simple tile map class that will display a grid of textures.&lt;br /&gt;
We&#39;ll be using the .xml format to import and process our assets.  This is mostly to make everything nice and easy since xml is so nice to work with but we could import the data in any form we like.&lt;br /&gt;
XNA does already have an &lt;a href=&quot;http://programyourfaceoff.blogspot.com/2011/11/xml-content-importer.html&quot;&gt;importer for the xml format&lt;/a&gt; which is very nice and flexible but one can have the control over how data is processed.&lt;br /&gt;
&lt;br /&gt;
The following is the code for our TileMap class which is to go into our Game Library project (I named mine ContentPipelineGameLibrary).  It&#39;s a very simple class.  It uses a single sprite sheet for the tile textures.  This is for ease in the serialization and deserialization.  I&#39;m using &lt;a href=&quot;http://www.mediafire.com/?vo3g59suu5o5but&quot;&gt;this one&lt;/a&gt; with two textures:  grass and dirt.&lt;br /&gt;
Go ahead and add this code,&lt;br /&gt;
&lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;c#&quot;&gt;using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace ContentPipelineTutorialGameLibrary
{
    public class TileMap
    {
        string _assetName = &amp;quot;&amp;quot;;
        Texture2D _spriteSheet;
        int[,] _textureGrid;
        int _tileWidth = 32;
        int _tileHeight = 32;
        int _tilesPerRow =2;

        Rectangle _drawRectangle = new Rectangle();
        Rectangle _sourceRectangle = new Rectangle();

        public int TilesPerRow
        {
            get { return _tilesPerRow; }
            set { _tilesPerRow = value; }
        }
        public int MapWidth
        {
            get { return _textureGrid.GetLength(1); }
        }
        public int MapHeight
        {
            get { return _textureGrid.GetLength(0); }
        }
        public string AssetName
        {
            get { return _assetName; }
            set { _assetName = value; }
        }
    
        public TileMap(int width, int height)
        {
            _textureGrid = new int[height, width];
            _drawRectangle.Width = _sourceRectangle.Width = _tileWidth;
            _drawRectangle.Height = _sourceRectangle.Height = _tileHeight;
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            for (int x = 0; x &amp;lt; _textureGrid.GetLength(1); x++)
            {
                for (int y = 0; y &amp;lt; _textureGrid.GetLength(0); y++)
                {
                    _drawRectangle.X = x * _tileWidth;
                    _drawRectangle.Y = y * _tileHeight;
                    _sourceRectangle.X =
                        (_textureGrid[y, x] % _tilesPerRow) * _tileWidth;
                    _sourceRectangle.Y =
                        (_textureGrid[y, x] / _tilesPerRow) * _tileHeight;
                    spriteBatch.Draw(
                        _spriteSheet,
                        _drawRectangle,
                        _sourceRectangle,
                        Color.White);
                }
            }
        }
        public void SetTextures(Texture2D spriteSheet, string assetName)
        {
            _spriteSheet = spriteSheet;
        }
        public int GetIndex(int x, int y)
        {
            return _textureGrid[y, x];
        }
        public void SetIndex(int x, int y, int value)
        {
            _textureGrid[y, x] = value;
        }
    }
}
&lt;/pre&gt;&lt;br /&gt;
Pretty straight forward stuff.  The _tilePerRow field is so we don&#39;t have to limit ourselves too much on how we format our sprite sheets.  The AssetName setter could prove problematic later on if we want to switch out sprite sheets during run-time but we can tweak things later.&lt;br /&gt;
&lt;/br&gt;
Before we get to any content extension classes, let&#39;s set up how we&#39;re going to format the data in our file.  Like I mentioned before I went with xml since it&#39;s so easy to work with but you can just as easily use almost anything (using classes that already have an importer/processor is tricky and I don&#39;t recommend it).&lt;br /&gt;
Right click on your content project.  Select Add -&amp;gt; New Item... and select XML Document in the dialogue.  Name it whatever you want, I named mine &quot;TileMap01&quot;.  The file is automatically given a .xml extension so right click on it and select Rename then change the extension to whatever (I chose &quot;.tilemap&quot;).  You will get a warning but pay no heed; we got this.&lt;br /&gt;
Now double click the newly created file, delete whatever&#39;s inside and add this:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:xml&quot; name=&quot;code&quot;&gt;&amp;lt;TileMap Width=&quot;4&quot; Height=&quot;4&quot;&amp;gt;
  &amp;lt;Texture AssetName=&quot;TileSheet&quot;/&amp;gt;
  &amp;lt;Layout&amp;gt;
    0 0 0 1
    0 1 0 1
    0 0 0 0
    1 0 1 1
  &amp;lt;/Layout&amp;gt;
&amp;lt;/TileMap&amp;gt;
&lt;/pre&gt;
&lt;br /&gt;
Now on to the importer.  Right click on your Content Extension Library and select Add -&amp;gt; New Item..., then select Content Importer.&lt;br /&gt;
Now replace the automatically generated code with this,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using System.Xml;

namespace ContentPipelineTutorialExtensionLibrary
{   
    [ContentImporter(&quot;.tilemap&quot;, DisplayName = &quot;TileMap Importer&quot;, 
        DefaultProcessor = &quot;TileMapProcessor&quot;)]
    public class TileMapImporter : ContentImporter&amp;lt;XmlDocument&amp;gt;
    {
        public override XmlDocument Import(
            string filename, ContentImporterContext context)
        {
            XmlDocument document = new XmlDocument();
            document.Load(filename);
            return document;
        }
    }
}
&lt;/pre&gt;
&lt;br /&gt;
Done.  All xml Importers will start this way.  Make sure the attribute that declares the extension matches yours.&lt;br /&gt;
Now add another new item to the Content Extension Library project, select Content Processor and replace the code with this,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using System.Xml;
using ContentPipelineTutorialGameLibrary;
using System.IO;

namespace ContentPipelineTutorialExtensionLibrary
{
    [ContentProcessor(DisplayName = &quot;TileMap Processor&quot;)]
    public class TileMapProcessor : ContentProcessor&amp;lt;XmlDocument, TileMap&amp;gt;
    {
        public override TileMap Process(
            XmlDocument input, ContentProcessorContext context)
        {
            
            XmlNodeList inputNodeList = input.GetElementsByTagName(&quot;TileMap&quot;);
            TileMap output = new TileMap(
                int.Parse(inputNodeList[0].Attributes[&quot;Width&quot;].Value),
                int.Parse(inputNodeList[0].Attributes[&quot;Height&quot;].Value));
            XmlNodeList nodeList = inputNodeList[0].ChildNodes;

            string[] layout;
            string[] rowEntries;

            foreach (XmlNode node in nodeList)
            {
                if (node.Name == &quot;Layout&quot;)
                {
                    layout = node.InnerText.Trim().Split(&#39;\n&#39;);
                    for (int row = 0; row &amp;lt; layout.Length; row++)
                    {
                        rowEntries = layout[row].Trim().Split(&#39; &#39;);
                        for (int rowEntry = 0; rowEntry &amp;lt; rowEntries.Length; rowEntry++)
                        {
                            output.SetIndex(
                                rowEntry, row, int.Parse(rowEntries[rowEntry]));
                        }
                    }
                }
                else if (node.Name == &quot;Texture&quot;)
                {
                    output.AssetName = node.Attributes[&quot;AssetName&quot;].Value;
                }
            }
            
            return output;
        }
    }
}
&lt;/pre&gt;
&lt;br /&gt;
So what we&#39;re doing here is reading through our xml, setting the texture asset name and setting the map&#39;s grid index.  Notice we&#39;re NOT setting the texture yet.  This is because the Texture2D class is not built during compile-time, it&#39;s a run-time object so we&#39;ll be setting the actual texture in the Content Reader which is called at run-time (when content.Load&lt;t&gt; is called).&lt;br /&gt;
That&#39;s it for processing our data.  Now let&#39;s make a Content Writer for the binary serialization.&lt;br /&gt;
Like before, add a new item and select Content Writer.  The code:&lt;br /&gt;
&lt;br /&gt;
&lt;/t&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Compiler;
using ContentPipelineTutorialGameLibrary;

namespace ContentPipelineTutorialExtensionLibrary
{
    [ContentTypeWriter]
    public class TileMapWriter : ContentTypeWriter&amp;lt;TileMap&amp;gt;
    {
        protected override void Write(ContentWriter output, TileMap value)
        {
            output.Write(value.MapWidth);
            output.Write(value.MapHeight);
            output.Write(value.AssetName);
            for (int x = 0; x &amp;lt; value.MapWidth; x++)
            {
                for (int y = 0; y &amp;lt; value.MapHeight; y++)
                {
                    output.Write(value.GetIndex(x, y));
                }
            }
        }

        public override string GetRuntimeReader(TargetPlatform targetPlatform)
        {
            return 
                &quot;ContentPipelineTutorialGameLibrary.TileMapReader, ContentPipelineTutorialGameLibrary&quot;;
        }
    }
}
&lt;/pre&gt;
&lt;br /&gt;
In the GetRuntimeReader method, we have the name of our Content Type Reader which we haven&#39;t created yet but will be located in the Game Library as opposed to the Content Pipeline Extension library.&lt;br /&gt;
And like before, make sure the names match yours (or, rather, what you will name your Content Reader).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now we need to actually make the reader.  Add a new item to the Game Library and select Content Type Reader.&lt;br /&gt;
The code:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace ContentPipelineTutorialGameLibrary
{
    public class TileMapReader : ContentTypeReader&amp;lt;TileMap&amp;gt;
    {
        protected override TileMap Read(ContentReader input, TileMap existingInstance)
        {
            TileMap tileMap = new TileMap(input.ReadInt32(), input.ReadInt32());
            string assetName=input.ReadString();
            tileMap.SetTextures(
                input.ContentManager.Load&amp;lt;Texture2D&amp;gt;(assetName), assetName);
            for (int x = 0; x &amp;lt; tileMap.MapWidth; x++)
            {
                for (int y = 0; y &amp;lt; tileMap.MapHeight; y++)
                {
                    tileMap.SetIndex(x, y, input.ReadInt32());
                }
            }
            return tileMap;
        }
    }
}
&lt;/pre&gt;
&lt;br /&gt;
This is where we set the texture by from the deserialized asset name.&lt;br /&gt;
This also might be a good time to explore the functions available in both the reader and writer.  There&#39;s pretty much a method for serializing anything you want.&lt;br /&gt;
We&#39;re not quite done yet.  In your content project, left click the tile map file and in the Properties window under Build Action select Compile.  Then, under Content Importer and Content Processor select the TileMap Importer and TileMap Processor, respectively.&lt;br /&gt;
If they don&#39;t appear in the drop-down, try compiling the solution and check again.&lt;br /&gt;
&lt;br /&gt;
Let&#39;s load the map and draw it!&lt;br /&gt;
Change your Game1.cs class to look like this:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:c#&quot; name=&quot;code&quot;&gt;using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using ContentPipelineTutorialGameLibrary;

namespace ContentPipelineTutorial
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        TileMap tileMap;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = &quot;Content&quot;;
        }

        protected override void Initialize()
        {        
            base.Initialize();
        }   
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            tileMap = Content.Load&amp;lt;TileMap&amp;gt;(&quot;TileMap01&quot;);
        }      
        protected override void UnloadContent()
        {
      
        }   
        protected override void Update(GameTime gameTime)
        {          
            base.Update(gameTime);
        }
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();
            tileMap.Draw(spriteBatch);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
&lt;/pre&gt;
&lt;br /&gt;
Now run the solution and you should see something like this:&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFKxBKl8JZi5C2IboEj2-C0FBHpz7UofPgGP7MXhz0NUmhpzrrXEAsD7R2GeH7jXaJb7Gh2DS6BCpr-VcmzXJnTbzPEEaWU62f0Gu7nzcGVBCsQ8se3dn0-6f116_geSxOygLu2uc6Z0s/s1600/content_pipeline_tutorial.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;401&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFKxBKl8JZi5C2IboEj2-C0FBHpz7UofPgGP7MXhz0NUmhpzrrXEAsD7R2GeH7jXaJb7Gh2DS6BCpr-VcmzXJnTbzPEEaWU62f0Gu7nzcGVBCsQ8se3dn0-6f116_geSxOygLu2uc6Z0s/s640/content_pipeline_tutorial.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
Okay, so that&#39;s pretty small so feel free to change things around a bit :)&lt;br /&gt;
That&#39;s it for this tutorial.  I am happy to answer any questions regarding this tutorial as best I can.&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;http://www.mediafire.com/?fc2dohnf0e83lvc&quot;&gt;source code&lt;/a&gt;&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://programyourfaceoff.blogspot.com/feeds/8484950485852499650/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/06/content-pipeline-tutorial-00.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/8484950485852499650'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5965588490067077786/posts/default/8484950485852499650'/><link rel='alternate' type='text/html' href='http://programyourfaceoff.blogspot.com/2011/06/content-pipeline-tutorial-00.html' title='Content Pipeline Tutorial'/><author><name>krakencalamari</name><uri>http://www.blogger.com/profile/02223204425724849216</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkPywP5Wlku8uxwKTcVGYn8JYTcN7bc7QC6-S57e8OAimKB3uxsgeO5WxN-lMQH1PacxtabmWf_eKEPa05bfMLM2cgw3NYCs_3DwRTluT9X-eQNa6Bhcb4X-DhpGvukQ/s220/kraken+calamari.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFKxBKl8JZi5C2IboEj2-C0FBHpz7UofPgGP7MXhz0NUmhpzrrXEAsD7R2GeH7jXaJb7Gh2DS6BCpr-VcmzXJnTbzPEEaWU62f0Gu7nzcGVBCsQ8se3dn0-6f116_geSxOygLu2uc6Z0s/s72-c/content_pipeline_tutorial.png" height="72" width="72"/><thr:total>2</thr:total></entry></feed>