Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday, May 12, 2012

Method of simple iterations on C#

Hi, I needed to write this stuff for my vba project, but as I don't like vba I wrote it on C# so here you can get  my simple iterations method  code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication12
 {  
    class Program 
      {   
          public const int N = 3;  
          // simple iteration method procedure
          static public void ProstIterMetode(double[,]a, double[] d)
          {
             int i,j;
             double[] x0 = new double [N];
             double delta;
             double[] E = new double [N];
             double[] x = new double [N];
             x0=d;
     
            do {
                 for (i=0; i< N; i++)
                 {
                     x[i]=0;
                     for(j=0; j< N; j++)
                     {
                         x[i]=x[i]+a[i,j]*x0[j]; 
                     }
                     x[i]=x[i]+d[i];
                     E[i]=Math.Abs(x[i]-x0[i]); 
                 }
               delta=E[0];
               for (i=1; i< N; i++)
               {
                  if (delta<E[i]) delta=E[i];
               };
               x0=x; 
             } while(delta<=0.000001);
    
           for (i = 0; i < N; i++)
              Console.WriteLine(x[i]);
           } 


    static void Main(string[] args)
     {
       double[,] a = new double[N, N];
       double[] b = new double[N];
       double[] x = new double[N];
       for (int i = 0; i < N; i++)
         for (int j = 0; j < N; j++)
           a[i, j] = i+1; // Convert.ToDouble(Console.ReadLine());
      for (int i = 0; i < N; i++)
       {
         for (int j = 0; j < N; j++)
           Console.Write(a[i, j] + " ");
         Console.WriteLine();
       }
      
       Console.WriteLine("Input b");
       for (int i = 0; i < N; i++)
         b[i] = i + 1;//Convert.ToDouble(Console.ReadLine());       


       Console.WriteLine("Input x");
       for (int i = 0; i < N; i++)
         x[i] = i + 1; //Convert.ToDouble(Console.ReadLine());  
          
        ProstIterMetode(a, b);


           }
   }
 }

Thursday, March 29, 2012

OpenGl house3D C# tao framework, 3DMax project

Hi there. Today I'll show you how to write something like a game with C#, OpenGL, Tao framework and  3D Max. It looks like that:




So first off all we must come up with structure of our program. it will consist of the following classes: House, camera, controller, exterior.

Than we need to draw the house, I did this job in 3DMax and it was really easy. You can find many different lessons or documentation, on how to do this in the internet, or even by some books but I prefer the first :)

You can DOWNLOAD it from HERE. And here is the project code:


The MainForm:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ShadowEngine;
using ShadowEngine.OpenGL;
using Tao.OpenGl;
using ShadowEngine.Sound;

namespace Casa
{
    public partial class MainForm : Form
    {
        //handle the viewport
        uint hdc;
        controller controller = new controller();
        int moving;
        static Vector2 formPos;
        bool lines;
        bool pressedH;

        public static Vector2 FormPos
        {
            get { return MainForm.formPos; }
            set { MainForm.formPos = value; }
        }

        public MainForm()
        {
            InitializeComponent();
            //identifier of where I will draw
            hdc = (uint)pnlViewPort.Handle;
            //making the mistake that happened
            string error = "";
            //Command initialization of the viewport
            OpenGLControl.OpenGLInit(ref hdc, pnlViewPort.Width, pnlViewPort.Height, ref error);

            if (error != "")
            {
                MessageBox.Show(error);
            }

            // start position of the camera angle so as defined in perspective, etc etc
            controller.Camera.InitCamera();
            //Enables the lights
            Lighting.SetupLighting();
            ContentManager.SetTextureList("textures\\"); //specify the location of the textures
            ContentManager.LoadTextures(); //the charge
            ContentManager.SetModelList("models\\"); // the specific location of the office
            ContentManager.LoadModels(); //the charge
            Camera.CenterMouse();
            controller.creatingObjects();
        }

        private void tmrPaint_Tick(object sender, EventArgs e)
        {
            // opengl clean paint
            Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT);
            //draws the entire scene
            controller.Camera.Update(moving);
            controller.DrawScene();
            //change the buffer
            Winapi.SwapBuffers(hdc);
            //finish paint
            Gl.glFlush();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            formPos = new Vector2(this.Left, this.Top); // first coordinates of camera
        }
     
        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {


            if (!pressedH)
            {
                panel1.Visible = true;
                panel2.Visible = true;
                panel3.Visible = true;
                panel4.Visible = true;
                pressedH = true;
            }
            else
            {
                panel1.Visible = false;
                panel2.Visible = false;
                panel3.Visible = false;
                panel4.Visible = false;
                pressedH = false;
            }
         
            if (e.KeyCode == Keys.Escape)
            {
                Close();
            }
            if (e.KeyCode == Keys.W)
            {
                moving = 1;
            }

            if (e.KeyCode == Keys.L)
            {
                if (lines)
                {
                    Gl.glPolygonMode(Gl.GL_FRONT_AND_BACK, Gl.GL_FILL);
                    lines = false;
                }
                else
                {
                    Gl.glPolygonMode(Gl.GL_FRONT_AND_BACK, Gl.GL_LINE);
                    lines = true;
                }
            }
        }

        private void pnlViewPort_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                moving = 1;
            }
            if (e.Button == MouseButtons.Right)
            {
                moving = -1;
            }
        }

        private void pnlViewPort_MouseUp(object sender, MouseEventArgs e)
        {
            moving = 0;
        }

        private void MainForm_KeyUp(object sender, KeyEventArgs e)
        {
            moving = 0;
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void pnlViewPort_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}






The class House:


using System;
using System.Collections.Generic;
using System.Text;
using ShadowEngine;
using ShadowEngine.ContentLoading;
using Tao.OpenGl;

namespace Casa
{
    public class House
    {
        ModelContainer m;
        Mesh aspa;
        float bladeAngle;

     

        public void Create()
        {        
            m = ContentManager.GetModelByName("house3.3DS");      
            m.CreateDisplayList();
            aspa = m.GetMeshWithName("ventilado0");
            aspa.CalcCenterPoint(); // calculating the midpoint of the object
            m.RemoveMeshByName("ventilado0"); //remove the mesh        
        }

        public void CreateCollisions()
        {
            Collision.AddCollisionSegment(new Point3D(-24.4f, -14.1f, 0), new Point3D(18.9f, -14.1f, 0), 0.5f);
            Collision.AddCollisionSegment(new Point3D(-24.4f, -14.1f, 0), new Point3D(-24.4f, 13.2f, 0), 0.5f);
            Collision.AddCollisionSegment(new Point3D(-20.2f, -0.1f, 0), new Point3D(-4.8f, -0.1f, 0), 0.5f);
            Collision.AddCollisionSegment(new Point3D(-0.5f, 0.7f, 0), new Point3D(-0.5f, -8.7f, 0), 0.5f);
            Collision.AddCollisionSegment(new Point3D(19.4f, 14.4f, 0), new Point3D(-24.4f, 14.4f, 0), 0.5f);
            Collision.AddCollisionSegment(new Point3D(19.4f, 14.4f, 0), new Point3D(19.4f, -14.4f, 0), 0.5f);
            Collision.AddCollisionSegment(new Point3D(-17.5f, 0.5f, 0), new Point3D(-17.5f, 11, 0), 0.5f);
            Collision.AddCollisionSegment(new Point3D(13.4f, -0.15f, 0), new Point3D(18.74f, -0.15f, 0), 0.5f);
            Collision.AddCollisionSegment(new Point3D(-0.43f, -9.1f, 0), new Point3D(12.4f, -9.1f, 0), 0.5f);
            //Collision.GhostMode = true;
        }

        public void Draw()
        {
            Gl.glPushMatrix();
            Gl.glTranslatef(0, 2.3f, 0);
            Gl.glScalef(0.1f, 0.1f, 0.1f);
            m.DrawWithTextures();

            #region Ventilator (rotation, drawing...)
            Gl.glPushMatrix();
            bladeAngle += 25;
            if (bladeAngle > 3600)
            {
                bladeAngle = 0;
            }
                     
            //rotaition of ventilator
            Gl.glTranslatef(aspa.CenterPoint.X, aspa.CenterPoint.Y, aspa.CenterPoint.Z);
            Gl.glRotatef(-bladeAngle, 0, 0, 1);
            Gl.glTranslatef(-aspa.CenterPoint.X, -aspa.CenterPoint.Y, -aspa.CenterPoint.Z);
         
            Gl.glBindTexture(Gl.GL_TEXTURE_2D, ContentManager.GetTextureByName(aspa.Name + ".jpg"));  
            aspa.Draw();
            Gl.glPopMatrix();
         
            #endregion

            Gl.glPopMatrix();
        }
    }
}


Class Camera:

using System;
using System.Collections.Generic;
using System.Text;
using Tao.OpenGl;
using System.Drawing;
using ShadowEngine; 

namespace Casa
{
    public class Camera
    {
        #region Camera constants
        const double div1 = Math.PI / 180;
        const double div2 = 180 / Math.PI;
        #endregion 
        
        #region Private atributes

        static float eyex, eyey, eyez;
        static float centerx, centery, centerz;
        static float forwardSpeed = 0.3f;
        static float yaw, pitch;
        static float rotationSpeed = 1/5f;
        static double i, j, k;

        #endregion

        public static float Pitch
        {
            get { return Camera.pitch; }
            set { Camera.pitch = value; }
        }

        public static float Yaw
        {
            get { return Camera.yaw; }
            set { Camera.yaw = value; }
        }

        public void InitCamera() //initilizing pos of x,y,z
        {
            eyex = -17.1f;
            eyey = 7.3f;
            eyez = -9.4f;
            centerx = -3;
            centery = 2;
            centerz = -2; 
            Look();
        }

        public void Look()
        {
            Gl.glMatrixMode(Gl.GL_MODELVIEW);
            Gl.glLoadIdentity();
            Glu.gluLookAt(eyex, eyey, eyez, centerx, centery, centerz, 0, 1, 0);
        }

        static public float AngleToRad(double pAngle)
        {
            return (float)(pAngle * div1);
        }

        static public float RadToAngle(double pAngle)
        {
            return (float)(pAngle * div2);
        }

        public void UpdateDirVector()
        {
            k = Math.Cos(AngleToRad((double)yaw));
            i = -Math.Sin(AngleToRad((double)yaw));
            j = Math.Sin(AngleToRad((double)pitch));     
            
            
            centerz = eyez - (float)k;
            centerx = eyex - (float)i;
            centery = eyey - (float)j;
        }

        public static void CenterMouse()
        {
            Winapi.SetCursorPos(MainForm.FormPos.X + 512, MainForm.FormPos.Y + 384);   
        }

        public void Update(int pressedButton)
        {
            #region Target chamber

                Pointer position = new Pointer();
                Winapi.GetCursorPos(ref position);   

                int difX = MainForm.FormPos.X + 512 - position.x;
                int difY = MainForm.FormPos.Y + 384 - position.y;

                if (position.y < MainForm.FormPos.Y + 384)
                {
                    pitch -= rotationSpeed * difY;
                }
                else
                    if (position.y > MainForm.FormPos.Y + 384)
                    {
                        pitch += rotationSpeed * -difY;
                    }
                if (position.x < MainForm.FormPos.X + 512)
                {
                    yaw += rotationSpeed * -difX;
                }
                else
                    if (position.x > MainForm.FormPos.X + 512)
                    {
                        yaw -= rotationSpeed * difX;
                    }
                UpdateDirVector();
                CenterMouse();


                if (pressedButton == 1) // pressed the left button of mouse
                {
                    if (!Collision.CheckCollision(new Point3D(eyex - (float)i * forwardSpeed, eyez - (float)k * forwardSpeed, 0)))
                    {
                        eyex -= (float)i * forwardSpeed;
                        eyez -= (float)k * forwardSpeed;
                    }   
                }
                if (pressedButton == -1) // pressed the left button of mouse
                {
                    if (!Collision.CheckCollision(new Point3D(eyex + (float)i * forwardSpeed, eyez + (float)k * forwardSpeed, 0)))
                    {
                        eyex += (float)i * forwardSpeed;
                        eyez += (float)k * forwardSpeed;
                    }
                }

            #endregion

            Look();  
        }
    }
}


Class Controller:



using System;
using System.Collections.Generic;
using System.Text;
using ShadowEngine;


namespace Casa
{
    public class controller
    {
        Camera camera = new Camera();
        House house = new House();
        Exterior sky = new Exterior();

        public void creatingObjects()
        {
            house.Create();
            house.CreateCollisions(); // making walls
            Sprite.Create();  // draw text on screen (coordinates)
        }

        public Camera Camera
        {
            get { return camera; }
        }

        public void DrawScene()
        {
            house.Draw(); // drawing the house
            sky.Draw();  // outside the house
            DebugMode.WriteCamaraPos(200, 200);
            Collision.DrawColissions();
        }
    }
}


Class Exterior:

using System;
using System.Collections.Generic;
using System.Text;
using ShadowEngine;
using Tao.OpenGl;

namespace Casa
{
    class Exterior
    {
        public void Draw()
        {
            // size height and length
            int width = 240;
            int height = 200;
            int length = 240;

            // begins at these coordinates
            int x = 10;
            int y = -3;
            int z = 7;

            //encentrar the square
            x = x - width / 2;
            y = y - height / 2;
            z = z - length / 2;

            Gl.glEnable(Gl.GL_TEXTURE_2D);
            Gl.glBindTexture(Gl.GL_TEXTURE_2D, ContentManager.GetTextureByName("back.jpg"));

            //begins to draw squares
            Gl.glBegin(Gl.GL_QUADS);
            Gl.glNormal3d(-1, 1, 1);
            Gl.glTexCoord2f(1.0f, 0.0f); Gl.glVertex3d(x + width, y, z);
            Gl.glNormal3d(-1, -1, 1);
            Gl.glTexCoord2f(1.0f, 1.0f); Gl.glVertex3d(x + width, y + height, z);
            Gl.glNormal3d(1, -1, 1);
            Gl.glTexCoord2f(0.0f, 1.0f); Gl.glVertex3d(x, y + height, z);
            Gl.glNormal3d(1, 1, 1);
            Gl.glTexCoord2f(0.0f, 0.0f); Gl.glVertex3d(x, y, z);
            Gl.glEnd();

            Gl.glBindTexture(Gl.GL_TEXTURE_2D, ContentManager.GetTextureByName("front.jpg"));
            Gl.glBegin(Gl.GL_QUADS);
            Gl.glNormal3d(1, 1, -1);
            Gl.glTexCoord2f(1.0f, 0.0f); Gl.glVertex3d(x, y, z + length);
            Gl.glNormal3d(1, -1, -1);
            Gl.glTexCoord2f(1.0f, 1.0f); Gl.glVertex3d(x, y + height, z + length);
            Gl.glNormal3d(-1, -1, -1);
            Gl.glTexCoord2f(0.0f, 1.0f); Gl.glVertex3d(x + width, y + height, z + length);
            Gl.glNormal3d(-1, 1, -1);
            Gl.glTexCoord2f(0.0f, 0.0f); Gl.glVertex3d(x + width, y, z + length);
            Gl.glEnd();

            Gl.glBindTexture(Gl.GL_TEXTURE_2D, ContentManager.GetTextureByName("top.jpg"));
            Gl.glBegin(Gl.GL_QUADS);
            Gl.glNormal3d(-1, -1, 1);
            Gl.glTexCoord2f(1.0f, 0.0f); Gl.glVertex3d(x + width, y + height, z);
            Gl.glNormal3d(-1, -1, -1);
            Gl.glTexCoord2f(1.0f, 1.0f); Gl.glVertex3d(x + width, y + height, z + length);
            Gl.glNormal3d(1, -1, -1);
            Gl.glTexCoord2f(0.0f, 1.0f); Gl.glVertex3d(x, y + height, z + length);
            Gl.glNormal3d(1, -1, 1);
            Gl.glTexCoord2f(0.0f, 0.0f); Gl.glVertex3d(x, y + height, z);
            Gl.glEnd();

            Gl.glBindTexture(Gl.GL_TEXTURE_2D, ContentManager.GetTextureByName("left.jpg"));
            Gl.glBegin(Gl.GL_QUADS);
            Gl.glNormal3d(1, -1, 1);
            Gl.glTexCoord2f(0.0f, 1.0f); Gl.glVertex3d(x, y + height, z);
            Gl.glNormal3d(1, -1, -1);
            Gl.glTexCoord2f(1.0f, 1.0f); Gl.glVertex3d(x, y + height, z + length);
            Gl.glNormal3d(1, 1, -1);
            Gl.glTexCoord2f(1.0f, 0.0f); Gl.glVertex3d(x, y, z + length);
            Gl.glNormal3d(1, 1, 1);
            Gl.glTexCoord2f(0.0f, 0.0f); Gl.glVertex3d(x, y, z);
            Gl.glEnd();

            Gl.glBindTexture(Gl.GL_TEXTURE_2D, ContentManager.GetTextureByName("right.jpg"));
            Gl.glBegin(Gl.GL_QUADS);
            Gl.glNormal3d(-1, 1, 1);
            Gl.glTexCoord2f(0.0f, 0.0f); Gl.glVertex3d(x + width, y, z);
            Gl.glNormal3d(-1, 1, -1);
            Gl.glTexCoord2f(1.0f, 0.0f); Gl.glVertex3d(x + width, y, z + length);
            Gl.glNormal3d(-1, -1, -1);
            Gl.glTexCoord2f(1.0f, 1.0f); Gl.glVertex3d(x + width, y + height, z + length);
            Gl.glNormal3d(-1, -1, 1);
            Gl.glTexCoord2f(0.0f, 1.0f); Gl.glVertex3d(x + width, y + height, z);
            Gl.glEnd();

            Gl.glBindTexture(Gl.GL_TEXTURE_2D, ContentManager.GetTextureByName("GRASS2.JPG"));
            Gl.glBegin(Gl.GL_QUADS);
            Gl.glNormal3d(1, 1, 1);
            Gl.glTexCoord2f(8.0f, 0.0f); Gl.glVertex3d(x, 1, z);
            Gl.glNormal3d(1, 1, -1);
            Gl.glTexCoord2f(8.0f, 8.0f); Gl.glVertex3d(x, 1, z + length);
            Gl.glNormal3d(-1, 1, -1);
            Gl.glTexCoord2f(0.0f, 8.0f); Gl.glVertex3d(x + width, 1, z + length);
            Gl.glNormal3d(-1, 1, 1);
            Gl.glTexCoord2f(0.0f, 0.0f); Gl.glVertex3d(x + width, 1, z);
            Gl.glEnd();
        }
    }
}

Class winApi



using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace Casa
{
    public struct Pointer
    {
        public int x;
        public int y;
    }

    public static class Winapi
    {
        [DllImport("GDI32.dll")]
        public static extern void SwapBuffers(uint hdc);

        [DllImport("user32.dll")]
        public static extern void SetCursorPos(int x, int y);

        [DllImport("user32.dll")]
        public static extern void GetCursorPos(ref Pointer point);
    }
}




Friday, October 7, 2011

How to write tic tac toe on C# (C sharp)







Hi, now I will show you how to write tic tac toe on C# (C sharp).
First of all you need to add on Form 10 buttons and 4 labels.













The Form should look like this:








After that we will write some C# code:






using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Tic_tac
{
    public partial class Form1 : Form
    {
        bool Player1 = true;
        bool Player2 = false;
        int X = 0;
        int O = 0;


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button10_Click(object sender, EventArgs e)
        {
            button1.Text = "";
            button2.Text = "";
            button3.Text = "";
            button4.Text = "";
            button5.Text = "";
            button6.Text = "";
            button7.Text = "";
            button8.Text = "";
            button9.Text = "";
            
            Player1 = true;
            Player2 = false;
           

        }

       

        private void button1_Click(object sender, EventArgs e)
        {
            if (Player1 == true)
            {
                //Player1 = true;
                button1.Text = "X";
                Player1 = false;
            }
            else
            {
                Player2 = true;
                button1.Text = "O";
                Player2 = false;
                Player1 = true;
            }  
            Wincombination();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (Player1 == true)
            {
                //Player1 = true;
                button2.Text = "X";
                Player1 = false;
            }
            else
            {
                Player2 = true;
                button2.Text = "O";
                Player2 = false;
                Player1 = true;
            }
            Wincombination();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (Player1 == true)
            {
                //Player1 = true;
                button3.Text = "X";
                Player1 = false;
            }
            else
            {
                Player2 = true;
                button3.Text = "O";
                Player2 = false;
                Player1 = true;
            }

            Wincombination();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (Player1 == true)
            {
                //Player1 = true;
                button4.Text = "X";
                Player1 = false;
            }
            else
            {
                Player2 = true;
                button4.Text = "O";
                Player2 = false;
                Player1 = true;
            }

            Wincombination();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (Player1 == true)
            {
                //Player1 = true;
                button5.Text = "X";
                Player1 = false;
            }
            else
            {
                Player2 = true;
                button5.Text = "O";
                Player2 = false;
                Player1 = true;
            }

            Wincombination();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (Player1 == true)
            {
               // Player1 = true;
                button6.Text = "X";
                Player1 = false;
            }
            else
            {
                Player2 = true;
                button6.Text = "O";
                Player2 = false;
                Player1 = true;
            }

            Wincombination();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (Player1 == true)
            {
               // Player1 = true;
                button7.Text = "X";
                Player1 = false;
            }
            else
            {
                Player2 = true;
                button7.Text = "O";
                Player2 = false;
                Player1 = true;
            }

            Wincombination();
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (Player1 == true)
            {
             //   Player1 = true;
                button8.Text = "X";
                Player1 = false;
            }
            else
            {
                Player2 = true;
                button8.Text = "O";
                Player2 = false;
                Player1 = true;
            }

            Wincombination();
        }

        private void button9_Click(object sender, EventArgs e)
        {
            if (Player1 == true)
            {
             //   Player1 = true;
                button9.Text = "X";
                Player1 = false;
            }
            else
            {
                Player2 = true;
                button9.Text = "O";
                Player2 = false;
                Player1 = true;
            }

            Wincombination();
        }

        private void Wincombination()
        {
            if (button1.Text == "X" && button2.Text == "X" && button3.Text == "X")
            {
                MessageBox.Show("X Win!", "Game over", MessageBoxButtons.OK);
                X = X + 1;
                label1.Text = X.ToString("");
            }
            if (button4.Text == "X" && button5.Text == "X" && button6.Text == "X")
            {
                MessageBox.Show("X Win!", "Game over", MessageBoxButtons.OK);
                X = X + 1;
                label1.Text = X.ToString("");
            }
            if (button7.Text == "X" && button8.Text == "X" && button9.Text == "X")
            {
                MessageBox.Show("X Win!", "Game over", MessageBoxButtons.OK);
                X = X + 1;
                label1.Text = X.ToString("");
            }

            if (button1.Text == "X" && button5.Text == "X" && button9.Text == "X")
            {
                MessageBox.Show("X Win!", "Game over", MessageBoxButtons.OK);
                X = X + 1;
                label1.Text = X.ToString("");
            }
            if (button3.Text == "X" && button5.Text == "X" && button7.Text == "X")
            {
                MessageBox.Show("X Win!", "Game over", MessageBoxButtons.OK);
                X = X + 1;
                label1.Text = X.ToString("");
            }

            if (button1.Text == "X" && button4.Text == "X" && button7.Text == "X")
            {
                MessageBox.Show("X Win!", "Game over", MessageBoxButtons.OK);
                X = X + 1;
                label1.Text = X.ToString("");
            }
            if (button2.Text == "X" && button5.Text == "X" && button8.Text == "X")
            {
                MessageBox.Show("X Win!", "Game over", MessageBoxButtons.OK);
                X = X + 1;
                label1.Text = X.ToString("");
            }
            if (button3.Text == "X" && button6.Text == "X" && button9.Text == "X")
            {
                MessageBox.Show("X Win!", "Game over", MessageBoxButtons.OK);
                X = X + 1;
                label1.Text = X.ToString("");
            }

            // for O

            if (button1.Text == "O" && button2.Text == "O" && button3.Text == "O")
            {
                MessageBox.Show("O Win!", "Game over", MessageBoxButtons.OK);
                O = O + 1;
                label2.Text = O.ToString("");
            }
            if (button4.Text == "O" && button5.Text == "O" && button6.Text == "O")
            {
                MessageBox.Show("O Win!", "Game over", MessageBoxButtons.OK);
                O = O + 1;
                label2.Text = O.ToString("");
            }
            if (button7.Text == "O" && button8.Text == "O" && button9.Text == "O")
            {
                MessageBox.Show("O Win!", "Game over", MessageBoxButtons.OK);
                O = O + 1;
                label2.Text = O.ToString("");
            }

            if (button1.Text == "O" && button5.Text == "O" && button9.Text == "O")
            {
                MessageBox.Show("O Win!", "Game over", MessageBoxButtons.OK);
                O = O + 1;
                label2.Text = O.ToString("");
            }
            if (button3.Text == "O" && button5.Text == "O" && button7.Text == "O")
            {
                MessageBox.Show("O Win!", "Game over", MessageBoxButtons.OK);
                O = O + 1;
                label2.Text = O.ToString("");
            }

            if (button1.Text == "O" && button4.Text == "O" && button7.Text == "O")
            {
                MessageBox.Show("O Win!", "Game over", MessageBoxButtons.OK);
                O = O + 1;
                label2.Text = O.ToString("");
            }
            if (button2.Text == "O" && button5.Text == "O" && button8.Text == "O")
            {
                MessageBox.Show("O Win!", "Game over", MessageBoxButtons.OK);
                O = O + 1;
                label2.Text = O.ToString("");
            }
            if (button3.Text == "O" && button6.Text == "O" && button9.Text == "O")
            {
                MessageBox.Show("O Win!", "Game over", MessageBoxButtons.OK);
                O = O + 1;
                label2.Text = O.ToString("");
            }


        }

        private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            button1.Text = "";
            button2.Text = "";
            button3.Text = "";
            button4.Text = "";
            button5.Text = "";
            button6.Text = "";
            button7.Text = "";
            button8.Text = "";
            button9.Text = "";

            Player1 = true;
            Player2 = false;
            X = 0;
            O = 0;
            label1.Text = "0";
            label2.Text = "0";
        }

        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Tic-Tac-Toe 1.0 by Bogdan Ustyak");
        }
    }
}

Microsoft. NET Framework



    Microsoft. NET (read dot-net) - software technology offered by Microsoft as a platform for creating both conventional programs and web applications. In many ways a continuation of the ideas and principles that are the technology of Java.
One of the ideas. NET is compatible services written in different languages. Although this opportunity is advertised as a benefit of Microsoft. NET, Java platform has the same opportunity.

    Each library (assembly) in. NET is a testimony of his version, which allows to eliminate possible conflicts between different versions of assemblies.
    .NET - cross-platform technology currently exists for the implementation of the Platform Microsoft Windows, FreeBSD (from Microsoft) and a variant of Linux technology for the project Mono (under an agreement between Microsoft with Novell), DotGNU [1].

    Copyright protection applies to a runtime (CLR - Common Language Runtime) for programs. NET. Compiler. NET produced by many companies for different languages ​​freely.

    . NET is divided into two main parts - the runtime (essentially a virtual machine) and development tools.
Development environment. NET-applications: Visual Studio. NET (C + +, C #, J #), SharpDevelop, Borland Developer Studio (Delphi, C #) and so is the Eclipse application development. NET-applications. Applicable program can also devise a text editor and use the command-line compiler.

    As technology is Java, development environment. NET generates byte code designed to perform a virtual machine. Input language of the machine in. NET is called CIL (Common Intermediate Language), also known as MSIL (Microsoft Intermediate Language), or just IL. The use of byte-code allows you krossplatformenist at precompiled project (in terms of. NET: collection), but not at the level of the original text, such as in C. Before starting the assembly in runtime (CLR) byte-code is converted into a built environment JIT-compiler (just in time, compiling on the fly) into machine code target processor.

    It should be noted that one of the first JIT-Compiler for Java was also developed by Microsoft (currently in Java using a multilevel perfect compilation - Sun HotSpot). Modern technology allows dynamic compilation to achieve the same level of performance with traditional 'static' compilers (like C + +) and performance issues often depends on the quality of a compiler.

Saturday, October 1, 2011

Gauss - Jordan method delphi / pascal / c#

  Today I have wrote Gauss - Jordan method on C# and delphi. It's also can be used on Pascal, you just need to rewrite it, without any problems.
Procedure written on C# is in the end of article.
   Program result you will find in text file "Result".
   There are couple procedures like "readFile" that read matrix from text file. In files there are such matrix:
1:
1 -4 -3 8
2 -6 -4 2
3 -8 1 -4
4 2 2 -6


2:
0 1 -6 -4
3 -1 -6 -4
2 3 9 2
3 2 3 8


3:
-3 -3 4
0 -1 0
6 2 -4

4:
-3 -3 2
0 -1 0
6 2 -4

So here it is...


program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type TMatrix = array [1..50,1..50] of real;
     TVect = array [1..50] of real;
     TFile = textFile;

var A: TMatrix ; b:TVect; n, per:integer; t,f:TFile; c:byte; s:string;

 procedure readFile(var A:TMatrix; var n:integer);
  var i,j:integer;
   begin  i:=1; j:=1;
    while not eof(t) do
     begin j:=1;
       while not eoln(t) do
         begin
           read(t,a[i,j]);
           inc(j);
         end;
         readln(t);
         inc(i);
     end;
     closeFile(t);
   end;


procedure setMatrix(var A:TMatrix; var n:integer);
var i,j:integer;
 begin
 writeln('Input Matrix A');
  for i := 1 to n do
   for j := 1 to n do
   begin
      write ('a',i,',', j ,'=');
    readln(A[i,j]);
   end;
  end;

procedure setVect(var b:TVect; var n:integer);
   var i:integer;
    begin
      for i := 1 to n do
      begin
        write ('b',i,'=');
        readln(b[i]);
      end;
    end;

procedure Gauss (A:TMatrix;b:TVect; n:integer);
var
  i, j, k,step:integer;    R,det,p:real;
       x:TVect;
 begin
 per:=1;
  for i := 1 to N - 1 do
   begin
    k := i;
    R := Abs(A[i, i]);
    for j := i + 1 to N do
     if (Abs(A[j, i]) >= R) then
      begin
       k := j;
       R := Abs(A[j, i]);
      end;
     if (k <> i) then
      begin
       R := B[k];
       B[k] := B[i];
       B[i] := R;
       for j := i to N do
        begin
         R := A[k, j];
         A[k, j] := A[i, j];
         A[i, j] := R;
        end;
       end;
                 R := A[i, i];
                  if R = 0 then  begin writeln('Denom <0'); readln; halt; end;
                 B[i] := B[i] / R;
                 for j := 1 to N do
                   begin
                    if R = 0 then begin writeln('Denom <0'); readln;  halt; end;
                     A[i, j] := A[i, j] / R;
                   end;
                 for k := i + 1 to N do
                 begin
                     R := A[k, i];
                     B[k] := B[k] - R * B[i];
                     A[k, i] := 0;
                     for j := i + 1 to N do
                        A[k, j] := A[k, j] - R * A[i, j];
                 end;
        end;
          if A[N,N] = 0 then begin writeln('Denom <0');readln;  halt; end;
         X[N] := B[N] / A[N, N];

         for i := N - 1 downto 1 do
         begin
             R := B[i];
             for j := i + 1 to N do
                 R := R - A[i, j] * X[j];
             X[i] := R;

          per:=per+1;
         end;


         for i:= 1 to n do
           writeln('x',i,'= ',x[i]:5:2);
 end;

procedure showMatrix(A:TMatrix; n:integer);
    var i,j:integer;
  begin
    for i := 1 to n do
    begin
      for j := 1 to n do
        write(A[i,j]:4:2,' ');
        writeln;
    end;
  end;

procedure Determinant;
var   i,step,k:integer;
      p,det:real;
begin
p:=1;
       step:=1;
       for i:=1 to per do
        step:=step*(-1);
       for k:=1 to n do
             begin
              p:=p * a[k,k];
              det:=p * step;
            end;
            writeln('Determinant = ', det:5:2);
end;


 procedure writeFile(x:TVect);
     var i:integer;
   begin
     for i := 1 to n do
       write(f,x[i],' ');
   end;

begin
writeln('Which matrix do you want to calculate');
readln(c);
case c of
1:
  begin
    s:='Matrix1.txt';
    n:=4;
  end;
2:
  begin
    s:='Matrix2.txt';
    n:=4
  end;
3:
  begin
    s:='Matrix3.txt';
    n:=3;
  end;
4:
  begin
    s:='Matrix4.txt';
    n:=3;
  end;
end;

assignFile(t,s);
reset(t);
//setMatrix(A,n);
readFile(A,n);
showMatrix(A,n);
setVect(B,n);


AssignFile(f,'Result.txt');
Rewrite(f);
Gauss(a,b,n);
determinant;
writeFile(b);
CloseFile(f);
writeln('Results are in text file "Results"');
readln
end.

//==============================================
//Procedure written on C#


static public void Gauss (ref double[,] A, ref double[] B, int N,
ref double[] X)
 {
  int i, j, k;
  double R;
  for (i = 1; i <= N - 1; i++)
   {
    k = i;
    R = Math.Abs(A[i, i]);
    for (j = i + 1; j <= N; j++)
     if (Math.Abs(A[j, i]) >= R)
      {
       k = j;
       R = Math.Abs(A[j, i]);
      }
     if (k != i)
      {
       R = B[k];
       B[k] = B[i];
       B[i] = R;
       for (j = i; j < N; j++)
        {
         R = A[k, j];
         A[k, j] = A[i, j];
         A[i, j] = R;
        }
       }
                 R = A[i, i];
                 B[i] = B[i] / R;
                 for (j = 1; j <= N; j++)
                     A[i, j] = A[i, j] / R;
                 for (k = i + 1; k <= N; k++)
                 {
                     R = A[k, i];
                     B[k] = B[k] - R * B[i];
                     A[k, i] = 0;
                     for (j = i + 1; j <= N; j++)
                         A[k, j] = A[k, j] - R * A[i, j];
                 }
             }
         X[N] = B[N] / A[N, N];
         for (i = N - 1; i >= 1; i--)
         {
             R = B[i];
             for (j = i + 1; j <= N; j++)
                 R = R - A[i, j] * X[j];
             X[i] = R;
         }
     }
 }


// program written on C++ from dreamincode.net


/******************************************************************************/
/* Perform Gauss-Jordan elimination with row-pivoting to obtain the solution to
 * the system of linear equations
 * A X = B
 *
 * Arguments:
 * lhs - left-hand side of the equation, matrix A
 * rhs - right-hand side of the equation, matrix B
 * nrows - number of rows in the arrays lhs and rhs
 * ncolsrhs- number of columns in the array rhs
 *
 * The function uses Gauss-Jordan elimination with pivoting.  The solution X to
 * the linear system winds up stored in the array rhs; create a copy to pass to
 * the function if you wish to retain the original RHS array.
 *
 * Passing the identity matrix as the rhs argument results in the inverse of
 * matrix A, if it exists.
 *
 * No library or header dependencies, but requires the function swaprows, which
 * is included here.
 */

//  swaprows - exchanges the contents of row0 and row1 in a 2d array
void swaprows(double** arr, long row0, long row1) {
    double* temp;
    temp=arr[row0];
    arr[row0]=arr[row1];
    arr[row1]=temp;
}

// gjelim
void gjelim(double** lhs, double** rhs, long nrows, long ncolsrhs) {

    // augment lhs array with rhs array and store in arr2
    double** arr2=new double*[nrows];
    for (long row=0; row<nrows; ++row)
        arr2[row]=new double[nrows+ncolsrhs];

    for (long row=0; row<nrows; ++row) {
        for (long col=0; col<nrows; ++col) {
            arr2[row][col]=lhs[row][col];
        }
        for (long col=nrows; col<nrows+ncolsrhs; ++col) {
            arr2[row][col]=rhs[row][col-nrows];
        }
    }

    // perform forward elimination to get arr2 in row-echelon form
    for (long dindex=0; dindex<nrows; ++dindex) {
        // run along diagonal, swapping rows to move zeros in working position
        // (along the diagonal) downwards
        if ( (dindex==(nrows-1)) && (arr2[dindex][dindex]==0)) {
            return; //  no solution
        } else if (arr2[dindex][dindex]==0) {
            swaprows(arr2, dindex, dindex+1);
        }
        // divide working row by value of working position to get a 1 on the
        // diagonal
        if (arr2[dindex][dindex] == 0.0) {
            return;
        } else {
            double tempval=arr2[dindex][dindex];
            for (long col=0; col<nrows+ncolsrhs; ++col) {
                arr2[dindex][col]/=tempval;
            }
        }

        // eliminate value below working position by subtracting a multiple of
        // the current row
        for (long row=dindex+1; row<nrows; ++row) {
            double wval=arr2[row][dindex];
            for (long col=0; col<nrows+ncolsrhs; ++col) {
                arr2[row][col]-=wval*arr2[dindex][col];
            }
        }
    }

    // backward substitution steps
    for (long dindex=nrows-1; dindex>=0; --dindex) {
        // eliminate value above working position by subtracting a multiple of
        // the current row
        for (long row=dindex-1; row>=0; --row) {
            double wval=arr2[row][dindex];
            for (long col=0; col<nrows+ncolsrhs; ++col) {
                arr2[row][col]-=wval*arr2[dindex][col];
            }
        }
    }

    // assign result to replace rhs
    for (long row=0; row<nrows; ++row) {
        for (long col=0; col<ncolsrhs; ++col) {
            rhs[row][col]=arr2[row][col+nrows];
        }
    }

    for (long row=0; row<nrows; ++row)
        delete[] arr2[row];
    delete[] arr2;
}