C Sharp:Guess The Number In WinForms And C Sharp
From GDWiki
Contents |
[edit] Guess the Number: An introduction to C-Sharp and WinForms
This article is here to help you get a grasp on very basic priciples of C Sharp. In it I will walk you through the creation of a very simple Guess the Number game, often prescribed as one of the first applications a programmer should write when beginning.
[edit] Set-Up
To start with, you will need an IDE, in this tutorial I myself will be using Microsoft Visual C-Sharp 2005. This will be all you need so get that installed and we'll move on to the next section.
[edit] Creating a New Project
With C-Sharp 2005 installed, open it up. In the upper middle left of the screen you should see an option to create a new project. Do this and a pop-up will appear. In the pop-up, click on Windows Application and name your project then click create.
[edit] Creating the Base
When the project is created, a form should show up inside of VCS that is blank. If you do not have the toolbar on the side of your workspace then click on view and then toolbar before making sure the map pin icon in the upper left corner of it is horizontal. From this toolbar drag and drop two text boxes into the form. After this, drag two buttons and put them under one of the text boxes. Change the text on button2 to Generate and on button1 to Guess. Now double click on Generate in the form to open up a code window. In this window, add this code(exclude the stock parts):
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Guess_the_number { public partial class Form1 : Form { public int answer; public int guess; public Random rand = new Random(); public Form1() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { textBox2.Text = null; textBox1.Text = null; answer = rand.Next(1, 11); } private void button1_Click(object sender, EventArgs e) { if (textBox2.Text != null) { if (textBox2.Text.ToString() == answer.ToString()) { textBox1.Text = "Congratulations"; textBox2.Text = "Hit generate to reset"; } else { textBox1.Text = "Try again"; textBox2.Text = null; } } } } }
Run this program and you will get a very simple, non-buggy Guess the Number Game
[edit] Further Challenges
- Try making the game work with user-inputted numbers(HINT: You will need two more text boxes and a slight change to the answer random number code)
- Try only giving the user a limited amount of chances before failure

