Basic XNA Game theory, with sprite loading and its movement and Collision detection

// In this programme I just want to introduce some basic concepts i.e the steps the flow of

// the windows game programme using C# in XNA development environment.

// for taking the complete project you have to email me at jawadnawaz@live.com

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;

namespace

JawadGame

{

///<summary>

/// This is the main type for your game

///</summary>

publicclassGame1 : Microsoft.Xna.Framework.Game

{

GraphicsDeviceManager graphics;

SpriteBatch spriteBatch;

Rectangle mainFrame, playSize, pauseSize, jerrySize, tomSize, sonicSize, soniccSize;

public Game1()

{

graphics =

newGraphicsDeviceManager(this);

Content.RootDirectory =

“Content”;

}

///<summary>

/// Allows the game to perform any initialization it needs to before starting to run.

/// This is where it can query for any required services and load any non-graphic

/// related content.  Calling base.Initialize will enumerate through any components

/// and initialize them as well.

///</summary>

protectedoverridevoid Initialize()

{

// TODO: Add your initialization logic here

base.Initialize();

}

///<summary>

/// LoadContent will be called once per game and is the place to load

/// all of your content.

///</summary>

// This is a texture we can render.

Texture2D bg, play, pause, tom, jerry, sonic, sonicc;

protectedoverridevoid LoadContent()

{

// Create a new SpriteBatch, which can be used to draw textures.

spriteBatch =

newSpriteBatch(GraphicsDevice);

bg = Content.Load<Texture2D>(“Textures/bg”);

mainFrame = newRectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);

play = Content.Load<Texture2D>(“Textures/play”);

playSize = newRectangle(0, 0, (int)(play.Width * 0.5), (int)(play.Height * 0.5));

pause = Content.Load<Texture2D>(“Textures/pause”);

pauseSize = newRectangle(750, 0, (int)(pause.Width * 0.5), (int)(pause.Height * 0.5));

sonic = Content.Load<Texture2D>(“Textures/sonic”);

sonicSize = newRectangle(242, 140, (int)(sonic.Width * 0.9), (int)(sonic.Height * 0.9));

tom = Content.Load<Texture2D>(“Textures/tom”);

tomSize = newRectangle(470, 175, (int)(tom.Width * 0.8), (int)(tom.Height * 0.8));

jerry = Content.Load<Texture2D>(“Textures/jerry”);

jerrySize = newRectangle(20, 300, (int)(jerry.Width * 0.3), (int)(jerry.Height * 0.3));

sonicc = Content.Load<Texture2D>(“Textures/sonicc”);

soniccSize = newRectangle(800, 0, (int)(sonicc.Width * 0.8), (int)(sonicc.Height * 0.9));

// TODO: use this.Content to load your game content here

}

///<summary>

/// UnloadContent will be called once per game and is the place to unload

/// all content.

///</summary>

protectedoverridevoid UnloadContent()

{

// TODO: Unload any non ContentManager content here

}

///<summary>

/// Allows the game to run logic such as updating the world,

/// checking for collisions, gathering input, and playing audio.

///</summary>

///<param name=”gameTime”>Provides a snapshot of timing values.</param>

protectedoverridevoid Update(GameTime gameTime)

{

soniccSize.X -= 1;

KeyboardState key = Keyboard.GetState();

if (key.IsKeyDown(Keys.Right))

{

jerrySize.X += 1;

}

elseif (key.IsKeyDown(Keys.Left))

{

jerrySize.X -= 1;

}

elseif (key.IsKeyDown(Keys.Up))

{

jerrySize.Y -= 1;

}

elseif (key.IsKeyDown(Keys.Down))

{

jerrySize.Y += 1;

}

//Reset all objects on initial locations.

elseif (key.IsKeyDown(Keys.Space))

{

jerrySize.X = 20;

jerrySize.Y = 300;

tomSize.X = 500;

soniccSize.X = 800;

soniccSize.Y = 0;

}

//collision detection between Tom and Jerry.

if (jerrySize.Intersects(tomSize))

{

tomSize.X += tomSize.X / 13;

}

// Allows the game to exit

if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)

this.Exit();

// TODO: Add your update logic here

base.Update(gameTime);

}

publicvoid movement(GameTime gameTime)

{

base.Update(gameTime);

}

///<summary>

/// This is called when the game should draw itself.

///</summary>

///<param name=”gameTime”>Provides a snapshot of timing values.</param>

protectedoverridevoid Draw(GameTime gameTime)

{

graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

// Draw the sprite.

spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);

spriteBatch.Draw(bg, mainFrame, Color.White);

spriteBatch.Draw(sonicc, soniccSize, Color.White);

spriteBatch.Draw(sonic, sonicSize, Color.White);

spriteBatch.Draw(tom, tomSize, Color.White);

spriteBatch.Draw(jerry, jerrySize, Color.White);

spriteBatch.Draw(play, playSize, Color.White);

spriteBatch.Draw(pause, pauseSize, Color.White);

spriteBatch.End();

base.Draw(gameTime);

}

}

}

Simple Calculator .

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Calculator

{

classProgram

{

staticvoid Main(string[] args)

{

//this is a simple program to teach the logic behind simple calculator and to understand the switch statement.

// You just need to build your concept and same concepts will work every where.

int a, b, ans=0;

char opr;

Console.WriteLine(“Please enter the First number: “);

a =

int.Parse(Console.ReadLine());

Console.WriteLine(“Please enter the Second number: “);

b =

int.Parse(Console.ReadLine());

Console.WriteLine(“Please enter an operand (+, -, /, *): “);

opr=

char.Parse(Console.ReadLine());

switch (opr)

{

case‘-‘:

ans = a – b;

break;

case‘+’:

ans = a + b;

break;

case‘/’:

ans = a / b;

break;

case‘*’:

ans = a * b;

break;

default:

Console.WriteLine(“invalid”);

break;

}

Console.WriteLine(“\n\t {0} {1} {2} = {3}”, a, opr, b, ans);

Console.ReadLine();

}

}

}

Simple Nested-If-else (its dam simple :p ;)

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace DaySelect

{

classProgram

{

staticvoid Main(string[] args)

{

//This is a very bigners level simple programms for understanding Nested if-else. i advice that for these type of simple programms use F11 key to debud step by step and see how compiler works 🙂

Console.WriteLine(“Enter Number of the day: i.e, 1 to 6”);

Console.WriteLine(“Enter your number: “);

int a = int.Parse(Console.ReadLine());

if (a == 1) Console.WriteLine(“\n\t This is Monday”);

else

if (a == 2) Console.WriteLine(“\t This is Tuesday”);

else

if (a == 3) Console.WriteLine(“\t This is Wednesday”);

else

if (a == 4) Console.WriteLine(“\t This is Thursday”);

else

if (a == 5) Console.WriteLine(“\t This is Friday”);

else

if (a == 6) Console.WriteLine(“\t This is Saturday”);

else

Console.WriteLine(“invalid”);

Console.ReadKey();

}

}

}

 

Simple C# Program implements a palindrome for both integers and Strings.

using
System;
using
 System.Collections.Generic;
using
 System.Linq;
using
 System.Text;
 
namespace
 A1
{
classProgram
    {
staticvoid Main(string[] args)
        {
Console.WriteLine("\n Please Enter your Data: ");
string data = Console.ReadLine();
int flag = Palindrome(data);
if (flag == 1)
            {
Console.WriteLine("Your Word \" {0} \"  is Palindrome Word", data);
            }
elseif (flag == 0)
            {
Console.WriteLine("Your Word \" {0} \"  is NOT Palindrome", data);
            }
Console.ReadKey();
        }
//START of My Palindrome Function
staticint Palindrome(string data)
        {
string upperconv = data.ToUpper();
char[] datarevers = newchar[data.Length];
for (int i = data.Length - 1; i >= 0; i--)
            {
                datarevers[i] = upperconv[i];
            }
int wordchecker = 0;
int r = datarevers.Length - 1;
for (int i = 0; i < datarevers.Length; i++)
            {
if (datarevers[r] == upperconv[i]) { wordchecker++; }
                r--;
            }
if (wordchecker == datarevers.Length)
            {
return 1;
            }
else
            {
return 0;
            }
        }
//End of Function
    }
}

Inheritance in C#

One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.

When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.

The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, dog IS-Amammal hence dog IS-A animal as well and so on.

Base and Derived Classes

A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base class or interface.

The syntax used in C# for creating derived classes is as follows:

<acess-specifier> class <base_class>
{
 ...
}
class <derived_class> : <base_class>
{
 ...
}

Consider a base class Shape and its derived class Rectangle:

using System;
namespace InheritanceApplication
{
   class Shape 
   {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
   }

   // Derived class
   class Rectangle: Shape
   {
      public int getArea()
      { 
         return (width * height); 
      }
   }
   
   class RectangleTester
   {
      static void Main(string[] args)
      {
         Rectangle Rect = new Rectangle();

         Rect.setWidth(5);
         Rect.setHeight(7);

         // Print the area of the object.
         Console.WriteLine("Total area: {0}",  Rect.getArea());
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces following result:

Total area: 35

Base Class Initialization

The derived class inherits the base class member variables and member methods. Therefore the super class object should be created before the subclass is created. You can give instructions for superclass initialization in the member initialization list.

The following program demonstrates this:

using System;
namespace RectangleApplication
{
   class Rectangle
   {
      //member variables
      protected double length;
      protected double width;
      public Rectangle(double l, double w)
      {
         length = l;
         width = w;
      }
      public double GetArea()
      {
         return length * width;
      }
      public void Display()
      {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }//end class Rectangle  
   class Tabletop : Rectangle
   {
      private double cost;
      public Tabletop(double l, double w) : base(l, w)
      { }
      public double GetCost()
      {
         double cost;
         cost = GetArea() * 70;
         return cost;
      }
      public void Display()
      {
         base.Display();
         Console.WriteLine("Cost: {0}", GetCost());
      }
   }
   class ExecuteRectangle
   {
      static void Main(string[] args)
      {
         Tabletop t = new Tabletop(4.5, 7.5);
         t.Display();
         Console.ReadLine();
      }
   }
}

When the above code is compiled and executed, it produces following result:

Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5

Multiple Inheritance in C#

C# does not support multiple inheritance. However, you can use interfaces to implement multiple inheritance. The following program demonstrates this:

using System;
namespace InheritanceApplication
{
   class Shape 
   {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
   }

   // Base class PaintCost
   public interface PaintCost 
   {
      int getCost(int area);

   }
   // Derived class
   class Rectangle : Shape, PaintCost
   {
      public int getArea()
      {
         return (width * height);
      }
      public int getCost(int area)
      {
         return area * 70;
      }
   }
   class RectangleTester
   {
      static void Main(string[] args)
      {
         Rectangle Rect = new Rectangle();
         int area;
         Rect.setWidth(5);
         Rect.setHeight(7);
         area = Rect.getArea();
         // Print the area of the object.
         Console.WriteLine("Total area: {0}",  Rect.getArea());
         Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area));
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces following result:

Total area: 35
Total paint cost: $2450