C# Simple Passing Parameters Issue - c#

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);
}
}

Related

C# Voice Recognition code not working on some machines

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! :)

Unpack iOS app receipt in c# and php

I have Xamarin iOS app with in-app products. I get base64 encoded app receipt:
NSUrl receiptURL = NSBundle.MainBundle.AppStoreReceiptUrl;
String receiptData = receipt.GetBase64EncodedString(0);
According to Apple docs 7.0+ app receipt is packed in PKCS7 container using ASN1. When I send it to apple server it returns receipt in JSON. But I want to parse it locally to know what iaps user does already have. I don't need validation, as Apple does it remotely, I just need to get receipts for purchased inaps.
So far, as an investigation, I've parsed it in php with phpseclib, manually (no idea how to do this programatically) located receipt and parsed it as well.
$asn_parser = new File_ASN1();
//parse the receipt binary string
$pkcs7 = $asn_parser->decodeBER(base64_decode($f));
//print_r($pkcs7);
$payload_sequence = $pkcs7[0]['content'][1]['content'][0]['content'][2]['content'];
$pld = $asn_parser->decodeBER($payload_sequence[1]['content'][0]['content']);
//print_r($pld);
$prd = $asn_parser->decodeBER($pld[0]['content'][21]['content'][2]['content']);
print_r($prd);
But even this way I've got a mess of attributes, each looks like:
Array
(
[start] => 271
[headerlength] => 2
[type] => 4
[content] => 2016-08-22T13:22:00Z
[length] => 24
)
It is not human readable, I need something like (output with print_r of returned by Apple) :
[receipt] => Array
(
[receipt_type] => ProductionSandbox
[adam_id] => 0
[app_item_id] => 0
[bundle_id] => com.my.test.app.iOS
...
[in_app] => Array
(
[0] => Array
(
[quantity] => 1
[product_id] => test_iap_1
[transaction_id] => 1000000230806171
...
[is_trial_period] => false
)
)
)
Things seem too complicated, I hardly believe unpacking receipt is so complex. Does anybody know how to manage this? I've found this post but library is written in objective-C which is not applicable to my current environment. I'd say sources of this lib are frightened me: so much complex code just to unpack standartized container. I mean working with json, bson, etc. is very easy, but not asn1.
Finally I've unpacked it using Liping Dai LCLib (lipingshare.com). Asn1Parser returns DOM-like tree with root node - very handy lib.
public class AppleAppReceipt
{
public class AppleInAppPurchaseReceipt
{
public int Quantity;
public string ProductIdentifier;
public string TransactionIdentifier;
public DateTime PurchaseDate;
public string OriginalTransactionIdentifier;
public DateTime OriginalPurchaseDate;
public DateTime SubscriptionExpirationDate;
public DateTime CancellationDate;
public int WebOrderLineItemID;
}
const int AppReceiptASN1TypeBundleIdentifier = 2;
const int AppReceiptASN1TypeAppVersion = 3;
const int AppReceiptASN1TypeOpaqueValue = 4;
const int AppReceiptASN1TypeHash = 5;
const int AppReceiptASN1TypeReceiptCreationDate = 12;
const int AppReceiptASN1TypeInAppPurchaseReceipt = 17;
const int AppReceiptASN1TypeOriginalAppVersion = 19;
const int AppReceiptASN1TypeReceiptExpirationDate = 21;
const int AppReceiptASN1TypeQuantity = 1701;
const int AppReceiptASN1TypeProductIdentifier = 1702;
const int AppReceiptASN1TypeTransactionIdentifier = 1703;
const int AppReceiptASN1TypePurchaseDate = 1704;
const int AppReceiptASN1TypeOriginalTransactionIdentifier = 1705;
const int AppReceiptASN1TypeOriginalPurchaseDate = 1706;
const int AppReceiptASN1TypeSubscriptionExpirationDate = 1708;
const int AppReceiptASN1TypeWebOrderLineItemID = 1711;
const int AppReceiptASN1TypeCancellationDate = 1712;
public string BundleIdentifier;
public string AppVersion;
public string OriginalAppVersion; //какую покупали
public DateTime ReceiptCreationDate;
public Dictionary<string, AppleInAppPurchaseReceipt> PurchaseReceipts;
public bool parseAsn1Data(byte[] val)
{
if (val == null)
return false;
Asn1Parser p = new Asn1Parser();
var stream = new MemoryStream(val);
try
{
p.LoadData(stream);
}
catch (Exception e)
{
return false;
}
Asn1Node root = p.RootNode;
if (root == null)
return false;
PurchaseReceipts = new Dictionary<string, AppleInAppPurchaseReceipt>();
parseNodeRecursive(root);
return !string.IsNullOrEmpty(BundleIdentifier);
}
private static string getStringFromSubNode(Asn1Node nn)
{
string dataStr = null;
if ((nn.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.OCTET_STRING && nn.ChildNodeCount > 0)
{
Asn1Node n = nn.GetChildNode(0);
switch (n.Tag & Asn1Tag.TAG_MASK)
{
case Asn1Tag.PRINTABLE_STRING:
case Asn1Tag.IA5_STRING:
case Asn1Tag.UNIVERSAL_STRING:
case Asn1Tag.VISIBLE_STRING:
case Asn1Tag.NUMERIC_STRING:
case Asn1Tag.UTC_TIME:
case Asn1Tag.UTF8_STRING:
case Asn1Tag.BMPSTRING:
case Asn1Tag.GENERAL_STRING:
case Asn1Tag.GENERALIZED_TIME:
{
if ((n.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.UTF8_STRING)
{
UTF8Encoding unicode = new UTF8Encoding();
dataStr = unicode.GetString(n.Data);
}
else
{
dataStr = Asn1Util.BytesToString(n.Data);
}
}
break;
}
}
return dataStr;
}
private static DateTime getDateTimeFromSubNode(Asn1Node nn)
{
string dataStr = getStringFromSubNode(nn);
if (string.IsNullOrEmpty(dataStr))
return DateTime.MinValue;
DateTime retval = DateTime.MaxValue;
try
{
retval = DateTime.Parse(dataStr);
}
catch (Exception e)
{
}
return retval;
}
private static int getIntegerFromSubNode(Asn1Node nn)
{
int retval = -1;
if ((nn.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.OCTET_STRING && nn.ChildNodeCount > 0)
{
Asn1Node n = nn.GetChildNode(0);
if ((n.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.INTEGER)
retval = (int)Asn1Util.BytesToLong(n.Data);
}
return retval;
}
private void parseNodeRecursive(Asn1Node tNode)
{
bool processed_node = false;
if ((tNode.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.SEQUENCE && tNode.ChildNodeCount == 3)
{
Asn1Node node1 = tNode.GetChildNode(0);
Asn1Node node2 = tNode.GetChildNode(1);
Asn1Node node3 = tNode.GetChildNode(2);
if ((node1.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.INTEGER && (node2.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.INTEGER &&
(node3.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.OCTET_STRING)
{
processed_node = true;
int type = (int)Asn1Util.BytesToLong(node1.Data);
switch (type)
{
case AppReceiptASN1TypeBundleIdentifier:
BundleIdentifier = getStringFromSubNode(node3);
break;
case AppReceiptASN1TypeAppVersion:
AppVersion = getStringFromSubNode(node3);
break;
case AppReceiptASN1TypeOpaqueValue:
break;
case AppReceiptASN1TypeHash:
break;
case AppReceiptASN1TypeOriginalAppVersion:
OriginalAppVersion = getStringFromSubNode(node3);
break;
case AppReceiptASN1TypeReceiptExpirationDate:
break;
case AppReceiptASN1TypeReceiptCreationDate:
ReceiptCreationDate = getDateTimeFromSubNode(node3);
break;
case AppReceiptASN1TypeInAppPurchaseReceipt:
{
if (node3.ChildNodeCount > 0)
{
Asn1Node node31 = node3.GetChildNode(0);
if ((node31.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.SET && node31.ChildNodeCount > 0)
{
AppleInAppPurchaseReceipt receipt = new AppleInAppPurchaseReceipt();
for (int i = 0; i < node31.ChildNodeCount; i++)
{
Asn1Node node311 = node31.GetChildNode(i);
if ((node311.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.SEQUENCE && node311.ChildNodeCount == 3)
{
Asn1Node node3111 = node311.GetChildNode(0);
Asn1Node node3112 = node311.GetChildNode(1);
Asn1Node node3113 = node311.GetChildNode(2);
if ((node3111.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.INTEGER && (node3112.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.INTEGER &&
(node3113.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.OCTET_STRING)
{
int type1 = (int)Asn1Util.BytesToLong(node3111.Data);
switch (type1)
{
case AppReceiptASN1TypeQuantity:
receipt.Quantity = getIntegerFromSubNode(node3113);
break;
case AppReceiptASN1TypeProductIdentifier:
receipt.ProductIdentifier = getStringFromSubNode(node3113);
break;
case AppReceiptASN1TypeTransactionIdentifier:
receipt.TransactionIdentifier = getStringFromSubNode(node3113);
break;
case AppReceiptASN1TypePurchaseDate:
receipt.PurchaseDate = getDateTimeFromSubNode(node3113);
break;
case AppReceiptASN1TypeOriginalTransactionIdentifier:
receipt.OriginalTransactionIdentifier = getStringFromSubNode(node3113);
break;
case AppReceiptASN1TypeOriginalPurchaseDate:
receipt.OriginalPurchaseDate = getDateTimeFromSubNode(node3113);
break;
case AppReceiptASN1TypeSubscriptionExpirationDate:
receipt.SubscriptionExpirationDate = getDateTimeFromSubNode(node3113);
break;
case AppReceiptASN1TypeWebOrderLineItemID:
receipt.WebOrderLineItemID = getIntegerFromSubNode(node3113);
break;
case AppReceiptASN1TypeCancellationDate:
receipt.CancellationDate = getDateTimeFromSubNode(node3113);
break;
}
}
}
}
if (!string.IsNullOrEmpty(receipt.ProductIdentifier))
PurchaseReceipts.Add(receipt.ProductIdentifier, receipt);
}
}
}
break;
default:
processed_node = false;
break;
}
}
}
if (!processed_node)
{
for (int i = 0; i < tNode.ChildNodeCount; i++)
{
Asn1Node chld = tNode.GetChildNode(i);
if (chld != null)
parseNodeRecursive(chld);
}
}
}
}
And usage:
public void printAppReceipt()
{
NSUrl receiptURL = NSBundle.MainBundle.AppStoreReceiptUrl;
if (receiptURL != null)
{
Console.WriteLine("receiptUrl='" + receiptURL + "'");
NSData receipt = NSData.FromUrl(receiptURL);
if (receipt != null)
{
byte[] rbytes = receipt.ToArray();
AppleAppReceipt apprec = new AppleAppReceipt();
if (apprec.parseAsn1Data(rbytes))
{
Console.WriteLine("Received receipt for " + apprec.BundleIdentifier + " with " + apprec.PurchaseReceipts.Count +
" products");
Console.WriteLine(JsonConvert.SerializeObject(apprec,Formatting.Indented));
}
}
else
Console.WriteLine("receipt == null");
}
}

How to add another one consumer?

How to add another one consumer in my program? I trying this, but not working...
I find this post how to add consumers in multithreading , but its not what i need, becouse I dont need lock... And i need without class or something like that. Just with my code.. PLease help :)
private int occupiedBufferCount = 0;
private int occupiedBufferCount2 = 0;
int i = 0;
private void Producer()
{
int how_much_numbers = Convert.ToInt32(textBox3.Text);
using (StreamWriter writer = new StreamWriter("random_skaiciai.txt"))
{
for (i = 0; i < how_much_numbers; i++)
{
Monitor.Enter(this);
if ((occupiedBufferCount == 1) || (occupiedBufferCount2 == 1))
{
Monitor.Wait(this);
}
++occupiedBufferCount;
buffer = i;
Random rnd = new Random();
numbers = i;
//numbers = rnd.Next(nuo, iki);
writer.WriteLine(numbers + "");
prm = false;
fib = false;
Monitor.Pulse(this);
Monitor.Exit(this);
if (isCanceled == true)
break;
}
writer.Close();
Set_p(kiek);
}
}
private void Consumer1()
{
int how_much_numbers = Convert.ToInt32(textBox3.Text);
using (StreamWriter writer = new StreamWriter("Primary_numbers.txt"))
{
while (i < how_much_numbers)
{
Monitor.Enter(this);
if ((occupiedBufferCount == 0))
{
Monitor.Wait(this);
}
--occupiedBufferCount;
if (numbers != 0)
if (prime_num(numbers) == true)
{
writer.WriteLine(numbers + "");
}
prm = true;
Monitor.Pulse(this);
Monitor.Exit(this);
if (isCanceled == true)
break;
}
writer.Close();
}
}
private void Consumer2()
{
int how_much_numbers = Convert.ToInt32(textBox3.Text);
using (StreamWriter writer = new StreamWriter("fibon_Numbers.txt"))
{
while (i < how_much_numbers)
{
Monitor.Enter(this);
if ((occupiedBufferCount2 == 0))
{
Monitor.Wait(this);
}
--occupiedBufferCount2;
if (numbers != 0)
if (isfibonaci(numbers) == true)
writer.WriteLine(numbers + "");
Monitor.Pulse(this);
Monitor.Exit(this);
if (isCanceled == true)
break;
}
writer.Close();
}
}

Rock, Paper, Scissor game - how to end when one wins three times?

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....

How to display multiple icons on same points in googlemap in .net?

How to display multiple icons on same points in googlemap in .net using goolemap api 3
Below is my code
public void selectTrainings(string strQuery)
{
try
{
clsTblMembers objtblMember = new clsTblMembers();
objtblMember.StrEmail = strQuery.ToString();
DataTable dt = objtblMember.SelectSearch();
if (dt != null)
{
int i;
for (i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["Latitude"].ToString() != "" && dt.Rows[i]["Longitude"].ToString() != "")
{
string StrLat = dt.Rows[i]["Latitude"].ToString();
string StrLon = dt.Rows[i]["Longitude"].ToString();
double Numlat;
bool isNumlat = double.TryParse(StrLat, out Numlat);
double Numlon;
bool isNumlon = double.TryParse(StrLon, out Numlon);
if ((isNumlat) && (isNumlon))
{
//coordinates datatype =double;
m1 = new MapControl.MapMarker();
m1.Latitude = Convert.ToDouble(dt.Rows[i]["Latitude"].ToString());
m1.Longitude = Convert.ToDouble(dt.Rows[i]["Longitude"].ToString());
getTraining(Convert.ToInt32(dt.Rows[i]["intId"].ToString()), Convert.ToInt32(dt.Rows[i]["intTypeId"].ToString()), dt.Rows[i]["strCode"].ToString(), dt.Rows[i]["strConductedBy"].ToString(), dt.Rows[i]["dtFromDate"].ToString(), dt.Rows[i]["dtToDate"].ToString(), dt.Rows[i]["strName"].ToString(), dt.Rows[i]["strUC"].ToString(), dt.Rows[i]["strVillage"].ToString());
if (dt.Rows[i]["intTypeId"].ToString() == "1")
{
m1.Title ="CMST - "+ dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t1.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "2")
{
m1.Title = "LMST - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t2.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "3")
{
m1.Title = " Govt.Official Training - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t3.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "4")
{
m1.Title = "Gender Based Violence - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/pg.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "5")
{
m1.Title = "Human Rights - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/ph.png";
}
else
{
m1.Title = "Livelihoods Skills Training - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t4.png";
}
m1.ImageSize1 = 32.0;
m1.ImageSize2 = 37.0;
m1.ImagePoint1 = 0;
m1.ImagePoint2 = 0;
m1.ImagePoint3 = 16.0;
m1.ImagePoint4 = 18.0;
m1.Shadow = "mapIcons/shadow.png";
m1.ShadowSize1 = 51.0;
m1.ShadowSize2 = 37.0;
m1.ShadowPoint1 = 0;
m1.ShadowPoint2 = 0;
m1.ShadowPoint3 = 16.0;
m1.ShadowPoint4 = 18.0;
GoogleMap.Markers.Add(m1);
}
}
}
}
}
catch (Exception ex)
{
}
}

Categories

Resources