Sunday, 26 June 2011

Play Football in Bed Room-XNA Game Studio

Fantastic Football-2D 

   
             It is a simple 2D game which renders images in gaming windows. To do this, take snap of your bed room and image file of football. 
You may wounder about the tittle itself why i have suited this tittle, it is all for attracting . However, this article guides you to how to develop your own games in  .NET Platform. if you have  experience in windows application and web based application (ASP.Net), you just need to learn little bit more to develop game. By my experience, Unlike windows based and web application, XNA does not provide user interface in Compile time (Form Designing phase) Because game is fully graphical dependent.Here,you need somewhat mathematical  knowledge in Trigonometric , Statistics and Game Logic.

Before starting, you have to prepare your system for game Development Environment by  installing  XNA game Studio.

What is XNA game Studio ?
      
                    XNA Game Studio and the XNA Framework are designed for cross-platform gaming scenarios with support for Windows Phone 7, Xbox 360, and Windows-based PCs. This allows you to target more platforms from the same code base. It also allows developers to focus game design for each platform on real device differences such as the device capabilities and experience, as opposed to writing with different frameworks for each targeted device.
  1. Download and Install XNA game studio from here
  2. Download Application File
  3. Download Project file 



Part I - Basic Settings:

  • As usual goto file--> New Project
  • Expand  visual C# Node, select XNA game studio and Name the Default Assemblies


             After creating a new project, you'll be presented with the code view of your game.



Part II - View of code:

             Some of the hard work has already been done for you. If you build and run your game now, the GraphicsDeviceManager will set up your screen size and render a blank screen. Your game will run and update all by itself. It's up to you to insert your own code to make the game more interesting.

Much of the code to start and run your game has already been written for you. You can insert your own code now.
These are the five methods allows you to code and run the game
  • The Initialize method is where you can initialize any assets that do not require a GraphicsDevice to be initialized.
  • The LoadContent method is where you load any necessary game assets such as models and textures.
  • The UnloadContent method is where any game assets can be released. Generally, no extra code is required here, as assets will be released automatically when they are no longer needed.
  • The Update loop is the best place to update your game logic: move objects around, take player input, decide the outcome of collisions between objects, and so on.
  • The Draw loop is the best place to render all of your objects and backgrounds on the screen.

  Part III - ADD Sprite

                    The next step is to add a graphic that can be drawn on the screen. Use a small graphics file, such as a small .bmp or .jpg file. Be creative—you can even make your own. You can even skip ahead a bit and make a sprite that "hides" parts that should not be seen (such as edges or corners) so that it looks even better.



  1. Make sure you can see the Solution Explorer for your project on the right side of the window. If you cannot see it, click the View menu, and then click Solution Explorer.
  2. Right-click the Content node, click Add, click Existing Item, and then browse to your graphic.
  3. If you can't see any files, make sure you change the Files of type selection box to read Texture Files
  4.  Click the graphic file, and then click Add.  
      5.  If the Properties window is not visible, press F4, or click the View menu, and then click
            Properties Window.

 Like above Add Bed Room  image file and football image to content folder.



Part IV -Update Code

Now Initialize these variables...


        Texture2D mytex,bgr,mou; //these varible for background,football and Cursor
       
        Vector2 sposition = Vector2.Zero;
        Vector2 text = new Vector2(680, 10);
        Vector2 gameover = new Vector2(200, 200);
        Vector2 gameover1 = new Vector2(230, 250);
        Vector2 spriteSpeed = new Vector2(0f, 10f);
        Vector2 mpos = Vector2.Zero;

        Vector2 origin;
        Vector2 screenpos;
        float RotationAngle;

        GraphicsDevice device;
        MouseState mouseStateCurrent;
        SpriteFont fnt,gover;


Update  "protected override void LoadContent() " method by adding...

            device = graphics.GraphicsDevice;
            spriteBatch = new SpriteBatch(GraphicsDevice);
            mytex = Content.Load<Texture2D>("fb");
            bgr = Content.Load <Texture2D>( "bg");
            mou = Content.Load<Texture2D>("pon");
            fnt = Content.Load<SpriteFont>("Arial");
            gover = Content.Load<SpriteFont>("over");


            Viewport viewport = graphics.GraphicsDevice.Viewport;
            origin.X = mytex.Width / 2;
            origin.Y = mytex.Height / 2;
            screenpos.X = viewport.Width / 2;
            screenpos.Y = viewport.Height / 2;


update "protected override void Draw(GameTime gameTime)" by adding..

            int screenWidth;
            int screenHeight;

            graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
            // TODO: Add your drawing code here
            spriteBatch.Begin();
           
            screenWidth = device.PresentationParameters.BackBufferWidth;
            screenHeight = device.PresentationParameters.BackBufferHeight;
            Rectangle screenRectangle = new Rectangle(0,0, screenWidth, screenHeight);
            spriteBatch.Draw(bgr, screenRectangle, Color.White);

            spriteBatch.Draw(mytex, sposition,null,    
            Color.White,RotationAngle,origin,0.5f,SpriteEffects.FlipHorizontally,1f);
            spriteBatch.Draw(mou,mpos,Color.White);
            spriteBatch.DrawString(fnt, "Score:"+i.ToString(),text,Color.YellowGreen);
            if(staus==true)
            {
                spriteBatch.DrawString(gover,"Game Over", gameover,Color.YellowGreen);
                spriteBatch.DrawString(fnt, "Score:" + i.ToString()+"\n Click Ball for
                   New Game\n Developed by Muthukumar", gameover1, Color.YellowGreen);
                spriteSpeed = new Vector2(0f, 0f);
         
            }
            spriteBatch.End();

            base.Draw(gameTime);


Update " protected override void Update(GameTime gameTime)" method by..
                 
                       This is the right place to show your mathematical talents and game logic...


            mpos.X = mouseStateCurrent.X;
            mpos.Y = mouseStateCurrent.Y;
            RotationAngle +=(float) gameTime.ElapsedGameTime.TotalSeconds*5;
            float circle = MathHelper.Pi * 2;
            RotationAngle = RotationAngle % circle;
            int MaxX =
                graphics.GraphicsDevice.Viewport.Width - mytex.Width;
            int MinX = 0;
            int MaxY =
                graphics.GraphicsDevice.Viewport.Height - mytex.Height;
            int MinY = 0;
            mouseStateCurrent = Mouse.GetState();
           
            if (mouseStateCurrent.LeftButton == ButtonState.Pressed)
            {
                if (staus == true)
                {
                    staus = false;
                    i = 0;
                }

                if (Math.Abs(sposition.Y - mouseStateCurrent.Y) <50 &&
                              Math.Abs(sposition.X - mouseStateCurrent.X) < 50)
                {
                                     
                    spriteSpeed = new Vector2(mouseStateCurrent.Y-100,
                                                       mouseStateCurrent.X-100);
                    sposition -=
                   spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds * 1;
                    i++;
                  
                }


            }
            else
            {
                sposition -=
              spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds * 2;
            }
          
            // Check for bounce.
            if (sposition.X > MaxX+50)
            {
                spriteSpeed.X *= -1;
                sposition.X = MaxX;
                i+=5;
            }

            else if (sposition.X < MinX)
            {
                spriteSpeed.X *= -1;
                sposition.X = MinX;
                i++;
            }

            if (sposition.Y > MaxY+75)
            {
                spriteSpeed.Y *= -1;
                sposition.Y = MaxY;
                i++;
                staus = true;
            }

            else if (sposition.Y < MinY)
            {
                spriteSpeed.Y *= -1;
                sposition.Y = MinY;
                i++;
            }
        

            base.Update(gameTime);



PART V:
  • Build and run your game.
now foot ball starts moving in your bed room

Preview of game:






Enjoy the game..............

Post your Valuable Comments.........


Thursday, 16 June 2011

Instant Mail Service- C#.Net


SMTP- Instant Mail Service:


SMTP- Simple Mail Transfer Protocol
SMTP is an Internet standard for electronic mail (e-mail) transmission across Internet Protocol (IP) networks.
This article will guide you to Design the SMTP mail Client using  .NET Frame work.
It is a very simple and cool application to mail instantly. Download  project files and Installation Files from the links below.
1. Download Project files for Developer.
2. Download Application Installation file with Windows Installer 4.5 (Size: 21.47 MB)
3. Download Application Installation file without Windows Installer 4.5 (Size: 381.50 KB)
let me guide you about step by step Development of SMTP Instant Mail Client .

Part I:

Design the Form as below.

In Tab1:

1.Add TabControl to the Form
2.Add TextBox (for To address and Subject)
3.Add Rich Text Box (Message Body)
4.Add Buttons( for Send and Clear)



















In Tab 2:
1.Add ComboBox (for Choose mail service Provider)
2.Add TextBox (for get Email address and Password)

















              You may ask why I’m dealing with basic options after  the designing Part. All these options gain their importance only while building and debugging the Application(give more importance for Naming the Controls,classes and Namespaces) .

SMTP Mail Service  basically consists, Two operations :
1. File and Directory Manipulations.
2. SMTP mail client Configuration.


1. File manipulation:
          Here, I implemented file operation instead of Database.It consists of two phases

Write to the File:

 Directory.CreateDirectory(@"C:\mailserv"); //Set path for folder
 FileStream fs = new FileStream(@"C:\mailserv\temp.txt",            
                                            FileMode.CreateNew, FileAccess.ReadWrite);
 fs.Close();
 StreamWriter sd = new StreamWriter(@"C:\mailserv\temp.txt");
 string ad = sendfrmtxt.Text + "\t" + Passwordtxt.Text + "\t" +

                                                 comboBox1.SelectedItem.ToString();
 sd.WriteLine(ad);// write to file
 sd.Flush(); //clear the Buffer
 sd.Close(); //close the writer


Read File:

StreamReader sr = new StreamReader(@"C:\mailserv\temp.txt");// set path for file reader
string tmp = sr.ReadLine();
string[] a = tmp.Split('\t'); // seperat the username and password
sendfrmtxt.Text = a[0];
Passwordtxt.Text = a[1];
passwordtxt2.Text = a[1];

2. SMTP client  Configuration :

Using System.Net.Mail; - class is used used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery.

MailMessage mMailMessage = new MailMessage();
mMailMessage.From = new MailAddress("From mail address");
mMailMessage.To.Add(new MailAddress("To mail address"));
mMailMessage.Subject ="My subject";
mMailMessage.Body = "Actual Content of the mail";
mMailMessage.IsBodyHtml = true;
mMailMessage.Priority = MailPriority.High;
//Upto this Everything is Comman for all Mail Services

SmtpClient mSmtpClient = new SmtpClient();
mSmtpClient.Port = 587; // Gmail works on this port
mSmtpClient.Host = "smtp.gmail.com";
mSmtpClient.EnableSsl = true; //Gmail works on Server Secured Layr

Note that Port number and Host name may differ for each Mail service
Eg:
1.For yahoo port=456 and host=smtp.mail.yahoo.com
2.For windowslive port=587  and host=smtp.live.com


Part II:

Complete Coding:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Net.Mail;//for Mail client
using System.IO;

namespace Mailing
{
    public partial class Mail : Form
    {
   
        SmtpClient mSmtpClient = new SmtpClient();
        public Mail()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            this.loadall();//Calling Finction
        }

        private void ButtonSend_Click(object sender, EventArgs e)
        {

            try
            {
                MailMessage mMailMessage = new MailMessage();
                mMailMessage.From = new MailAddress(sendfrmtxt.Text);
                mMailMessage.To.Add(new MailAddress(sendto.Text));
                mMailMessage.Subject = sub.Text;
                mMailMessage.Body = mesgtxt.Text;
                mMailMessage.IsBodyHtml = true;
                mMailMessage.Priority = MailPriority.High;
             
                mSmtpClient.Credentials = new
                      System.Net.NetworkCredential(sendfrmtxt.Text, Passwordtxt.Text);
            
                mSmtpClient.Send(mMailMessage);
                MessageBox.Show("Mail send Successfully", "Instant Mail Box");
            }
            catch (Exception e1)
            {
               MessageBox.Show(e1.Message+"CheckSettings,username, password","Error");
            }

        }

        private void Button3_Click(object sender, EventArgs e)
        {

            this.saveall();   //calling function
        }
      
        private void Mail_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("Do you want to close the Application", "Instant Mail
                     Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                 MessageBoxDefaultButton.Button2) == DialogResult.No)
                e.Cancel = true;
            else
                e.Cancel = false;
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            mesgtxt.Clear();
        }


        private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (TabControl1.SelectedIndex == 0)
            {
                this.saveall();
            }
            if (TabControl1.SelectedIndex == 1)
            {
                notify.Visible = false;
            }
        }


//called functions

        public void loadall()
        {
            try
            {
                StreamReader sr = new StreamReader(@"C:\mailserv\temp.txt");
                string tmp = sr.ReadLine();
                string[] a = tmp.Split('\t');

                sendfrmtxt.Text = a[0];
                Passwordtxt.Text = a[1];
                passwordtxt2.Text = a[1];
                comboBox1.SelectedItem = a[2];
                if (a[2] == "Gmail")
                {
                    mSmtpClient.Port = 587; // Gmail works on this port
                    mSmtpClient.Host = "smtp.gmail.com";
                    mSmtpClient.EnableSsl = true; //Gmail works on Server Secured Layr
                }
                else if (a[2] == "Live")
                {
                    mSmtpClient.Port = 587;
                    mSmtpClient.Host = "smtp.live.com";
                    mSmtpClient.EnableSsl = true; //windowslive works on Server Secure
                }
                else if (a[2] == "Yahoo")
                {
                    mSmtpClient.Port = 465;
                    mSmtpClient.Host = "smtp.mail.yahoo.com";
                    mSmtpClient.EnableSsl = true;
                }
                sr.Close();
            }
            catch(Exception)
            {
                MessageBox.Show("Goto to the Settings and Set your username and
                           Password    Contact:www.facebook.com/nmkr90", "New User");
            }
         }



        public void saveall()
        {
            if (Passwordtxt.Text == passwordtxt2.Text)
            {
                try
                {
                    Directory.Delete(@"C:\mailserv", true);
                    comboBox1.SelectedItem = "Gmail";
                }
                catch (Exception)
                {
                    ;
                }
                 Directory.CreateDirectory(@"C:\mailserv");

                try
                {
               FileStream fs = new FileStream(@"C:\mailserv\temp.txt",            
                                            FileMode.CreateNew, FileAccess.ReadWrite);
                    fs.Close();
                }
                catch (Exception)
                {              ;
                }
                StreamWriter sd = new StreamWriter(@"C:\mailserv\temp.txt");
                string ad;
                try
                {
                    ad = sendfrmtxt.Text + "\t" + Passwordtxt.Text + "\t" +
                                                 comboBox1.SelectedItem.ToString();
                }
                catch (Exception)
                {
                   ad = sendfrmtxt.Text + "\t" + Passwordtxt.Text + "\t" + "Gmail";
                }
                sd.WriteLine(ad);
                sd.Flush();
                sd.Close();
                this.loadall();
                notify.Visible = true;
            }
            else
            {
                MessageBox.Show("Re-Enter Password Correctly");
            }
        }

      
    }
}