CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13
  1. #1
    Join Date
    Feb 2006
    Posts
    11

    C# Game Code Samples I would like to see ....

    Hi,
    I'm trying to learn game programming with C# and was just looking for some very rudimentary examples. I would just like to see some very basic code samples which each do one simple thing. I drew up a list of what I would consider to be a good game programming 101. When I was learning BASIC some 20 years ago, I was able to learn to do most of the stuff on this list within a few days. I am having a much more difficult time doing the same thing in C#.
    I'm sure most of this stuff is unbelievably simple for somebody out there. Please help by submitting some of the samples on this list.

    Note: Each of these should be a separate code example. I'm not talking about one big application that does everything on this list.


    Make a dot

    Make dot move every time you hit the enter key using a simple loop

    1. Draw new dot each time refreshing the screen

    2. Keep adding more dots to existing canvas

    Make a game loop which exits when you hit the Esc key

    Make dot move using arrow keys

    Make it so when dot exits on right side of screen it enters again on the left

    Make it so dot cannot go beyond edge of screen

    Make a square room for dot

    Make dot move around at 45 degree angles and bounce off walls like in Pong

    Make a rectangle paddle and make it move left and right using mouse

    Add collision to paddle

    OK now let's think Space Invaders:
    Change the paddle to a 2D sprite of a spaceship

    Change the dot to 2D animated sprite monster

    Make the ship fire dots every time you click the mouse or hit the spacebar

    Make it so when dot hit's monster, it adds a point to score displayed on screen

    Make monster display an explosion graphic and disappear when hit

    Now think Pac Man:
    Player has 3 lives. Every time a monster touches player, the game halts and you have to start over. After 3 fails, display the end screen with final score and give the option to play again.

    Now, make level 1 with 1 monster, level 2 has 2 monsters, level 3 etc...
    each time you complete a level you get a congratulations screen.

    Add sounds. Exploding monster, firing gun, looping soundtrack.

    Create a high scores list. Allow user to enter their name if they make the top 10.

    Now let's think 3D:

    Make a cube

    1. Rotate cube in x or y using mouse

    2. Rotate camera around cube using mouse

    Make a 3D room with the camera positioned above the room looking down.
    Add textures to walls.
    Add tiled texture to floor.

    Add a teapot and apply a generic color

    Now think Tanks:
    Make the teapot rotate using the left and right arrow keys and move forward using the up arrow key.
    Make the teapot fire a ball when you hit a mouse button or hit the space bar
    Create explosion effect when ball hits wall or object.
    Draw graphic on wall where ball hits.
    Add parablic curve to ball trajectory to simulate gravity.
    Add colored cube Ammo Pickup and give the teapot an Ammo Limit.
    Make pickups appear periodically in random locations.
    Add assorted color obstacles using various DirectX primitives.

    Basic AI
    Make a colored cone with the point facing forward to indicate the front.
    Make the cone a zombie: randomly wandering about, bumping into walls.
    Make a different color zombie. This one still wanders aimlessly, but avoids walls and obstacles.
    Make another color cone which follows you wherever you go.
    Make another color cone which will follow you only if you are within it's field of vision.
    Make another which will only attack if you are within a certain range.
    Make an enemy that shoots back at you.

    Make enemies which will spawn duplicates of themselves if you don't shoot them within a certain amount of time.

    Replace teapot with mesh model
    Make model play an animation when moving forward / shooting

    Make the camera follow the model
    Make objects which get between camera and model transparent
    Make option to switch between First Person and camera views

    Make game fill screen

  2. #2
    Join Date
    Feb 2006
    Posts
    11

    Draw a Dot using C#

    No matter where I looked, there didn't seem to be a command for drawing a simple dot in C#. The best I could come up with is you draw a rectangle which is 1 X 1

    Code:
    /// <Title>Draw a Dot</Title>
    /// <Trademark>Tutorials in plain English by Dillinger</Trademark>
    /// <Copyright>Copyright © 2006 Timothy Lee Heermann</Copyright>
    
    using System;
    using System.Windows.Forms;
    using System.Drawing;
    
    namespace Tutorials.DrawDot
    {
        class MyForm : Form
        {
            // Variable Declarations and such go here
            // n/a
    
            /// <summary>Run MyForm. </summary>
            /// <remarks>We don't actually run our form. Nooooooooo.
            /// We instantiate an instance of MyForm and run that!</remarks>
            static void Main(string[] args)
            {
                Application.Run(new MyForm());
            }
    
            /// <summary> The Constructor for our application. </summary>
            MyForm()
            {
                /// <remarks> Setup various Form window attributes. </remarks>
                BackColor = Color.Black;
                Text = " See Dot";
    
                /// <remarks> Create OnPaint Event Handler: 
                /// fired every time Windows says it's time to repaint the canvas
                /// When Windows says Paint, execute DrawGraphics Method ( see below ) </remarks>
                Paint += new PaintEventHandler(DrawGraphics); 
            }
    
            /// <summary> Update the screen and draw any graphic objects </summary>
            /// <param name="sender"></param> <param name="PaintNow"></param>
            void DrawGraphics(Object sender, PaintEventArgs PaintNow) 
            {
                Rectangle Dot = new Rectangle( 150, 100, 1, 1 ); // Dot (Position X, Position Y, Width, Height)
                SolidBrush WhiteBrush = new SolidBrush(Color.White); // Create a white brush to paint our Dot
                PaintNow.Graphics.FillRectangle(WhiteBrush, Dot); // Divide Pi by 8 slices and serve with ice cream!
            }
        }
    }
    Last edited by Dillinger; March 13th, 2006 at 06:41 PM. Reason: New and unimproved!

  3. #3
    Join Date
    Feb 2006
    Posts
    11

    Draw a Dot using C# simplified

    This example draws a line which is one point long:
    Code:
    /// <Title>Draw a Dot using a very short line</Title>
    /// <Trademark>Tutorials in plain English by Dillinger</Trademark>
    
    using System;
    using System.Windows.Forms;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    
    namespace Tutorials.DrawDotLine
    {
        class MyForm : Form
        {
            // Variable Declarations and such go here
            // n/a
    
            /// <summary>Run MyForm. </summary>
            /// <remarks>We don't actually run our form. Nooooooooo.
            /// We instantiate an instance of MyForm and run that!</remarks>
            static void Main(string[] args)
            {
                Application.Run(new MyForm());
            }
    
            /// <summary> The Constructor for our application. </summary>
            MyForm()
            {
                /// <remarks> Setup various Form window attributes. </remarks>
                BackColor = Color.Black;
                Text = " See Dot";
    
                /// <remarks>Create OnPaint Event Handler: 
                /// fired every time Windows says it's time to repaint the canvas. </remarks>
                Paint += new PaintEventHandler(DrawGraphics); // When Windows says Paint: run DrawGraphics (see below)
            }
    
            /// <summary>Update the screen and draw any graphic objects. </summary>
            /// <remarks>Triggered by the PaintEventHandler.</remarks>
            /// <param name="sender"></param> <param name="PaintNow"></param>
            void DrawGraphics(Object sender, PaintEventArgs PaintNow)
            {
                PaintNow.Graphics.DrawLine(Pens.White, 150, 100, 150.1F, 100);
            }
        }
    }
    Now can somebody show me how to make Dot move?
    Last edited by Dillinger; March 13th, 2006 at 03:34 PM. Reason: Was missing Main from VC# template. Made one page solution

  4. #4
    Join Date
    Feb 2006
    Posts
    11

    Draw a Dot using C# simplified

    We can use the default pen width of 1 to draw a dot
    as long as our rectangle size is no larger that 1
    Code:
    /// <Title>Draw a Dot Simplified</Title>
    /// <Trademark>Tutorials in plain English by Dillinger</Trademark>
    /// <Copyright>Copyright © 2006 Timothy Lee Heermann</Copyright>
    
    using System;
    using System.Windows.Forms;
    using System.Drawing;
    
    namespace Tutorials.SeeDot
    {
        class MyForm : Form
        {
            // Variable Declarations and such go here
            // n/a
    
            /// <summary>Run MyForm. </summary>
            /// <remarks>We don't actually run our form. Nooooooooo.
            /// We instantiate an instance of MyForm and run that!</remarks>
            static void Main(string[] args)
            {
                Application.Run(new MyForm());
            }
    
            /// <summary> The Constructor for our application. </summary>
            MyForm()
            {
                /// <remarks> Setup various Form window attributes. </remarks>
                BackColor = Color.Black;
                Text = " See Dot";
    
                /// <remarks>Create OnPaint Event Handler: 
                /// fired every time Windows says it's time to repaint the canvas. </remarks>
                Paint += new PaintEventHandler(DrawGraphics); // When Windows says Paint: run DrawGraphics (see below)
            }
    
            /// <summary>Update the screen and draw any graphic objects. </summary>
            /// <remarks>Triggered by the PaintEventHandler.</remarks>
            /// <param name="sender"></param> <param name="PaintNow"></param>
            void DrawGraphics(Object sender, PaintEventArgs PaintNow)
            {
                // Draw Rectangle( DefaultPen.Color, Rectangle.Type ( Coords Left, Top, Right, Bottom ))
                PaintNow.Graphics.DrawRectangle(Pens.White, Rectangle.FromLTRB(150, 100, 151, 101));
            }
        }
    }

  5. #5
    Join Date
    Feb 2006
    Posts
    11

    Move Sprite using Arrow Keys in C#

    This is a simple example of Event Based movement.
    The render loop is called only if an Event is triggered, like a key being pressed.
    Otherwise no resources are used
    Code:
    /// <Title>See Dot Move using Arrow Keys</Title>
    /// <remarks>Example demonstrates Event Based movement </remarks>
    /// <Trademark>Tutorials in plain English by Dillinger</Trademark>
    /// <Copyright>Copyright ©  2006 Timothy Lee Heermann</Copyright>
    
    using System;
    using System.Windows.Forms;
    using System.Drawing;
    
    namespace Tutorials.MoveArrowKeys
    {
        class MyForm : Form
        {
            // Variable Declarations and such
            // Note: These positions represent the top, left corner of our "Sprite" rectangle
            int SpriteX = 100; // Starting position in pixels from left of window, to right
    	  // Contrary to High School Geometry, in Windows Forms, Y is DOWN! Don't ask me Y!
            int SpriteY = 70; // From top to bottom??! 
    
            /// <summary>Run MyForm. </summary>
            /// <remarks>We don't actually run our form. Nooooooooo.
            /// We instantiate an instance of MyForm and run that!</remarks>
            static void Main( )
            {
                Application.Run(new MyForm());
            }
    
            /// <summary> The Constructor for our application</summary>
            MyForm()
            {
                //Initial settings for our Form window 
                Size = new Size(360, 300);
                Text = " Press the Arrow Keys";
                BackColor = Color.Black;
                CenterToScreen();
    
                /// <remarks>Turn on double-buffering to eliminate flickering </remarks>
                SetStyle(ControlStyles.UserPaint, true);
                SetStyle(ControlStyles.AllPaintingInWmPaint, true);
                SetStyle(ControlStyles.DoubleBuffer, true);
    
                /// <remarks>Create OnPaint Event Handler: 
                /// fired every time Windows says it's time to repaint the canvas. </remarks>
                Paint += new PaintEventHandler(RenderStuff); // When Windows says jump, RenderStuff
            }
    
            /// <summary> The Main "Loop" of our program </summary>
            /// <remarks>Since this is Event based, the Form Window is only
            /// updated when something happens: like a key being pressed.
            /// Otherwise, no resources are being used</remarks>
            void RenderStuff(Object sender, PaintEventArgs PaintNow)
            {
    		// Create rectangle (start position, and size X & Y)
                Rectangle Dot = new Rectangle(SpriteX, SpriteY, 2, 2); 
    		// Create Brush(Color) to paint rectangle
                SolidBrush whiteBrush = new SolidBrush(Color.White); 
                PaintNow.Graphics.FillRectangle(whiteBrush, Dot);
            }
            /// <summary>Keypress event.</summary>
            protected override void OnKeyDown(KeyEventArgs KeyboardInput)
            {
                switch (KeyboardInput.KeyCode)
                {
                    case Keys.Right: // If Right Arrow key is pressed
                        SpriteX = SpriteX + 2; // Update Sprite postion
    			  // Trigger the Paint event all over again, creating a "render loop"
                        Invalidate();                     
    		    break; // end case statement
    
                    case Keys.Left: // Then clearly this must make guacamole!
                        SpriteX = SpriteX - 2;
                        Invalidate();
                        break;
    
                    case Keys.Up:
                        SpriteY = SpriteY - 2;
                        Invalidate();
                        break;
    
                    case Keys.Down:
                        SpriteY = SpriteY + 2;
                        Invalidate();
                        break;
                }
            }
        }
    } // ... and you can take dot to da bank!
    Last edited by Dillinger; March 13th, 2006 at 06:44 PM. Reason: @%#$&^! Perfectionists!

  6. #6
    Join Date
    Feb 2006
    Posts
    11

    Simple Animation using C#

    This is a very very rudimentary example of animation
    using the C# Timer class to trigger a simple OnPaint render loop
    which moves a dot across the screen
    Code:
    /// <Title>Simple Animation</Title>
    /// <Trademark>Tutorials in plain English by Dillinger</Trademark>
    /// <Copyright>Copyright © 2006 Timothy Lee Heermann</Copyright>
    
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    namespace Tutorials.Animation
    {
        public class MyForm : Form
        {
            // Declare Variables
            int SpriteX, SpriteY; // Sprite position in pixels from Left, Top
            int SpriteWidth = 4, SpriteHeight = 4; // Sprite size
    
            Timer MyTimer; /// <remarks>Create an instance of the Timer class called MyTimer </remarks>
            int TimerDuration = 500; // Set Timer duration (1 second = 1000 milliseconds)
            int SpriteMove = 4;  // Distance to move Sprite every Timer tick
    
            /// <summary>Run MyForm. </summary>
            /// <remarks>We don't actually run our form. Nooooooooo.
            /// We instantiate an instance of MyForm and run that!</remarks>
            static void Main()
            {
                Application.Run(new MyForm());
            }
    
            /// <summary> The Constructor for our application. </summary>
            MyForm()
            {
                // Set the Form window's attributes
                Text = " See Dot Move";
                BackColor = Color.Black;
                CenterToScreen();
    
                SpriteX = 0; // Sprite position starting at the far left of our window
                SpriteY = 100; // Starting from the top down (minus menubar height of approx 38)
    
                MyTimer = new Timer(); // Instatiate instance of MyTimer
                MyTimer.Interval = TimerDuration; // Set the timer duration. 
                MyTimer.Start(); // Obviously this line makes cheese fall from the sky
                // Create Event Handler for Timer Tick. Every time MyTimer Ticks... 
                MyTimer.Tick += new EventHandler(Update); // run the Method called Update (see below)
    
                /// <remarks>Create OnPaint Event Handler: 
                /// fired every time Windows says it's time to repaint the canvas. </remarks>
                Paint += new PaintEventHandler(DrawGraphics); // When Windows says Paint: run DrawGraphics (see below)
            }
    
            void DrawGraphics(Object sender, PaintEventArgs PaintNow)
            {
                Rectangle MySprite = new Rectangle(SpriteX, SpriteY, SpriteWidth, SpriteHeight); // Create rectangle (start position, and size X & Y)
                SolidBrush WhiteBrush = new SolidBrush(Color.White); // Create Brush(Color) to paint rectangle
    
                PaintNow.Graphics.FillRectangle(WhiteBrush, MySprite);
            }
    
            public void Update(object sender, System.EventArgs e) // Every time MyTimer ticks
            {
                SpriteX += SpriteMove; // Update Sprite position
    
                // If Sprite Position = Window width
                if (SpriteX >= (640 - (SpriteWidth * 2))) // Subtract the width of the sprite * 2 so it's not offscreen
                    MyTimer.Stop();
    
                Invalidate(); // Trigger OnPaint again, creating a loop
            }
        }
    } // ... and dat's the name of dat tune!

  7. #7
    Join Date
    Feb 2006
    Posts
    11

    Infinite 2D Screen in C#

    This creates an endless screen.
    When sprite exits on right side of screen,
    it reappears again on the left
    Code:
    /// <Title>Infinite Screen</Title>
    /// <Trademark>Tutorials in plain English by Dillinger</Trademark>
    /// <Copyright>Copyright © 2006 Timothy Lee Heermann</Copyright>
    
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    namespace Tutorials.InfiniteScreen
    {
        public class MyForm : Form
        {
            // Declare Variables
            int SpriteX, SpriteY; // Sprite position in pixels from Left, Top
            int SpriteWidth = 4, SpriteHeight = 4; // Sprite size
    
            int SpriteMove = 4;  // Distance to move Sprite every tick
    
            Timer MyTimer; // Create an instance of the Timer class called MyTimer
    
            /// <summary>Run MyForm. </summary>
            /// <remarks>We don't actually run our form. Nooooooooo.
            /// We instantiate an instance of MyForm and run that!</remarks>
            [STAThread]
            static void Main()
            {
                Application.Run(new MyForm());
            }
    
            /// <summary> The Constructor for our project. </summary>
            public MyForm()
            {
                // Set the Form window's attributes
                Text = " Infinite Screen";
                BackColor = Color.Black;
                CenterToScreen();
    
                MyTimer = new Timer(); // Instantiate instance of MyTimer
                MyTimer.Interval = 20; // Set the timer duration. 1000 milliseconds = 1 second 
                MyTimer.Start(); // Obviously this line makes cheese fall from the sky
                // Create Event Handler for Timer Tick. Every time MyTimer Ticks... 
                MyTimer.Tick += new EventHandler(Update); // run the Method called Update (see below)
    
                SpriteX = 0; // Starting at the far left of our window
                SpriteY = 100 ; // From top to bottom. +Y is Down!
    
                /// <remarks>Create OnPaint Event Handler: 
                /// fired every time Windows says it's time to repaint the canvas.
                /// When Windows says Paint: run DrawGraphics (see below) </remarks>
                Paint += new PaintEventHandler(DrawGraphics); 
            }
    
            /// <summary> Update Sprite position every time MyTimer ticks </summary>
            public void Update(object sender, System.EventArgs e) 
            {
                SpriteX += SpriteMove; /// <remarks>Update Sprite position </remarks>
    
                // If Sprite Position exceeds Window width...
    		// Subtract the width of the sprite * 2 so it's not offscreen
                if (SpriteX >= this.Width) 
                    SpriteX = ( 0 - SpriteWidth) ;
    
                Invalidate(); // Trigger OnPaint again, creating a loop
            }
    
            /// <summary>Update the screen and draw any graphic objects. </summary>
            /// <remarks>Triggered by the PaintEventHandler.</remarks>
            /// <param name="sender"></param> <param name="PaintNow"></param>
            void DrawGraphics(Object sender, PaintEventArgs PaintNow) // When Windows says it's time to redraw the window
            {
                // Create rectangle (start position, and size X & Y)
                Rectangle Dot = new Rectangle(SpriteX, SpriteY, SpriteWidth, SpriteHeight);
                // Create Brush(Color) to paint Dot
                SolidBrush WhiteBrush = new SolidBrush(Color.White); 
    
                PaintNow.Graphics.FillRectangle(WhiteBrush, Dot);
            }
        }
    } // That's all folks!
    Last edited by Dillinger; March 13th, 2006 at 06:00 PM. Reason: misspelt

  8. #8
    Join Date
    Feb 2006
    Posts
    11

    Exit C# Application using Escape Key

    This simple Form window Exits the application when you press the Escape Key
    Code:
    /// <Title>Exit using Escape Key</Title>
    /// <Trademark>Tutorials in plain English by Dillinger</Trademark>
    /// <Copyright>Copyright ©  2006 Timothy Lee Heermann</Copyright>
    
    using System;
    using System.Windows.Forms;
    using System.Drawing;
    
    namespace Tutorials.EscapeExit
    {
        class MyForm : Form
        {
            // Variable Declarations and such go here
            // n/a
    
            /// <summary>Run MyForm. </summary>
            /// <remarks>We don't actually run our form. Nooooooooo.
            /// We instantiate an instance of MyForm and run that!</remarks>
            static void Main( )
            {
                Application.Run(new MyForm());
            }
    
            /// <summary> The Constructor for our application. </summary>
            MyForm()
            {
                /// <remarks> Setup various Form window attributes. </remarks>
                Size = new Size(400, 300);
                Text = " Hit Escape to Exit";
                CenterToScreen();
            }
    
            /// <summary>Get Keyboard Input</summary>
            /// <param name="KeyboardPressed"></param>
            protected override void OnKeyDown(KeyEventArgs KeyboardPressed)
            {
                base.OnKeyDown(KeyboardPressed);
                switch (KeyboardPressed.KeyCode)
                {
                    case Keys.Escape: // If Escape key is pressed...
                        GC.Collect(0); // clean up any unused resources...
                        Environment.Exit(0); // and bail!
                     break; // end case statement
                }
            }
        }
    } // ... and that's all she wrote!
    Last edited by Dillinger; March 13th, 2006 at 05:55 PM. Reason: Nitpickin and a-grinnin

  9. #9
    Join Date
    Feb 2006
    Posts
    11

    Sprite Rebounds Off Screen Edge using C#

    In this simple example the Sprite reverses direction when it hits the edge of the screen
    Code:
    /// <Title>Screen Rebound</Title>
    /// <Trademark>Tutorials in plain English by Dillinger</Trademark>
    /// <Copyright>Copyright ©  2006 Timothy Lee Heermann</Copyright>
    
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    namespace Tutorials.ScreenRebound
    {
        public class MyForm : Form
        {
            // Declare Variables
            int SpriteX, SpriteY; // Sprite position in pixels from Left, Top
            int SpriteWidth = 4, SpriteHeight = 4; // Sprite size
    
            int SpriteMove = 10;  // Distance to move Sprite every tick
    
            bool SpriteReverse = false;
    
            Timer MyTimer; // Create an instance of the Timer class called MyTimer
    
            /// <summary>Run MyForm. </summary>
            /// <remarks>We don't actually run our form. Nooooooooo.
            /// We instantiate an instance of MyForm and run that!</remarks>
            static void Main()
            {
                Application.Run(new MyForm());
            }
    
            /// <summary> The Constructor for our application</summary>
            public MyForm()
            {
                /// <remarks> Setup various Form window attributes. </remarks>
                ClientSize = new System.Drawing.Size(400, 250);
                Text = "  Bouncing off the Walls!";
                BackColor = Color.Black;
                CenterToScreen();
    
                MyTimer = new Timer(); // Instantiate instance of MyTimer
                MyTimer.Interval = 20; // Set the timer duration. 1000 milliseconds = 1 second 
                MyTimer.Start(); // Tell Timer to start timing
                // Create Event Handler for Timer Tick. Every time MyTimer Ticks... 
                MyTimer.Tick += new EventHandler(Update); // run the Method called Update (see below)
    
                SpriteX = 0; // Starting at the far left of our window
                SpriteY = 100; // About halfway down the window (minus menubar height)
    
                /// <remarks>Create OnPaint Event Handler: 
                /// fired every time Windows says it's time to repaint the canvas. 
                /// When Windows says Paint run DrawGraphics method (see below)</remarks>
                Paint += new PaintEventHandler(DrawGraphics);
            }
    
            void DrawGraphics(Object sender, PaintEventArgs PaintNow)
            {
                Rectangle Dot = new Rectangle(SpriteX, SpriteY, SpriteWidth, SpriteHeight); // Create rectangle (start position, and size X & Y)
                SolidBrush WhiteBrush = new SolidBrush(Color.White); // Create Brush(Color) to paint rectangle
    
                PaintNow.Graphics.FillRectangle(WhiteBrush, Dot);
            }
    
            public void Update(object sender, System.EventArgs e) // Every time MyTimer ticks
            {
                if (SpriteReverse == false)
                    SpriteX += SpriteMove; // Update Sprite position Positive X
                if (SpriteReverse == true)
                    SpriteX -= SpriteMove; // Update Sprite position Negative X
    
                // If Sprite Position = Window width
                if (SpriteX >= this.Width - SpriteWidth) // If Sprite reaches this side of screen's Right side
                    SpriteReverse = true; // Reverse Sprite's inner calling
                if (SpriteX <= 0) // If Sprite reaches screen's Left side..
                    SpriteReverse = false; // Obviously this line sends a mild electric shock to the user
    
                Invalidate(); // Trigger Paint Event again, creating a loop
            }
        }
    } // ... and that's how string cheese was invented!

  10. #10
    Join Date
    Feb 2006
    Posts
    11

    Move Sprite using Mouse in C#

    In this example we can update the Sprite's X coordinates using the Mouse
    Code:
    /// <Title>Move Dot using Mouse</Title>
    /// <Trademark>Tutorials in plain English by Dillinger</Trademark>
    /// <Copyright>Copyright ©  2006 Timothy Lee Heermann</Copyright>
    using System;
    using System.Windows.Forms;
    using System.Drawing;
    
    namespace Tutorials.MoveMouseX
    {
        class MyForm : Form
        {
            // Variable Declarations and such
            // These positions represent the Left, Top corner of our "Sprite" rectangle
            int SpriteX = 100; // Starting position in pixels from left of window, to right
            // Contrary to High School Geometry, in Windows Forms, Y is DOWN! Don't ask me Y!
            int SpriteY = 70; // From top to bottom??! 
    
            /// <summary>Run MyForm. </summary>
            /// <remarks>We don't actually run our form. Nooooooooo.
            /// We instantiate an instance of MyForm and run that!</remarks>
            static void Main( )
            {
                Application.Run(new MyForm());
            }
    
            /// <summary> The Constructor for our application</summary>
            MyForm()
            {
                //Initial settings for our Form window 
                Size = new Size(400, 300);
                Text = " Move Mouse Left & Right";
                BackColor = Color.Black;
                CenterToScreen();
    
                /// <remarks>Turn on double-buffering to eliminate flickering </remarks>
                SetStyle(ControlStyles.UserPaint, true);
                SetStyle(ControlStyles.AllPaintingInWmPaint, true);
                SetStyle(ControlStyles.DoubleBuffer, true);
    
                /// <remarks>Create OnPaint Event Handler: 
                /// fired every time Windows says it's time to repaint the Form. </remarks>
                Paint += new PaintEventHandler(RenderStuff);
    
                /// <remarks>Creates a new mouse movement event handler </remarks>
                MouseMove += new MouseEventHandler(MouseMoveUpdate);
            }
    
            /// <summary> The Main "Loop" of our program </summary>
            /// <remarks>Since this is Event based, the Form Window is only
            /// updated when something happens: like a mouse being moved.
            /// Otherwise, no resources are being used</remarks>
            void RenderStuff(Object sender, PaintEventArgs PaintNow)
            {
                Rectangle Dot = new Rectangle(SpriteX, SpriteY, 2, 2); // Create rectangle (start position, and size X & Y)
                SolidBrush WhiteBrush = new SolidBrush(Color.White); // Create Brush(Color) to paint rectangle
    
                PaintNow.Graphics.FillRectangle(WhiteBrush, Dot);
            }
    
            /// <summary> Events to update if the Mouse is moved </summary>
            /// <param name="sender"></param> 
            /// <param name="GetMousePosition">Get's current position of User's Mouse</param>
            void MouseMoveUpdate(object sender, MouseEventArgs GetMousePosition)
            {
                // Move Sprite to Mouse's X coordinate
                SpriteX = GetMousePosition.X; // Set Sprite position to User's current Mouse coords
                Invalidate(); // Trigger the Paint Event and update our Form window
            }
        }
    } // ... and that's the meaning of life, the universe... all that good stuff!

  11. #11
    Join Date
    Feb 2006
    Posts
    11

    You have to answer your own questions around here

    Well, I have managed to get quite a way down my list so far. All on my own and unassisted from anyone. Since this post has been up for months and not a single soul has bothered to offer any help whatsoever, I see no reason to continue wasting my time posting any further on this forum.
    Goodbye and thanks a friggin lot!

  12. #12
    Join Date
    Oct 2005
    Location
    England
    Posts
    803

    Re: You have to answer your own questions around here

    That is good though, the fact that you have managed to solve the problems on your own will have taught you far more than what any help from any member of the forum could offer.
    Rich

    Visual Studio 2010 Professional | Windows 7 (x64)
    Ubuntu

  13. #13
    Join Date
    Apr 2015
    Posts
    1

    Re: You have to answer your own questions around here

    Quote Originally Posted by Rich2189 View Post
    That is good though, the fact that you have managed to solve the problems on your own will have taught you far more than what any help from any member of the forum could offer.
    No, it's not good. Visitors like me would have loved to utilize an anywhere near completed list for reference when trying to solve these exercises. If you don't get any response from other users, you're not benefitting from the fact that you are posting on a forum and hence are looking forward to receive feedback.

    He would have solved some of these exercises regardless of response or not. All that would have changed is the completion of the list and the speed of progress. There's no way he could have learned less from getting one-to-one feedback from other people. That's like saying you don't need teachers because figuring literally everything out on your own is better than receiving feedback and explanations on how to do certain things. Even collaborating on certain tasks is commonly deemed more efficient than completely autodidact learning.

    In any case, if he would have benefitted from it or not, you post to a forum in the hope of getting any form of response. If anyone would have come along and thought that it's better to work in complete isolation on this list instead of either getting help or collaborating, the least one could have done is say so.

    I'll be looking forward to utilizing DillingerLee's many tutorials in JavaScript to some day create my own independent collection of tutorials. My thanks to DillingerLee, and thanks to all others who helped him (which sadly does not include anyone on this forum).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured