I'm a beginner with programming so any hints would be greatly appreciated!
I'm trying to create a program where the user guesses whether a 'coin toss' will produce heads (0) or tails (1) using a random number generator and a loop as the 'coin'. The program must output the percent of correct guesses out of the total games played.
I've tried many different ways and it's far from right! It's v discouraging.
Thanks in advance for any tips!!
-C
This is basically the closest I've come:
for (numPlays = 0; ; numPlays++)
{
Console.Write("\nWrite H/h to guess Heads, T/t to guess Tails, or Q/q to quit => ");
userChoice = Convert.ToChar(Console.ReadLine());
if (userChoice == 'H' || userChoice == 'h')
{
if (compChoice == 0)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
Console.WriteLine("\nYOU LOSE");
if (userChoice == 'Q' || userChoice == 'q')
if (compChoice == 1)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
Console.WriteLine("\nYOU LOSE");
if (userChoice == 'q' || userChoice == 'Q')
{
percentWin = (double)(numWins / numPlays);
Console.WriteLine("\nYou won {0} out of {1} game(s) or {2:P} of the games played.", numWins, numPlays, percentWin);
}
}
}
Console.ReadKey();
}
}
I optimized your code a little bit,I hope this helps:
int numPlays = 0, numWins = 0;
int compChoice = 0;
char userChoice;
double percentWin;
Random rnd = new Random();
while (true)
{
Console.Write("\nWrite H/h to guess Heads, T/t to guess Tails, or Q/q to quit => ");
userChoice = Console.ReadKey().KeyChar;
compChoice = rnd.Next(0, 2);
if (char.ToLowerInvariant(userChoice) != 'q')
{
if (char.ToLowerInvariant(userChoice) == 'h' && compChoice == 0)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else if (char.ToLowerInvariant(userChoice) == 't' && compChoice == 1)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
{
Console.WriteLine("\nYOU LOSE");
}
numPlays++;
}
else
{
percentWin = (double) numWins/numPlays;
Console.WriteLine("\nYou won {0} out of {1} game(s) or {2:P} of the games played.", numWins, numPlays, percentWin);
break;
}
}
I think you don't need an explanation, all of the code is self-explanatory.But you have an obvious mistake when you calculating the percentage:
percentWin = (double)(numWins / numPlays);
Here you are performing an integer division,then casting that result to double,it's pointless because you already lose your decimal points.Instead you should cast one of the operands to double so it will perform a double division and you will get the correct result.
Just invoke this method and play your game!
public static void SomeMethod()
{
Console.Write("\nWrite H/h to guess Heads, T/t to guess Tails, or Q/q to quit => ");
char userChoice;
int numWins = 0;
int numPlays = 0;
double percentWin = 0d;
while ((userChoice = Convert.ToChar(Console.ReadLine())).ToString().ToLower() != "q")
{
numPlays++;
int compChoice = new Random().Next(2);
if (userChoice == 'H' || userChoice == 'h')
{
if (compChoice == 0)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
{
Console.WriteLine("\nYOU LOSE");
}
continue;
}
if (userChoice == 'T' || userChoice == 't')
{
if (compChoice == 1)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
{
Console.WriteLine("\nYOU LOSE");
}
continue;
}
}
if (numPlays != 0)
{
percentWin = (double)numWins / numPlays;
}
Console.WriteLine("\nYou won {0} out of {1} game(s) or {2:P} of the games played.", numWins, numPlays, percentWin);
Console.ReadKey();
}
This should not be any difficult, you just need to make a clear algorithm
Let me suggest one
Char playOrExit= 'y'
Int32 gameCount = 0;
Int32 Wins = 0;
While (playOrExit.ToUpper.Equals('Y'))
{
Console.Write("Press Y to continue playing and N to exit");
playOrExit = Convert.ToChar(Console.ReadLine());
//Computer choice will be math.random from 0 and 1
//now take user choice
//compare and show if he won or lost
}
if(gameCount >0)
{
Console.WriteLine("\nYou played {0} times, out of which {1} game(s) were won.", gameCount,Wins);
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
using System;
using System.Collections.Generic;
namespace Learning_C__Program
{
class Program
{
static void Main(string[] args)
{
int enemyHealth = 1000;
int playerHealth = 1000;
string[] limbPicked = {"","","",""};
string[] enemyTypes = {"Ogre","Beast","Dragon"};
Random enemyPick = new Random();
int pickEnemy = enemyPick.Next(2);
// Below is the if statements for when an ogre is picked
int i = 1;
while(i == 1) {
if (pickEnemy == 0||pickEnemy == 1||pickEnemy == 2) {
string enemyUsing;
if (pickEnemy == 0) {
enemyUsing = enemyTypes[0];
}
else if (pickEnemy == 1) {
enemyUsing = enemyTypes[1];
}
else {
enemyUsing = enemyTypes[2];
}
Console.WriteLine("You encounter an unhappy " + enemyUsing + "! It starts a fight!\nSelect a limb to hit: ");
limbPicked[0] = Convert.ToString(Console.ReadLine());
if (limbPicked[0] == "Head"||limbPicked[0] == "head"||limbPicked[0] == "Torso"||limbPicked[0] == "torso"||limbPicked[0] == "Arms"||limbPicked[0] == "arms"||limbPicked[0] == "Legs"||limbPicked[0] == "legs") {
Random hitAmount = new Random();
int damage1 = hitAmount.Next(1,300);
Console.WriteLine("You attempted to strike the " + enemyUsing + " in the " + limbPicked[0] + " doing " + damage1 + " damage to the " + enemyUsing + "! They now have " + (enemyHealth - damage1) + " health!");
enemyHealth = enemyHealth - damage1;
Random enemyHitAmount = new Random();
int damage2 = enemyHitAmount.Next(1,300);
Console.WriteLine("The enemy attacks! They do " + damage2 + " damage to you! You now have " + (playerHealth - damage2) + " health!");
playerHealth = playerHealth - damage2;
if (playerHealth == 0) {
Random deathSentence = new Random();
int words = deathSentence.Next(7);
string[] wordsSaying = {"slain","slaughtered","murdered","defeated","beheaded","impaled","shredded"};
if (words == 0) {
Console.WriteLine("The enemy has slain you\nPress any key to exit");
}
else if (words == 1) {
Console.WriteLine("The enemy has slaughtered you\nPress any key to exit");
}
else if (words == 2) {
Console.WriteLine("The enemy has murdered you\nPress any key to exit");
}
else if (words == 3) {
Console.WriteLine("The enemy has defeated you\nPress any key to exit");
}
else if (words == 4) {
Console.WriteLine("The enemy has beheaded you\nPress any key to exit");
}
else if (words == 5) {
Console.WriteLine("The enemy has impaled you\nPress any key to exit");
}
else {
Console.WriteLine("The enemy has shredded you\nPress any key to exit");
}
Console.ReadKey();
if (enemyHealth == 0) {
Random deathSentence2 = new Random();
int words2 = deathSentence2.Next(7);
string[] wordsSaying2 = {"slain","slaughtered","murdered","defeated","beheaded","impaled","shredded"};
if (words2 == 0) {
Console.WriteLine("You have slain the enemy\nPress any key to exit");
}
else if (words2 == 1) {
Console.WriteLine("You have slaughtered the enemy\nPress any key to exit");
}
else if (words2 == 2) {
Console.WriteLine("You have murdered the enemy\nPress any key to exit");
}
else if (words2 == 3) {
Console.WriteLine("You have defeated the enemy\nPress any key to exit");
}
else if (words2 == 4) {
Console.WriteLine("You have beheaded the enemy\nPress any key to exit");
}
else if (words2 == 5) {
Console.WriteLine("You have impaled the enemy\nPress any key to exit");
}
else {
Console.WriteLine("You have shredded the enemy\nPress any key to exit");
}
Console.ReadKey();
}
}
else {
Console.WriteLine("That is not one of the available limbs, please select one of the following:\nHead\nTorso\nArms\nLegs");
}
}
break;
}
Console.ReadKey();
}
}
}
}
My code is starting, and then when I go to input the area I want to try to hit, it moves on to line 48, where it starts to print out "You attempted to strike the " + enemyUsing + " in the " etc
But it types Y then ends for some reason! Please help!
just remove break; at line 150, which exits the while (i == 1) loop
Also looks like you misplaced else block, it should be after checking user input, not after if (playerHealth == 0)
else
{
Console.WriteLine("That is not one of the available limbs, please select one of the following:\nHead\nTorso\nArms\nLegs");
}
The location of the break; actually should be after one of your exit conditions
else
{
Console.WriteLine("You have shredded the enemy\nPress any key to exit");
}
Console.ReadKey();
break; // exit while loop or return; if you want to stop game
I have the following C# Code
int amount_guesses = 2;
int c_answer = 4;
int u_answer = 0;
Console.WriteLine("Guessing Game");
Console.WriteLine("*Hint:The number is between 1 and 5");
Console.WriteLine("*Hint:You only get 2 guesses");
while (u_answer != c_answer || amount_guesses != 0)
{
u_answer = Convert.ToInt32(Console.ReadLine());
amount_guesses = amount_guesses-1;
if (u_answer == c_answer)
{
Console.WriteLine("Well Done that is the Correct Number");
}
else
{
Console.WriteLine("Wrong Number!Try again.You have {0} trys left", amount_guesses);
}
}
Console.WriteLine("Press any key to close");
Console.ReadLine();
But it's not jumping out of the loop when the requirements in the while statement are not met.
I also tried
while ((u_answer != c_answer) || (amount_guesses != 0))
But it's still not working, I ended changing the logic to this:
int amount_guesses = 2;
int c_answer = 4;
int u_answer = 0;
Console.WriteLine("Guessing Game");
Console.WriteLine("*Hint:The number is between 1 and 5");
Console.WriteLine("*Hint:You only get 2 guesses");
while (u_answer != c_answer && amount_guesses != 0)
{
u_answer = Convert.ToInt32(Console.ReadLine());
amount_guesses = amount_guesses-1;
if (u_answer == c_answer)
{
Console.WriteLine("Well Done that is the Correct Number");
amount_guesses = 0;
}
else
{
Console.WriteLine("Wrong Number!Try again.You have {0} trys left", amount_guesses);
}
}
Console.WriteLine("Press any key to close");
Console.ReadLine();
That works fine, but I wanted to know why my code at the top where I use || does not work?
A while loop continues as long as its condition is met. In your case, you want to continue loop as long as the player hasn't guessed the number and has guesses left. You should use an && (logical AND) condition, not an ||:
while (u_answer != c_answer && amount_guesses != 0)
{
// Here ----------------^
This is a common(ish) issue when using negation in boolean logic. OR sounds like it should be right as it matches are English way of speaking, but actually AND is what you want.
I try to always write the condition testing for equality and then negate it, so instead of:
u_answer != c_answer && amount_guesses != 0
You can write:
!(u_answer == c_answer || amount_guesses == 0)
Which is the same condition.
Take a look at De Morgams Law, also more easily remembered as
Break the line, change the sign
static int beverageSelection()
{
Console.WriteLine();
int brand;
string _val = "";
Console.Write("Enter number: ");
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace)
{
double val = 0;
bool _x = double.TryParse(key.KeyChar.ToString(), out val);
if (_x)
{
_val += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (key.Key == ConsoleKey.Backspace && _val.Length > 0)
{
_val = _val.Substring(0, (_val.Length - 1));
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
brand = Convert.ToInt32(Console.ReadLine());
return brand;
}
The method above is giving me a headache. I cannot figure out how to tell the console app that it shouldn't let me input any character or even the enter button until I have typed a number into the console. Then and only then should I be able to press enter.
In any case this program is a vending machine I created for fun and I do not fully understand the do while loop in this code just to be clear.
Use Console.ReadLine instead of Console.ReadKey:
int brand = 0;
while (true)
{
string val = Console.ReadLine();
if (int.TryParse(val, out brand)) break;
}
Improved your original code to display and accept only numbers
static void Main(string[] args)
{
Console.WriteLine();
int brand;
string _val = "";
Console.Write("Enter number: ");
while(true)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter && int.TryParse(_val, out brand))
{
Console.WriteLine();
break;
}
if (key.Key != ConsoleKey.Backspace)
{
int val;
if (int.TryParse(key.KeyChar.ToString(), out val))
{
_val += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (_val.Length > 0)
{
_val = _val.Substring(0, _val.Length - 1);
Console.Write("\b \b");
}
}
}
Console.WriteLine("Brand: {0}", brand);
Console.ReadKey();
}
For the sake of completeness, if anyone wants the console to prevent non-numeric characters until a numeric value is chosen, you can simply use this unerring code to accomplish your task:
int inputBoundary = Console.CursorLeft;
string consoleInput = String.Empty;
ConsoleKeyInfo inputKey;
while((inputKey = Console.ReadKey(true)).Key != ConsoleKey.Enter || consoleInput == String.Empty)
{
if (inputKey.Key == ConsoleKey.Backspace && Console.CursorLeft != inputBoundary)
{
Console.Write("\b \b");
consoleInput = consoleInput.Remove(consoleInput.Length - 1);
continue;
}
if (Char.IsNumber(inputKey.KeyChar))
{
Console.Write(inputKey.KeyChar);
consoleInput += inputKey.KeyChar;
}
}
int selection = Int32.Parse(consoleInput);
I am relatively new to coding on c# and just wondering why I get a red underline on my "Else" line. can anyone help me??
class Program
{
static void Main()
{
string temp;
int number;
char computer = ' ', answer;
Random rand = new Random();
Console.WriteLine("Press p for paper, s for scissor or r for rock");
temp = Console.ReadLine();
answer = Convert.ToChar(temp);
number = rand.Next(3);
switch (number)
{
case 1:
computer = 'p';
Console.WriteLine("CPU chose paper");
break;
case 2:
computer = 's';
Console.WriteLine("CPU chose scissors");
break;
case 3:
computer = 'r';
Console.WriteLine("CPU chose rock");
break;
}
if (answer == computer)
{
Console.WriteLine("Draw");
}
else if (((answer == 'r')&&(computer == 's'))
||((answer == 's')&&(computer == 'p'))
||((answer == 'p')&&(computer == 'r')))
{
Console.WriteLine("You have won");
}
else (((answer == 's')&&(computer == 'r'))
||((answer == 'p')&&(computer == 's'))
||((answer == 'r')&&(computer == 'p')))
{
Console.WriteLine("You have lost");
}
Console.ReadLine();
}
}
You cant have conditions in else. I have converted your else with else if. below is corrected code
class Program
{
static void Main()
{
string temp;
int number;
char computer = ' ', answer;
Random rand = new Random();
Console.WriteLine("Press p for paper, s for scissor or r for rock");
temp = Console.ReadLine();
answer = Convert.ToChar(temp);
number = rand.Next(3);
switch (number)
{
case 1:
computer = 'p';
Console.WriteLine("CPU chose paper");
break;
case 2:
computer = 's';
Console.WriteLine("CPU chose scissors");
break;
case 3:
computer = 'r';
Console.WriteLine("CPU chose rock");
break;
}
if (answer == computer)
{
Console.WriteLine("Draw");
}
else if (((answer == 'r') && (computer == 's')) || ((answer == 's') && (computer == 'p')) || ((answer == 'p') && (computer == 'r')))
{
Console.WriteLine("You have won");
}
else if
(((answer == 's') && (computer == 'r')) || ((answer == 'p') && (computer == 's')) || ((answer == 'r') && (computer == 'p')))
{
Console.WriteLine("You have lost");
}
else
{
Console.WriteLine("In conclusive");
}
Console.ReadLine();
}
}
The else alone can't take a condition. To check a condition you need another if clause in the else branch:
if (condition) {
...
}
else if (other condition)
{
...
}
I wrote a small Shotgun app, however, the section of code that needs to stop the game when either the AI (called Genius), the user, or both, are shot, I can't get to work. What am I doing wrong? I feel like I over-complicated my code a ton by adding lots of returns with different booleans, in which some are being passed and others aren't.
In testing it right now, the loop ends no matter what if the user move (called string move) equals "f". In any other scenario, I can not get the loop to end.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public static void Main(string[] args)
{
Start("r");
}
public static string Start(string move)
{
Console.Write("Welcome to the Shotgun App\nEnter s for single player and m for multiplayer: ");
string gameType = Console.ReadLine();
if (gameType == "s")
{
Console.Write("Single Player Controls:\n r = reload\n s = shield\n f = fire\nYou start with 1 ammo\nReady to play?");
Console.ReadLine();
int ammo = 1;
int geniusAmmo = 1;
string geniusMove = "";
bool done = false;
while (!done)
{
Console.Write("\nEnter your move: ");
move = Console.ReadLine();
switch (move)
{
case "r":
Console.Write("\nYou have reloaded, press enter for Genius\n");
ammo++;
Console.Write("Your ammo is " + ammo);
Console.ReadLine();
Genius(geniusMove, move, geniusAmmo, done);
break;
case "s":
Console.Write("\nYou have shielded, press enter for Genius\n");
Console.Write("Your ammo is " + ammo);
Console.ReadLine();
Genius(geniusMove, move, geniusAmmo, done);
break;
case "f":
if (ammo != 0)
{
Console.Write("\nYou have fired, press enter for Genius\n");
ammo--;
Console.Write("Your ammo is " + ammo);
Console.ReadLine();
Genius(geniusMove, move, geniusAmmo, done);
}
else
{
Console.Write("You don't have enough ammo, try again");
done = false;
}
break;
default:
Console.Write("\nInvalid move, try again\n");
done = false;
break;
}
done = EndLoop(move, geniusMove, done);
Console.ReadLine();
}
return move;
}
else
{
return move;
}
}
public static string Genius(string geniusMove, string move, int geniusAmmo, bool done)
{
Random RandomNumber = new Random();
int x = RandomNumber.Next(0,3);
if (x == 0)
{
geniusMove = "f";
geniusAmmo--;
Console.Write("Genius had decided to fire.\nGenius ammo is " + geniusAmmo + "\n");
TestMoves(move, geniusMove);
}
else if (x == 1)
{
geniusMove = "r";
geniusAmmo++;
Console.Write("Genius had decided to reload.\nGenius ammo is " + geniusAmmo + "\n");
TestMoves(move, geniusMove);
}
else if (x == 2)
{
geniusMove = "s";
Console.Write("Genius had decided to shield.\nGenius ammo is " + geniusAmmo + "\n");
TestMoves(move, geniusMove);
}
return geniusMove;
}
public static void TestMoves(string move, string geniusMove)
{
bool done = false;
if (move == "s" && geniusMove == "f")
{
Console.Write("Nice shield, no one has died yet");
}
else if (move == "f" && geniusMove == "f")
{
Console.Write("You both died! Good game!");
}
else if (move == "r" && geniusMove == "f")
{
Console.Write("No shield!? You died! Good game!");
}
else if (move == "f" && geniusMove == "s")
{
Console.Write("Genius is too good, no one has died yet");
}
else if (move == "f" && geniusMove != "s")
{
Console.Write("Genius let his guard down! Good game!");
}
else if (move != "f" && geniusMove != "f")
{
Console.Write("Keep playing it safe.");
}
else
{
}
}
static bool EndLoop(string move, string geniusMove, bool done)
{
done = false;
if (move == "s" && geniusMove == "f")
{
return false;
}
else if (move == "f" && geniusMove == "f")
{
return true;
}
else if (move != "s" && geniusMove == "f")
{
return true;
}
else if (move == "f" && geniusMove == "s")
{
return false;
}
else if (move == "f" && geniusMove != "s")
{
return true;
}
else if (move != "f" && geniusMove != "f")
{
return false;
}
else
{
return done;
}
}
}
}
You are setting done in a few different places, both in some execution branches in the switch cases, and when calling EndLoop. The assignment from EndLoop will overwrite any previous assignment, so make that The One Place You Set done.
Setting done with EndLoop in TestMoves does not have any effect since you immediately return a hard-coded value right after you call EndLoop.
I suggest you follow through EndLoop in a debugger. If it makes it easier for you to visualize what's happening, you might consider instead printing to the console the input parameters for EndLoop, and which if condition you end up selecting.
geniusMove will always be an empty string since you are not storing the result of the call to the Genius method.
Either store the result in the geniusMove variable or pass it in by reference
public static string Genius(ref string geniusMove, string move, int geniusAmmo, bool done)
or
geniusMove = Genius(geniusMove, move, geniusAmmo, done);