Looping back to start - c#

I am building this program for my CIT class and want to have it loopback and create a new number when the number is guessed correctly. I read over the section in my textbook that covers this but I am a little confused as to how to add this and where exactly.
Here is the code I have now:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Guess_My_Number
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int number;
private void Form1_Load(object sender, EventArgs e)
{
// Generate the number.
Random generator = new Random();
number = generator.Next(0, 100);
MessageBox.Show("Can you guess the number I am thinking of
between 1 and 100?");
}
private void guessButton_Click(object sender, EventArgs e)
{
// Get the guess from the textbox.
int guess = Convert.ToInt32(guessTextbox.Text);
// Check if the number is right.
if (guess > number)
{
MessageBox.Show("Too high, try again.");
}
if (guess < number)
{
MessageBox.Show("Too low, try again.");
}
if (guess == number)
{
MessageBox.Show("Congratulations, you guessed my number!");
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Clost the program.
this.Close();
}
}
}

namespace Guess_My_Number
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int number;
Random generator = new Random();
private void Form1_Load(object sender, EventArgs e)
{
GenerateNewNumber();
}
private void GenerateNewNumber()
{
number = generator.Next(0, 100);
MessageBox.Show("Can you guess the number I am thinking of
between 1 and 100?");
}
private void guessButton_Click(object sender, EventArgs e)
{
// Get the guess from the textbox.
int guess = Convert.ToInt32(guessTextbox.Text);
// Check if the number is right.
if (guess > number)
{
MessageBox.Show("Too high, try again.");
}
if (guess < number)
{
MessageBox.Show("Too low, try again.");
}
if (guess == number)
{
MessageBox.Show("Congratulations, you guessed my number!");
GenerateNewNumber();
}
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

Related

C# Button Click and Private Variables

So I'm trying to make a window forms guess the number game, simple but when I click guess no matter what the label goes up by one. I think it may be due to my variables as despite having them global userGuess still comes up as a local variable...`
Commenting out userScore removes the problem, but I still do not understand why the logic is failing
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
namespace Guess_The_Number_Form
{
public partial class Form1 : Form
{
private int userScore;
private int randNum;
private int userGuess;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
txtBoxGuess.Hide()
;
}
private void toolTip1_Popup(object sender, PopupEventArgs e)
{
}
private void btnRandom_Click(object sender, EventArgs e)
{
Random rand = new Random();
int randNum = rand.Next(0, 10);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
userGuess = Convert.ToInt32(txtBoxGuess.Text);
}
private void txtBoxGuess_Enter(object sender, EventArgs e)
{
}
private void btnGuess_Click(object sender, EventArgs e)
{
if (userGuess == randNum)
{
// userScore++;
lbluserScore.Text = userScore.ToString();
lbluserScore.Text = $"{userScore}";
}
else if (userGuess != randNum)
{
userScore--;
lbluserScore.Text = userScore.ToString();
lbluserScore.Text = $"{userScore}";
}
else if (userScore < 0)
{
lbluserScore.Text = Color.Red.ToString();
}
}
}
}
You need to change this:
private void btnRandom_Click(object sender, EventArgs e)
{
Random rand = new Random();
int randNum = rand.Next(0, 10);
}
to
private void btnRandom_Click(object sender, EventArgs e)
{
Random rand = new Random();
randNum = rand.Next(0, 10);
}
That way, you'll set the member variable randNum rather than a local variable randNum. You also want to check that you really are assigning the user-inputted value into userGuess properly. My guess is that it's not, which means you never change the value of either of those variables, and the program thinks the user always guessed the right value.

VS Breaking once list goes past 2(1) rather than cycling back to 0

Trying to cycle through my characters but instead it breaks once I click next at the last character. The response given by visual studio is : ArgumentOutOfRangeException was unhandled and referring to my "playerCharacter pc = player[currentPlayerIndex];"
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;
namespace RPGExample
{
public partial class Form1 : Form
{
private List<PlayerCharacter> player;
int currentPlayerIndex = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// set up an empty list
player = new List<PlayerCharacter>();
// add a couple of players
player.Add(new PlayerCharacter("Attila"));
player.Add(new PlayerCharacter("Boromir"));
// create some weapons (could be in a list too)
Weapon sword = new Weapon("Broadsword",40,5);
Weapon leatherShield = new Weapon("Leather Shield",2,35);
Weapon woodenStaff = new Weapon("Wooden Staff",30,10);
// and some food
Food bread = new Food("Bread", 15);
// because Weapons and food inherit from CollectableObject
// a player can carry either (polymorphism)
// equip the players
player[0].Add(sword);
player[0].Add(leatherShield);
player[1].Add(woodenStaff);
player[1].Add(bread);
// display the player we are viewing
DisplayPlayer(currentPlayerIndex);
}
// display info about a player by calling objects to string function
public void DisplayPlayer(int playerIndex)
{
// we number from 1 for the user
// try removing the brackets around playerIndex + 1 !!!
lblPlayerInfo.Text = "Player " + (playerIndex + 1);
PlayerCharacter pc = player[currentPlayerIndex];
txtPlayers.Text = pc.ToString();
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if (currentPlayerIndex > 0)
{
currentPlayerIndex--;
DisplayPlayer(currentPlayerIndex);
}
}
private void btnNext_Click(object sender, EventArgs e)
{
if (currentPlayerIndex < player.Count)
{
currentPlayerIndex++;
DisplayPlayer(currentPlayerIndex);
}
}
}
}
You should just DisplayPlayer before incremeent/decrement currentPlayerIndex, or replace strict comparison (<) by comparison with equality (<=) :)
private void btnPrevious_Click(object sender, EventArgs e)
{
if (currentPlayerIndex >= 0)
{
currentPlayerIndex--;
DisplayPlayer(currentPlayerIndex);
}
}
private void btnNext_Click(object sender, EventArgs e)
{
if (currentPlayerIndex < player.Count)
{
currentPlayerIndex++;
DisplayPlayer(currentPlayerIndex);
}
}

C# number guessing game

I'm trying to create a simple number guessing game in C#. The program generates a random number when you click the "Generate random number" button. Once you enter your guess in the textbox and click "Guess", the program lets you know if you've guessed right or wrong.
The problem is that I can't pass the randomly generated number to myFunction() so it can validate the user's guess. Here's the code and it's a bit of a mess; and thank you all in advance for your help.
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;
namespace Number_guessing_game
{
public partial class Form1 : Form
{
int montH;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myFunction(int montH);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int montH = rnd.Next(1, 10);
}
void myFunction(int montH)
{
int guess = int.Parse(textBox1.Text);
if (guess == montH)
{
MessageBox.Show("You win!");
}
if (guess != montH)
{
MessageBox.Show("You lose!");
}
}
}
}
The problem is in your button2_Click function. Inside the function after you generate a random number, you are creating a new int and assigning the random number to that, instead of the already declared class-level variable. Change your button2_Click to the following:
private void button2_Click(object sender, EventArgs e)
{
montH = new Random().Next(1,10);
}
Another few things I will mention, because montH is a class-level variable, it is accessible by every function in your class, so you don't need to pass it as a parameter to myFunction(), in fact, button1_Click could validate the result for you:
private void button1_Click(object sender, EventArgs e)
{
if (int.Parse(TextBox1.Text) == montH)
{
MessageBox.Show("You Win!!");
}
else
{
MessageBox.Show("You Lose...");
}
}
Simply define your montH as a class level variable(as you did), then use following code:
int montH;
private void button2_Click(object sender, EventArgs e)
{
Random rnd = new Random();
montH = rnd.Next(1, 10); //<--- there is no need to redefine montH by int monthH
}
private void GussButton_Click(object sender, EventArgs e)
{
myFunction(month);
}
If in your button2_click event handler want to use it there isn't need to redefine it by int montH;,
because int montH; cause define a new montH variable in method level.
Change your code to:
private void button2_Click(object sender, EventArgs e)
{
Random rnd = new Random();
montH = rnd.Next(1, 10);
}
Try this below:
namespace Number_guessing_game
{
public partial class Form1 : Form
{
public int montH;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myFunction(montH);
}
private void Form1_Load(object sender, EventArgs e)
{
montH=0;
}
private void button2_Click(object sender, EventArgs e)
{
Random rnd = new Random();
montH = rnd.Next(1, 10);
}
void myFunction(montH)
{
int guess = int.Parse(textBox1.Text);
if (guess == montH)
{
MessageBox.Show("You win!");
}
if (guess != montH)
{
MessageBox.Show("You lose!");
}
}
}
}
Don't create a new montH in button2_Click()... otherwise the new montH only alive in this function
private void button2_Click(object sender, EventArgs e)
{
Random rnd = new Random();
montH = rnd.Next(1, 10);
}
I hope the below works for you ! What you dont need to do is actually put your montH in your Function itself since it is a seen variable to the class. When you are comparing the guess ==montH it is already taking the montH int assigned and checking from your montH variable.
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;
namespace Number_guessing_game
{
public partial class Form1 : Form
{
int montH;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myFunction();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int montH = rnd.Next(1, 10);
}
void myFunction()
{
int guess = int.Parse(textBox1.Text);
if (guess == montH)
{
MessageBox.Show("You win!");
}
if (guess != montH)
{
MessageBox.Show("You lose!");
}
}
}
}

send datagridview item to another form

hey i wrote below code to send my datagridview value seleted row to another form but i got this error my event is double content click and i dont know why this happened
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
using System.Windows.Forms;
namespace WindowsFormsApplication12
{
public partial class Form5 : Form
{
public Form5()
{
InitializeComponent();
}
private void Form5_Load(object sender, EventArgs e)
{
tblClassTableAdapter.Fill(dataSet1.tblClass);
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.tblClassTableAdapter.FillBy1(this.dataSet1.tblClass, textBox1.Text);
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
new Form6(int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString())).Show();
}
}
and my form 6
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;
namespace WindowsFormsApplication12
{
public partial class Form6 : Form
{
int classid;
private string p;
public Form6(int myid)
{
classid = myid;
InitializeComponent();
}
public Form6(string p)
{
// TODO: Complete member initialization
this.p = p;
}
public void Form6_Load(object sender, EventArgs e)
{
textBox1.Text = classid.ToString();
}
public DataGridViewRow dataGridViewRow { get; set; }
}
}
thank you guys for helping
DataGridViewCellEventArgs has two important args for you:
e.rowIndex, e.columnIndex which specifying in which cell you pressed.
By the way, you are trying to parse Int from cell, surround it with try/catch for case the parse fails.
try this code instead:
try {
if (e.ColumnIndex > -1 && e.RowIndex > -1)
new Form6(int.Parse(dataGridView1[e.ColumnIndex,e.RowIndex].Value.ToString())).Show();
}
catch (Exception ex) {
MessageBox.Show("Error: " + ex.Message);
}
I think it should help you, mark as answered if yes.

adding a counter class to winform

I have a project that wants
A method that returns the current count.
A Constructor that sets the count to zero.
I have the first few down but need help with the return count to 0 and then the constructor. I need to do this by adding a counter class but I'm confused about the way to add it.
Can some one help me out?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project10TC
{
public partial class Form1 : Form
{
int zero = 0;
int i = 1;
public Form1()
{
InitializeComponent();
}
private EventHandler myCounter;
// end of Form class
private class myCounter()
{
myCounter = new myCounter( );
}
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Teancum Clark\nCS 1400\n Project 10");
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = (++i).ToString();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = (--i).ToString();
}
private void button3_Click(object sender, EventArgs e)
{
textBox1.Text = (zero).ToString();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
public class Counter
{
public int Value { get; private set; }
public void Increment()
{
Value = Value + 1;
}
public void Decrement()
{
if (Value > 0) Value = Value - 1;
}
public Counter()
{
Value = 0;
}
}

Categories

Resources