I have made a voice recognition program in C#. It was all working fine and then randomly stopped working. Now it doesn't respond to any input or say the first output s.Speak("hello, how may i assist you?"); when it's started like it's supposed to.
I have ran the program on my friend's Windows 10 system and it runs fine. This leads me to believe that it's a problem with my system. I am using Windows 7 by the way.
Heres the code -
using System;
using System.Windows.Forms;
using System.Speech.Synthesis;
using System.Speech.Recognition;
using System.Diagnostics;
using System.Xml;
using System.Media;
namespace JarvisTest
{
public partial class Form1 : Form
{
SpeechSynthesizer s = new SpeechSynthesizer();
Boolean wake = false;
String name = "Rhys";
String temp;
String condition;
String high;
String low;
Choices list = new Choices();
public Form1()
{
SpeechRecognitionEngine rec = new SpeechRecognitionEngine();
list.Add(new String[] { "hello", "bye", "how are you", "great", "what time is it", "whats the date", "open google", "open youtube", "wake", "sleep", "restart", "update", "whats the weather", "whats the temperature", "jarvis", "shut down", "exit", "play", "pause", "spotify", "last track", "next track", "whats todays high", "whats todays low", "whats todays weather", "whats your favorite song", "never mind", "whats my name", "minimise", "maximise"});
Grammar gr = new Grammar(new GrammarBuilder(list));
try
{
rec.RequestRecognizerUpdate();
rec.LoadGrammar(gr);
rec.SpeechRecognized += rec_SpeachRecognized;
rec.SetInputToDefaultAudioDevice();
rec.RecognizeAsync(RecognizeMode.Multiple);
}
catch { return; }
s.SelectVoiceByHints(VoiceGender.Male);
s.Speak("hello, how may i assist you?");
InitializeComponent();
}
public String GetWeather(String input)
{
String query = String.Format("https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=' Guernsey')&format=xml&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
XmlDocument wData = new XmlDocument();
try
{
wData.Load(query);
}
catch
{
//MessageBox.Show("No internet connection");
return "No internet connection detected";
}
XmlNamespaceManager manager = new XmlNamespaceManager(wData.NameTable);
manager.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
XmlNode channel = wData.SelectSingleNode("query").SelectSingleNode("results").SelectSingleNode("channel");
XmlNodeList nodes = wData.SelectNodes("query/results/channel");
try
{
int rawtemp = int.Parse(channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["temp"].Value);
int rawhigh = int.Parse(channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", manager).Attributes["high"].Value);
int rawlow = int.Parse(channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", manager).Attributes["low"].Value);
temp = (rawtemp - 32) * 5/9 + "";
high = (rawhigh - 32) * 5 / 9 + "";
low = (rawlow - 32) * 5 / 9 + "";
condition = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["text"].Value;
if (input == "temp")
{
return temp;
}
if (input == "high")
{
return high;
}
if (input == "low")
{
return low;
}
if (input == "cond")
{
return condition;
}
}
catch
{
return "Error Reciving data";
}
return "error";
}
public void restart()
{
Process.Start(#"C:\Users\Rhys-Le-P\Documents\Visual Studio 2017\Projects\JarvisTest\JarvisTest\obj\Debug\JarvisTest.exe");
Environment.Exit(1);
}
public void shutdown()
{
Environment.Exit(1);
}
public void say(String h)
{
s.Speak(h);
wake = false;
}
String[] greetings = new String[3] { "hi", "hello", "hi, how are you" };
public String greetings_action()
{
Random r = new Random();
return greetings[r.Next(3)];
}
//Commands
private void rec_SpeachRecognized(object sender, SpeechRecognizedEventArgs e)
{
String r = e.Result.Text;
if (r == "jarvis")
{
wake = true;
//say(greetings_action());
SoundPlayer simpleSound = new SoundPlayer(#"C:\Users\Rhys-Le-P\Downloads\Beep.wav");
simpleSound.Play();
}
// if (r == "wake")
// {
// wake = true;
// say("i am awake");
// }
//if (r == "sleep")
//{
// wake = false;
// say("zzz");
// }
if (wake == true)
{
if (r == "minimise")
{
this.WindowState = FormWindowState.Minimized;
}
if (r == "maximise")
{
this.WindowState = FormWindowState.Maximized;
}
if (r == "whats my name")
{
say("your name is " + name);
}
if (r == "next track")
{
SendKeys.Send("^{RIGHT}");
//say("playing next track");
}
if(r == "last track")
{
SendKeys.Send("^{LEFT}");
//say("playing last track");
}
if(r == "spotify")
{
Process.Start(#"C:\Users\Rhys-Le-P\AppData\Roaming\Spotify\Spotify.exe");
}
//{
// input
if (r == "play" || r == "pause")
{
SendKeys.Send(" ");
}
// input
if (r == "hello")
{
//output
say("hi");
}
// input
if (r == "how are you")
{
//output
say("good, and you?");
}
// input
if (r == "bye")
{
//output
say("good bye!");
}
// input
if (r == "great")
{
//output
say("good to hear!");
}
// input
if (r == "what time is it")
{
//output
say(DateTime.Now.ToString("h:mm tt"));
}
// input
if (r == "whats the date")
{
//output
say(DateTime.Now.ToString("d/M/yyyy"));
}
// input
if (r == "open google")
{
//output
say("opening google");
Process.Start("http://www.google.com");
}
// input
if (r == "open youtube")
{
//output
say("opening youtube");
Process.Start("http://www.youtube.com");
}
// input
if (r == "restart" || r == "update")
{
//output
say("restarting");
restart();
}
if (r == "whats todays weather")
{
say("Todays weather is, " + GetWeather("cond") + "with a high of" + GetWeather("high") + "degrees and a low of" + GetWeather("low") +"degrees");
}
if (r == "whats the weather")
{
say("The sky is, " + GetWeather("cond") + ".");
}
if (r == "whats the temperature")
{
say("it is, " + GetWeather("temp") + "degrees.");
}
if (r == "whats todays high")
{
say("Todays high is, " + GetWeather("high") + "degrees.");
}
if (r == "whats todays low")
{
say("Todays low is, " + GetWeather("low") + "degrees.");
}
// input
if (r == "shut down" || r == "exit")
{
//output
say("Shutting Down System");
shutdown();
}
if (r == "whats your favorite song")
{
say("I love this song!");
SoundPlayer simpleSound = new SoundPlayer(#"C:\Users\Rhys- Le-P\Downloads\BSIM.wav");
simpleSound.Play();
}
if (r == "never mind")
{
say("Ok sir");
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Any help is greatly appreciated! :)
Related
I know I sound like a bad programmer right now - but I'm new and I can't figure out how to use this reference thing and pass parameters, I mean I know how to do it - but at the same time - this isn't working and I don't know why.
static void Main(string[] args) {
DealCard(ref card);
Console.WriteLine();
Console.ReadLine();
}
private static void DealCard(string card) {
string finalNum = "";
string finalSuite = "";
bool diffCard = false;
do {
Random cardPicker = new Random();
int cardSuite = cardPicker.Next(1, 5);
if (cardSuite == 1) {
finalSuite = "Hearts";
} else if (cardSuite == 2) {
finalSuite = "Spades";
} else if (cardSuite == 3) {
finalSuite = "Clubs";
} else if (cardSuite == 4) {
finalSuite = "Diamonds";
}
int cardNum = cardPicker.Next(1, 14);
if (cardNum == 1) {
finalNum = "Ace";
} else if (cardNum == 2) {
finalNum = "Two";
} else if (cardNum == 3) {
finalNum = "Thre";
} else if (cardNum == 4) {
finalNum = "Four";
} else if (cardNum == 5) {
finalNum = "Five";
} else if (cardNum == 6) {
finalNum = "Six";
} else if (cardNum == 7) {
finalNum = "Seven";
} else if (cardNum == 8) {
finalNum = "Eight";
} else if (cardNum == 9) {
finalNum = "Nine";
} else if (cardNum == 10) {
finalNum = "Ten";
} else if (cardNum == 11) {
finalNum = "Jack";
} else if (cardNum == 12) {
finalNum = "Queen";
} else if (cardNum == 13) {
finalNum = "King";
}
string newCard = finalNum + " of " + finalSuite;
if (newCard != card) {
card = finalNum + " of " + finalSuite;
diffCard = true;
} else {
}
card = newCard;
} while (diffCard == false);
}
Yes I know that massive 'if' is an eyesore.
Yes I know I could accomplish this in less than half the lines.
Yes I know it's a simple question.
Yes I know I'm bad, but I'd like to humbly request that anyone helps me to stop losing hair over this.
You have to declare your method like this:
private static void DealCard(ref string card)
Basically the method has to accept a ref parameter.
Here is documentation to support the answer:
Value Type Parameters
Reference Type Parameters
Your code can be like this
public class Program
{
public static void Main(string[] args) {
string card = "";
DealCard(ref card);
}
private static void DealCard(ref string card)
{
string finalNum = "";
string finalSuite = "";
bool diffCard = false;
do {
Random cardPicker = new Random();
int cardSuite = cardPicker.Next(1, 5);
string[] suite = new String[]{"Hearts","Spades", "Clubs", "Diaminds"};
int cardNum = cardPicker.Next(1, 3);
string[] numbers = new String[]{"one","two","three", "four"};
string newCard = numbers[cardNum] + " of " + suite[cardSuite];
if (newCard != card) {
card = finalNum + " of " + finalSuite;
diffCard = true;
} else {
}
card = newCard;
Console.WriteLine(newCard);
} while (diffCard == false);
}
}
I'm making a hot-potato game in C#. In the code I was trying to handle an exception in the Game() method where it will prompt you to pass the potato to someone (by their player number) it would prevent you from entering your own player number (trying to pass it to yourself.)
The only thing is, I'm having trouble trying to handle the exception:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HotPotatoe
{
class Program
{
public static void Main()
{
Console.Clear();
Console.Write("How many players are there? (up to 4): ");
string PlayerCount = Console.ReadLine();
string PlayerOne = null;
string PlayerTwo = null;
string PlayerThree = null;
string PlayerFour = null;
if (PlayerCount == "2")
{
Console.Write("Enter player 1's name: ");
PlayerOne = Console.ReadLine();
Console.Write("Enter player 2's name: ");
PlayerTwo = Console.ReadLine();
Random ran = new Random();
int WhoStarts = ran.Next(1, 2);
Game(PlayerOne, PlayerTwo, PlayerThree, PlayerFour, WhoStarts);
}
else if (PlayerCount == "3")
{
Console.Write("Enter player 1's name: ");
PlayerOne = Console.ReadLine();
Console.Write("Enter player 2's name: ");
PlayerTwo = Console.ReadLine();
Console.Write("Enter player 3's name: ");
PlayerThree = Console.ReadLine();
Random ran = new Random();
int WhoStarts = ran.Next(1, 3);
Game(PlayerOne, PlayerTwo, PlayerThree, PlayerFour, WhoStarts);
}
else if (PlayerCount == "4")
{
Console.Write("Enter player 1's name: ");
PlayerOne = Console.ReadLine();
Console.Write("Enter player 2's name: ");
PlayerTwo = Console.ReadLine();
Console.Write("Enter player 3's name: ");
PlayerThree = Console.ReadLine();
Console.Write("Enter player 4's name: ");
PlayerFour = Console.ReadLine();
Random ran = new Random();
int WhoStarts = ran.Next(1, 4);
Game(PlayerOne,
PlayerTwo,
PlayerThree,
PlayerFour,
WhoStarts);
}
else
{
Console.WriteLine("Not valid!");
Console.ReadKey();
Main();
}
}
private static void Game
(string player1,
string player2,
string player3,
string player4,
int whoStarts)
{
Player Player1 = new Player();
Player Player2 = new Player();
Player Player3 = new Player();
Player Player4 = new Player();
Player1.Name = player1;
Player2.Name = player2;
Player3.Name = player3;
Player4.Name = player4;
Player1.Number = 1;
Player2.Number = 2;
Player3.Number = 3;
Player4.Number = 4;
Player1.IsOut = false;
Player2.IsOut = false;
if(Player3.Name == null)
{
Player3.IsOut = true;
}
else
{
Player3.IsOut = false;
}
if (Player4.Name == null)
{
Player4.IsOut = true;
}
else
{
Player3.IsOut = false;
}
switch (whoStarts)
{
case 1:
Player1.HasPotatoe = true;
break;
case 2:
Player2.HasPotatoe = true;
break;
case 3:
Player3.HasPotatoe = true;
break;
default:
Player4.HasPotatoe = true;
break;
}
List<Player> PlayingList = new List<Player>
{
Player1,
Player2
};
if (Player3.IsOut == false)
{
PlayingList.Add(Player3);
}
if (Player4.IsOut == false)
{
PlayingList.Add(Player4);
}
Random rand = new Random();
int NumOfRounds = rand.Next(1, 10);
do
{
foreach (Player p in PlayingList)
{
if (p.HasPotatoe == true)
{
Console.Write("Player {0} has the potatoe! Who do you want to pass it to? (by number): ", p.Number);
string input = Console.ReadLine();
if (input == "1")
{
PlayingList[0].HasPotatoe = true;
NumOfRounds--;
}
else if (input == "2")
{
PlayingList[1].HasPotatoe = true;
NumOfRounds--;
}
else if (input == "3")
{
if (Player3.IsOut == true)
{
Console.WriteLine("That person isn't playing! Choose another player!");
Console.ReadKey();
}
else
{
PlayingList[2].HasPotatoe = true;
NumOfRounds--;
}
}
else if (input == "4")
{
if (Player4.IsOut == true)
{
Console.WriteLine("That person isn't playing! Choose another player!");
Console.ReadKey();
}
else
{
PlayingList[3].HasPotatoe = true;
NumOfRounds--;
}
}
else if(input == p.Number.ToString()) // this is the part i'm having trouble with................................
{
Console.WriteLine("{0}", p.Number.ToString());
Console.WriteLine("You can't pass it to yourself! -_- Choose someone else..." + p.Number.ToString());
Console.ReadKey();
}
}
}
} while (NumOfRounds != 0);
if(Player1.HasPotatoe == true)
{
Console.WriteLine("{0} is out! Play again!", Player1.Name);
Console.ReadKey();
Main();
}
else if(Player2.HasPotatoe == true)
{
Console.WriteLine("{0} is out! Play again!", Player2.Name);
Console.ReadKey();
Main();
}
else if (Player3.HasPotatoe == true)
{
Console.WriteLine("{0} is out! Play again!", Player3.Name);
Console.ReadKey();
Main();
}
else if (Player4.HasPotatoe == true)
{
Console.WriteLine("{0} is out! Play again!", Player4.Name);
Console.ReadKey();
Main();
}
}
}
class Player
{
public string Name { get; set; }
public int Number { get; set; }
public bool HasPotatoe { get; set; }
public bool IsOut { get; set; }
}
}
The specific part where the error is:
Random rand = new Random();
int NumOfRounds = rand.Next(1, 10);
do
{
foreach (Player p in PlayingList)
{
if (p.HasPotatoe == true)
{
Console.Write("Player {0} has the potatoe! Who do you want to pass it to? (by number): ", p.Number);
string input = Console.ReadLine();
if (input == "1")
{
PlayingList[0].HasPotatoe = true;
NumOfRounds--;
}
else if (input == "2")
{
PlayingList[1].HasPotatoe = true;
NumOfRounds--;
}
else if (input == "3")
{
if (Player3.IsOut == true)
{
Console.WriteLine("That person isn't playing! Choose another player!");
Console.ReadKey();
}
else
{
PlayingList[2].HasPotatoe = true;
NumOfRounds--;
}
}
else if (input == "4")
{
if (Player4.IsOut == true)
{
Console.WriteLine("That person isn't playing! Choose another player!");
Console.ReadKey();
}
else
{
PlayingList[3].HasPotatoe = true;
NumOfRounds--;
}
}
else if(input == p.Number.ToString()) // this is where the problem is...
{
Console.WriteLine("{0}", p.Number.ToString());
Console.WriteLine("You can't pass it to yourself! -_- Choose someone else..." + p.Number.ToString());
Console.ReadKey();
}
}
}
} while (NumOfRounds != 0);
so basically I say: if(input == p.Number().ToString()) // p.Number() == player's number
then throw the exception. But i'm not sure how to go about that. I've tried converting the integer to a string with the .ToString() method. but it doesn't seem to change anything. I've also tried turning the input into a 32 bit integer with the Int32.Parse(input) method, but still no luck. The result just does something random. For example if I was player two, and I prompt to pass the potato to player two, then it will just write to the console that player 2 has the potato over and over. I'm not sure how to do this right. Any suggestions?
throw an exception is simple.
else if(input == p.Number.ToString())
throw new Exception("You cant do that");
Maybe your issue is creating your own exceptions to catch them later. Do
public class BadPlayerException: Exception
{
}
...
throw new BadPlayerEcxeption():
I'm currently coding a grades calculator that adds 3 test scores and gives you a letter grade depending on the average. So far I have been able to code everything without any issues except for one thing. In this calculator I added a checkbox that drops the lowest grade and averages out the highest 2 if checked. I just started programming a few weeks ago and have no idea how begin coding this. Should I use an if statement or a loop? If you guys have any tips on eliminating unnecessary code or anything else, feel free to point it out.
public frmGradeCalculator()
{
InitializeComponent();
}
private void chkDropLowest_CheckedChanged(object sender, EventArgs e)
{
}
private void btnClear_Click(object sender, EventArgs e)
{
// Clear Text
txtTest1.Clear();
txtTest2.Clear();
txtTest3.Clear();
txtAverage.Clear();
txtLetterGrade.Clear();
// Set Focus
txtTest1.Focus();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
// Declare variables
byte bytTest1;
byte bytTest2;
byte bytTest3;
float fltAverage;
string strLetterGrade = "F";
// Convert to text
if (byte.TryParse(txtTest1.Text, out bytTest1))
{
}
else
{
MessageBox.Show("Invalid Number!",
"Yancarlos Grade Calculator",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtTest1.Focus();
return;
}
if (byte.TryParse(txtTest2.Text, out bytTest2))
{
}
else
{
MessageBox.Show("Invalid Number!",
"Yancarlos Grade Calculator",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtTest2.Focus();
return;
}
if (byte.TryParse(txtTest3.Text, out bytTest3))
{
}
else
{
MessageBox.Show("Invalid Number!",
"Yancarlos Grade Calculator",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtTest3.Focus();
return;
}
// Formula
fltAverage = (bytTest1 + bytTest2 + bytTest3) / 3;
if (fltAverage <= 59.9)
{
strLetterGrade = "F";
}
else if (fltAverage <= 63.9)
{
strLetterGrade = "D-";
}
else if (fltAverage <= 66.9)
{
strLetterGrade = "D";
}
else if (fltAverage <= 69.9)
{
strLetterGrade = "D+";
}
else if (fltAverage <= 73.9)
{
strLetterGrade = "C-";
}
else if (fltAverage <= 76.9)
{
strLetterGrade = "C";
}
else if (fltAverage <= 79.9)
{
strLetterGrade = "C+";
}
else if (fltAverage <= 83.9)
{
strLetterGrade = "B-";
}
else if (fltAverage <= 86.9)
{
strLetterGrade = "B";
}
else if (fltAverage <= 89.9)
{
strLetterGrade = "B+";
}
else if (fltAverage <= 93.9)
{
strLetterGrade = "A-";
}
else if (fltAverage <= 96.9)
{
strLetterGrade = "A";
}
else
{
strLetterGrade = "A+";
}
// convert back to user
txtAverage.Text = fltAverage.ToString("f1");
txtLetterGrade.Text = strLetterGrade.ToString();
}
private void btnExit_Click(object sender, EventArgs e)
{
// Exit application
Application.Exit();
}
private void frmGradeCalculator_Load(object sender, EventArgs e)
{
}
}
}
To answer your specific question on whether to use a loop or an if statement, all checkbox controls have a Checked property that you can check.
if(chkDropLowest.Checked)
{
//Calculate average without the lowest test
}
As far as design goes, I would recommend that you not assign so much functionality to a specific button. I would instead create a new method to call from that button (that way you are safe if you ever decide to use a new control in the future)
Example:
private string CalculateLetterGrade(byte test1, byte test2, byte test3)
{
string letterGrade;
if(chkDropLowest.Checked)
{
//Drop lowest test then calculate average
}
else
{
//Use all tests then calculate average
}
//Determine the string for the letter grade, then return it
return letterGrade;
}
You seem to have the average logic worked out so I'll leave that to you.
Give this a shot when you go to calculate the average:
double totalScore = bytTest1 + bytTest2 + bytTest3;
double lowest = Math.Min(Math.Min(bytTest1, bytTest2), bytTest3);
if (chkDropLowest.IsChecked == true)
{
// Drop the lowest test
fltAverage = (totalScore - lowest) / 2;
}
else
{
// Include all three tests
fltAverage = (totalScore) / 3;
}
Just a little bit for interest sake I've refactored your btnCalculate_Click. This solves your problem, but I've posted it more so that you can have a look at code that more tersely solves your problem and maybe give you some syntax to look at.
private void btnCalculate_Click(object sender, EventArgs e)
{
Func<TextBox, double?> parseTextBox = tb =>
{
double value;
if (!double.TryParse(tb.Text, out value))
{
MessageBox.Show("Invalid Number!",
"Yancarlos Grade Calculator",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
tb.Focus();
return null;
}
return value;
};
double?[] tests =
(
from tb in new[] { txtTest3, txtTest2, txtTest1, }
let result = parseTextBox(tb)
orderby result descending
select result
).ToArray();
if (tests.Any(t => t == null))
{
return;
}
double average =
tests
.Take(3 - (checkBox1.Checked ? 1 : 0))
.Average()
.Value;
var grades = new[]
{
new { Score = 59.9, Grade = "F" },
new { Score = 63.9, Grade = "D-" },
new { Score = 66.9, Grade = "D" },
new { Score = 69.9, Grade = "D+" },
new { Score = 73.9, Grade = "C-" },
new { Score = 76.9, Grade = "C" },
new { Score = 79.9, Grade = "C+" },
new { Score = 83.9, Grade = "B-" },
new { Score = 86.9, Grade = "B" },
new { Score = 89.9, Grade = "B+" },
new { Score = 93.9, Grade = "A-" },
new { Score = 96.9, Grade = "A" },
new { Score = 100.0, Grade = "A+" },
};
string grade =
grades
.Where(g => g.Score >= average)
.Select(g => g.Grade)
.First();
txtAverage.Text = average.ToString("f1");
txtLetterGrade.Text = grade;
}
I am writing a Rock(Sten), Paper(Påse), Scissor(Sax) game, that plays against the computer. It works and all but I want to break the game when one off the two wins three times. But it keeps looping...
Im really new to programming so excuse if the code is messy... :(
And im Swedish so the code is in Swedish to... Hope you understand, if not ask me..
This is the Main:
static void Main(string[] args)
{
Game ssp = new Game();
Interaction.MsgBox("Welcome!");
string Choice = Interaction.InputBox("Chose Rock, Scissor eller Paper:");
ssp.Start();
ssp.Seewicharethevinner(Choice);
}
This is the class with the methods that handels the game:
string CompusterChoice;
//Starts the game
public void Start()
{
//Computers hand
Random rnd = new Random();
int x = rnd.Next(0, 3);
if (x == 0)
{ DatornsVal = "Rock"; }
else if (x == 1)
{ DatornsVal = "Paper"; }
else if (x == 2)
{ DatornsVal = "Scissor"; }
}
//Look who will win
public void Seewicharethewinner(string _Choice)
{
string PlayerChoice = _Choice;
string _PlayerChoice = _Choice.ToUpper();
string _ComputerChoice = ComputerChoice.ToUpper();
if (_PlayerChoice == _ComputerChoice)
{
Interaction.MsgBox("Tie!\nYour choice was: " + _Choice + "\n" + "Computer choice was: " + _ComputerChoice);
string Choice = Interaction.InputBox("Chose Rock, Scissor eller Paper:");
ssp.Start();
ssp.Seewicharethevinner(Choice);
}
else if (_ComputerChoice == "ROCK" && _PlayerChoice == "SCISSOR" || _ComputerChoice == "SICSSOR" && _PlayerChoice == "PAPER" || _ComputerChoice == "PAPER"
&& _PlayerChoice == "ROCK")
{
Interaction.MsgBox("You Lose!\nYour choice was: " + _Choice + "\n" + "Computer choice was: " + _ComputerChoice);
int player = 0;
int computer = 1;
Points(computer, player);
string Choice = Interaction.InputBox("Chose Rock, Scissor eller Paper:");
ssp.Start();
ssp.Seewicharethevinner(Choice);
}
else if (_ComputerChoice == "ROCK" && _PlayerChoice == "PAPER" || _ComputerChoice == "SICSSOR" && _PlayerChoice == "ROCK" || _ComputerChoice == "PAPER"
&& _PlayerChoice == "SICSSOR")
{
Interaction.MsgBox("You won!\nYour choice was: " + _Choice + "\n" + "Computer choice was: " + _ComputerChoice);
int player = 1;
int computer = 0;
Points(computer, player);
string Choice = Interaction.InputBox("Chose Rock, Scissor eller Paper:");
ssp.Start();
ssp.Seewicharethevinner(Choice);
}
}
public void Points(int _computer, int _player)
{
int computerpoints = 0;
int playerpoints = 0;
if (_computer > _player)
{
computerpoints++;
}
else
{
playerpoints++;
}
if (computerpoints == 3)
{
Interaction.MsgBox("Computer won three times!");
}
if (playerpoints == 3)
{
Interaction.MsgBox("You won three times!");
}
}
So it looks like the problem is that in your Poang method you check to see if someone has won 3 times and if so display a message, but after you check that you don't terminate the program. It just keeps going on as if nothing happened. Also, your win count variables are locally scoped, so they lose their value every time the function ends.
There are a lot of things that could be done to make this program better, however I am just going to provide the simplest fix here:
public void UtseVinnare(string _Val)
{
string SpelareVal = _Val;
string _SpelarVal = _Val.ToUpper();
string _DatornsVal = DatornsVal.ToUpper();
if (_DatornsVal == _SpelarVal)
{
Interaction.MsgBox("Oavgjort!\nDitt val var: " + SpelareVal + "\n" + "Datorns val var: " + DatornsVal);
string Val = Interaction.InputBox("Välj Sten, Sax eller Påse:");
Starta();
UtseVinnare(Val);
}
else if (_DatornsVal == "STEN" && _SpelarVal == "SAX" || _DatornsVal == "SAX" && _SpelarVal == "PÅSE" || _DatornsVal == "PÅSE"
&& _SpelarVal == "STEN")
{
Interaction.MsgBox("Du förlorade!\nDitt val var: " + SpelareVal + "\n" + "Datorns val var: " + DatornsVal);
int spelare = 0;
int dator = 1;
if (Poang(dator, spelare))
{
return;
}
string Val = Interaction.InputBox("Välj Sten, Sax eller Påse:");
Starta();
UtseVinnare(Val);
}
else if (_DatornsVal == "STEN" && _SpelarVal == "PÅSE" || _DatornsVal == "SAX" && _SpelarVal == "STEN" || _DatornsVal == "PÅSE"
&& _SpelarVal == "SAX")
{
Interaction.MsgBox("Du vann!\nDitt val var: " + SpelareVal + "\n" + "Datorns val var: " + DatornsVal);
int spelare = 1;
int dator = 0;
if (Poang(dator, spelare))
{
return;
}
string Val = Interaction.InputBox("Välj Sten, Sax eller Påse:");
Starta();
UtseVinnare(Val);
}
}
int datorpoangraknare = 0;
int spelarpoangraknare = 0;
public bool Poang(int _dator, int _spelare)
{
if (_dator > _spelare)
{
datorpoangraknare++;
}
else
{
spelarpoangraknare++;
}
if (datorpoangraknare == 3)
{
Interaction.MsgBox("Datorn vann tre gånger!");
return true;
}
if (spelarpoangraknare == 3)
{
Interaction.MsgBox("Du vann tre gåger!");
return true;
}
return false;
}
Instead of trying to fix your code with the current methods I would suggest adding the following to make your code easier to follow:
1: Use enums to give a clear meaning to numbers.
public enum Choice
{
Rock,
Paper,
Scissor
}
public enum WinResult
{
Won,
Tie,
Lost
}
2: Add a method to ask input from user and return the result.
private Choice GiveChoice()
{
// This is a label where we can jump to if the input was invalid.
start:
// Ask the question.
Console.Clear();
Console.WriteLine("Choose (0:Rock, 1:Paper, 2:Scissor):");
string answer = Console.ReadLine();
int result = -1;
// Validate and re-ask if invalid.
if (!int.TryParse(answer, out result) || (result < 0 && result > 2))
goto start;
return (Choice) result;
}
3: Add a method to compare 2 results from eachother.
// Returns if v1 has won, tied or lost from v2. (Left to right)
private WinResult CompareForWinner(Choice v1, Choice v2)
{
if (v1 == Choice.Paper)
{
if (v2 == Choice.Paper)
return WinResult.Tie;
if (v2 == Choice.Rock)
return WinResult.Lost;
return WinResult.Won;
}
if (v1 == Choice.Rock)
{
if (v2 == Choice.Paper)
return WinResult.Lost;
if (v2 == Choice.Rock)
return WinResult.Tie;
return WinResult.Won;
}
// v1 = Scissor.
if (v2 == Choice.Paper)
return WinResult.Won;
if (v2 == Choice.Rock)
return WinResult.Lost;
return WinResult.Tie;
}
It's not a direct answer to your question. But I think it will help you solve it yourself.
Surely the answer to this question should be go and read a book on programming c#?
I noticed that this is marked as a Duplicate above. When you go to that Duplicate that too is marked as a duplicate and only 11 hours ago.
I really don't think people should be just posting up their homework....
Error: the class choosedisplay can be designed, but is not the first class in the file. Visual Studio requires that designers use the first class in the file.
How to move the class code so that it is in the first class.
I dont Know about program i am a Mechanical Engineer. I trying to do my project in C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using GraphSynth.Representation;
using GraphSynth.Forms;
using GraphSynth.Generation;
namespace GraphSynth.Forms
{
public class chooseViaHumanGui : RecognizeChooseApply
{
public override int choose(List<option> options, candidate cand)
{
SearchIO.output("There are " + options.Count.ToString() + " recognized locations.", 2);
if (options.Count == 0)
{
SearchIO.output("Sorry there are no rules recognized.", 0);
return int.MinValue;
}
else if (options.Count > Program.settings.maxRulesToDisplay)
{
SearchIO.output("Sorry there are too many rules to show.", 0);
return int.MinValue;
}
else
{
SearchIO.output("Double-click on one to show the location.", 2);
chooseDisplay choiceDisplay = new chooseDisplay();
choiceDisplay.promptUser(options, (Boolean)(cand.recipe.Count == 0));
return choiceDisplay.choice;
}
}
public override double[] choose(option RC, candidate cand)
{ return null; }
#region Constructors
public chooseViaHumanGui(Boolean _display)
: base(Program.seed, Program.rulesets, Program.settings.maxRulesToApply, _display,
Program.settings.recompileRules, Program.settings.execDir, Program.settings.compiledparamRules) { }
#endregion
}
// This is the class Program for choose display //
public partial class chooseDisplay : Form
{
#region Fields
List<option> rulesToDisplay = new List<option>();
List<int> optionNumbers = new List<int>();
public int choice = int.MinValue;
System.Windows.Forms.Timer checkForStopTimer = new System.Windows.Forms.Timer();
#endregion
public chooseDisplay()
{
checkForStopTimer.Tick += new EventHandler(processTimer_Tick);
checkForStopTimer.Interval = 500;
checkForStopTimer.Start();
}
public void promptUser(List<option> RCs, Boolean hideUndo)
{
InitializeComponent();
rulesToDisplay = RCs;
string ruleNo, location;
int option = 0;
this.Text = "Choices from RuleSet #" + RCs[0].ruleSetIndex.ToString();
for (int i = 0; i != rulesToDisplay.Count; i++)
{
option = i + 1;
ruleNo = rulesToDisplay[i].ruleNumber.ToString();
location = rulesToDisplay[i].location.ToString();
recognizedRulesList.Items.Add(option.ToString() + ".\t" + ruleNo + "\t" + location);
optionNumbers.Add(i);
}
if (hideUndo) this.undoButton.Enabled = false;
ShowDialog();
}
private void showGraph_Click(object sender, EventArgs e)
{
SearchIO.addAndShowGraphDisplay(rulesToDisplay[recognizedRulesList.SelectedIndex].location.copy(),
"Recognized Location " + recognizedRulesList.SelectedItem.ToString());
}
private void removeFromList_Click(object sender, EventArgs e)
{
int numToRemove = recognizedRulesList.CheckedIndices.Count;
if (numToRemove == recognizedRulesList.Items.Count)
{
MessageBox.Show("You cannot remove all possible options.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (numToRemove == recognizedRulesList.Items.Count - 1)
{
int[] toRemove = new int[numToRemove];
recognizedRulesList.CheckedIndices.CopyTo(toRemove, 0);
for (int i = numToRemove; i != 0; i--)
{
if (toRemove[i - 1] != optionNumbers.Count)
{
recognizedRulesList.Items.RemoveAt(toRemove[i - 1]);
optionNumbers.RemoveAt(toRemove[i - 1]);
}
}
if (DialogResult.Yes == MessageBox.Show(
"You are removing all but one option [" +
recognizedRulesList.Items[0].ToString() +
"]. Would you like to apply this option?",
"Apply Remaining Option?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
{
choice = optionNumbers[0];
this.Close();
}
}
else
{
int[] toRemove = new int[numToRemove];
recognizedRulesList.CheckedIndices.CopyTo(toRemove, 0);
for (int i = numToRemove; i != 0; i--)
{
if (toRemove[i - 1] != optionNumbers.Count)
{
recognizedRulesList.Items.RemoveAt(toRemove[i - 1]);
optionNumbers.RemoveAt(toRemove[i - 1]);
}
}
}
}
private void applyButton_Click(object sender, EventArgs e)
{
int numChecked = recognizedRulesList.CheckedIndices.Count;
checkForStopTimer.Stop();
if (numChecked == 0)
{
MessageBox.Show("No Options Checked.", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
checkForStopTimer.Start();
}
else if (numChecked == 1)
{
if (!Program.settings.confirmEachUserChoice ||
(DialogResult.Yes == MessageBox.Show(
"Apply Option: " + recognizedRulesList.CheckedItems[0].ToString() + "?",
"Apply Option?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)))
{
int[] toSaveVector = new int[numChecked];
recognizedRulesList.CheckedIndices.CopyTo(toSaveVector, 0);
choice = optionNumbers[toSaveVector[0]];
this.Close();
}
else checkForStopTimer.Start();
}
else if (DialogResult.Yes == MessageBox.Show(
"You cannot apply all of these at the same time. Would you simply like to remove all unchecked Options?", "Remove Unchecked?",
MessageBoxButtons.YesNo, MessageBoxIcon.Question))
{
int[] toSaveVector = new int[numChecked];
recognizedRulesList.CheckedIndices.CopyTo(toSaveVector, 0);
List<int> toSave = new List<int>(toSaveVector);
for (int i = recognizedRulesList.Items.Count; i != 0; i--)
{
if (!toSave.Contains(i - 1))
{
recognizedRulesList.Items.RemoveAt(i - 1);
optionNumbers.RemoveAt(i - 1);
}
}
checkForStopTimer.Start();
}
else checkForStopTimer.Start();
}
void processTimer_Tick(object sender, EventArgs e)
{
if (Program.terminateRequest)
{
recognizedRulesList.SetItemChecked(recognizedRulesList.Items.Count - 1, true);
for (int i = 0; i != recognizedRulesList.Items.Count - 1; i++)
recognizedRulesList.SetItemChecked(i, false);
applyButton_Click(sender, e);
}
}
private void undo_Click(object sender, EventArgs e)
{
if ((!Program.settings.confirmEachUserChoice ||
(DialogResult.Yes == MessageBox.Show("Undo the last rule that was applied?",
"Undo Last Rule?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))))
{
choice = -1;
this.Close();
}
}
private void stopButton_Click(object sender, EventArgs e)
{
if ((!Program.settings.confirmEachUserChoice ||
(DialogResult.Yes == MessageBox.Show("Send Stop message to Generation Process?",
"Send Stop?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))))
{
choice = int.MinValue;
this.Close();
}
}
}
}
Look here: https://stackoverflow.com/a/8864376/3317555. Basically the choosedisplay class is sharing a file with another class. All you should have to do is move choosedisplay into it's own file.
EDIT: Fixed bad wording.
You've got two classes declared in the same code file. Move the second one to a different file.
EDIT: Actually, as the second is a form and is probably what that code file was created for in the first place, you should probably move the first class out into its own file.