Share via


Step 4: Add a Method to Restart the Game

You've seen how the IDE can add an event handler method to your program automatically. You can also write methods and add them to your code. Many programmers spend much of their time adding their own methods.

Note

Writing your own methods is useful when there is a set of statements that need to be executed many times, in different places. This occurs frequently when you write programs.

For example, in creating this maze program, when the program starts, you want it to automatically reposition the mouse pointer in the upper-left corner of the panel. When the user moves the pointer into a wall, you want it to reposition the pointer at the start. When the user moves the pointer out of the playing field and back in again, you want it to reposition the pointer at the start again.

You can reposition the pointer over the starting point using three lines of code. But it saves time if you don't have to write those same three lines of code in several different places in your program. If you place those three lines of code in a method, for example, a method called MoveToStart(), you only have to write them once. Then you just call the MoveToStart() method any time you want to move the pointer back to the upper-left corner of the panel.

link to videoFor a video version of this topic, see Tutorial 2: Create a Maze in Visual Basic - Video 2 or Tutorial 2: Create a Maze in C# - Video 2.

To add a method to restart the game

  1. Go to the code for the form by right-clicking Form1.cs in Solution Explorer and selecting View Code from the menu.

  2. You should see the finishLabel_MouseEnter() method that you added. Just below that method, add a new MoveToStart() method.

    Private Sub MoveToStart()
        Dim startingPoint = Panel1.Location
        startingPoint.Offset(10, 10)
        Cursor.Position = PointToScreen(startingPoint)
    End Sub
    
    private void MoveToStart()
    {
        Point startingPoint = panel1.Location;
        startingPoint.Offset(10, 10);
        Cursor.Position = PointToScreen(startingPoint);
    }
    
  3. There's a special type of comment that you can add above any method, and the IDE can help you add it. Put your cursor on the line above the new method. In Visual C#, add three slash marks (///). In Visual Basic, add three single quotation marks ('''). The IDE automatically fills in the following text.

    ''' <summary> 
    '''  
    ''' </summary> 
    ''' <remarks></remarks> 
    Private Sub MoveToStart()
        Dim startingPoint = Panel1.Location
        startingPoint.Offset(10, 10)
        Cursor.Position = PointToScreen(startingPoint)
    End Sub
    
    /// <summary> 
    ///  
    /// </summary> 
    private void MoveToStart()
    {
        Point startingPoint = panel1.Location;
        startingPoint.Offset(10, 10);
        Cursor.Position = PointToScreen(startingPoint);
    }
    
  4. On the line between the two summary tags, fill in the following comment. (After you press ENTER, the IDE automatically adds a new line with either three slash marks (///) or three single quotation marks ('''), depending on your programming language, so you can continue your comment.)

    ''' <summary> 
    ''' Move the pointer to a point 10 pixels down and to the right 
    ''' of the starting point in the upper-left corner of the maze. 
    ''' </summary>
    
    /// <summary> 
    /// Move the pointer to a point 10 pixels down and to the right 
    /// of the starting point in the upper-left corner of the maze. 
    /// </summary> 
    

    Note

    You just added an XML comment. As you may remember, the IDE showed you information in a tooltip when you paused above the word MessageBox. The IDE fills in tooltips for your methods automatically. Anything you put into an XML comment appears in the IDE's tooltip, as well as in the IntelliSense window. With a program with many methods, that can be useful. Also, if you put a wall that's 10 pixels down and to the right of the upper-left corner of the panel, you can change (10, 10) in the code. Experiment with different numbers until you find a pointer starting point that works for your maze.

  5. After you add your method, you need to call it. Because you want your program to move the pointer over the starting point as soon as the program starts, you should call the method as soon as the form starts. For Visual C#, look for the following method in your form's code.

    public Form1()
    {
        InitializeComponent();
    }
    

    For Visual Basic, add this method in your form's code. Before the finishLabel_MouseEnter method, start typing the following code.

    Public Sub New()
    

    When you press the ENTER key to move to the next line, IntelliSense should make the following code appear to complete the method.

    Public Sub New()
        ' This call is required by Windows Forms Designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call. 
    End Sub
    

    This is a special method called the constructor. It gets executed once, when your form is created. Right now, all it does is call a method called InitializeComponent(). You will add a line to it to call the new MoveToStart() method that you just wrote. Before you continue, consider what to add to your program to get it to call the MoveToStart() method immediately after it calls the InitializeComponent() method.

    Note

       The InitializeComponent() method in your form's constructor is a method that the IDE wrote. It adds all of the controls and components to the form, and sets up their properties. Any time you change any of the properties of your form or its controls, the IDE alters that method. You can look at it by opening the file Form1.Designer.cs from Solution Explorer. You don't need to edit the contents of the InitializeComponent() method. The IDE takes care of this based on the form that you created in the Design view.

  6. Add a call to the MoveToStart() method immediately after it calls the InitializeComponent() method. Your form code should look like the following.

    Public Class Form1
    
        Public Sub New()
            ' This call is required by Windows Forms Designer.
            InitializeComponent()
            ' Add any initialization after the InitializeComponent() call.
            MoveToStart()
        End Sub 
    
        Private Sub finishLabel_MouseEnter() Handles finishLabel.MouseEnter
            ' Show a congratulatory MessageBox, then close the form.
            MessageBox.Show("Congratulations!")
            Close()
        End Sub 
    
        ''' <summary> 
        ''' Move the mouse pointer to a point 10 pixels down and to the right 
        ''' of the starting point in the upper-left corner of the maze. 
        ''' </summary> 
        ''' <remarks></remarks> 
        Private Sub MoveToStart()
            Dim startingPoint = Panel1.Location
            startingPoint.Offset(10, 10)
            Cursor.Position = PointToScreen(startingPoint)
        End Sub 
    
    End Class
    
    namespace Maze
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                MoveToStart();
            }
    
            private void finishLabel_MouseEnter(object sender, EventArgs e)
            {
                // Show a congratulatory MessageBox, then close the form.
                MessageBox.Show("Congratulations!");
                Close();
            }
    
            /// <summary> 
            /// Move the pointer to a point 10 pixels down and to the right 
            /// of the starting point in the upper-left corner of the maze. 
            /// </summary> 
            private void MoveToStart()
            {
                Point startingPoint = panel1.Location;
                startingPoint.Offset(10, 10);
                Cursor.Position = PointToScreen(startingPoint);
            }
        }
    }
    

    Note the call to the MoveToStart() method underneath InitializeComponent(). If you're programming in Visual C#, remember to end that line with a semicolon (;), or your program won't build.

  7. Now save your program and run it. As soon as the program starts, your pointer should automatically be repositioned slightly down and to the right of the upper-left corner of the panel.

To continue or review