How to replay the game and break out of a loop? - c#

I'm building a program that the dices generates random numbers. I decided to write down in other methods while calling it in the main method. I'm trying to replay the game and break out of the loop by writing in a seperate method. For some reason it won't work and the console shows me an error to which I will show you the picture below.
static void Main(string[] args)
{
Console.WriteLine("Hey! Welcome to Tina's Dice Game");
Console.WriteLine("Let's Start!");
PlayGame();
PlayAgain();
RollDice();
static void PlayGame()
{
while (true)
{
int Dice1 = RollDice();
int Dice2 = RollDice();
Console.WriteLine("Dice 1 = " + Dice1);
Console.WriteLine("Dice 2 = " + Dice2);
Console.WriteLine("I got " + Dice1 + " and " + Dice2);
if (Dice1 % 2 == 0 && Dice2 % 2 == 0)
{
Console.WriteLine("Evens are better than odds");
}
else
{
Console.WriteLine("Odds are still cool.");
}
}
}
}
public static void PlayAgain()
{
Console.WriteLine("Do you want to play it again? (Yes or No)");
string answer = Console.ReadLine();
if (answer == "Yes")
{
PlayGame();
} else
{
break;
}
}
public static Random random = new Random();
public static int RollDice()
{
int Dice = random.Next(2, 4);
return Dice;
}
The console prints out:

The first issue is with you're not closing your Main method.
Add a closing bracket (}) before the static void PlayGame() line (and then remove the extraneous bracket after the PlayGame() function's definition).
You might want to reindent your code (that would have made the error glaringly obvious) - there's surely a menu item for that in your IDE.
Secondly, you can't use break when you're not in a loop; you'd use return to "break out" of a function.
Thirdly, you have an infinite loop without break in your PlayGame() method; you'll never get to that PlayAgain() call.

I sense that you are learning so here I give you something similar to what you appear to be trying. I will annotate with comments in the code but here is a basic rundown:
in the static void Main() you output some text first
Then in my version I create a boolean variable doIt and set it to "true" so that I can use that in the loop; looping until it is no longer true - and since I set it to true initially it does one "game" play with PlayGame();
Next I call the PlayAgain method which I changed to return a boolean from your players answer, setting "doIt" to the value: doIt = PlayAgain();
It starts the while loop again and if doIt is still true, plays again, otherwise it goes to the next statement (the "Goodbye") then returns exiting the program.
I formatted a bit and here is everything with LONG comments:
using System;
public class Program
{
static void Main()
{
Console.WriteLine("Hey! Welcome to Tina's Dice Game");
Console.WriteLine("Let's Start!");
bool doIt = true;
while (doIt)
{
PlayGame();
doIt = PlayAgain();
}
Console.WriteLine("Goodbye!");
return;
}
// here you had PayGame inside Main() so I left it there
// the main difference is I now call it ONLY from Main()
// since the other public methods cannot "see" it
// this fixes one of the issues
static void PlayGame()
{
bool doingWell = true;
while (doingWell)
{
int dice1 = RollDice();
int dice2 = RollDice();
Console.WriteLine("Dice 1 = " + dice1);
Console.WriteLine("Dice 2 = " + dice2);
Console.WriteLine("I got " + dice1 + " and " + dice2);
doingWell = (dice1 % 2 == 0 && dice2 % 2 == 0);
if (doingWell)
{
Console.WriteLine("Evens are better than odds");
}
else
{
Console.WriteLine("Odds are still cool.");
}
}
}
// public method, this returns a boolean from the check: answer == "Yes"
// goAgain is set to the true/false value of the condition it checked,
// returning true only when "Yes" is the answer
// Anything else like "YES","yes", "yep", or "no" returns false
// since this is a case sensitive comparison
// reference: https://learn.microsoft.com/en-us/dotnet/csharp/how-to/compare-strings
public static bool PlayAgain()
{
Console.Write("Do you want to play it again? (Yes or No)");
string answer;
answer = Console.ReadLine();
Console.WriteLine($"You said:{answer}");
var goAgain = answer == "Yes";
return goAgain;
}
// I put the "random" in the roll dice method so we create a new one each time
public static int RollDice()
{
Random random = new Random();
int dice = random.Next(2, 4);
return dice;
}
}

Related

solution needed with a homework c# (cs7036)

I am trying to make a menu with different options on replit where the user can choose an option.
I am making the options on seperate files, so I later can call for the methods from those files instead of writing everything in the main file.
One of these menuoptions will have an option with a random generator which will generate a random string.
I created the method on another file, But when it gave me an error (7036) when i tried to call it to the main method.
I have pasted an example of the code here below, But you can also access and run the code on this link: https://replit.com/#AY2002/testc22#main.cs Which will be easier to understand. I am a begginer and, Therefore seeking a simple answer.
Thank you!
//MAIN replit FILE
using System;
using System.Collections.Generic;
namespace Namespace1 {
// This is the main file where the menu is built. the menu is working fine.
// the menu have 4 options and an exit option, which will be divided into 4 different replit files and one of them will have a method that randomly generates a string. you can see the method when you scroll down near to the bottom of the main file.
class Program {
public static void Main (string[] args)
{
string[] Menuchoises = new string [] {"Choise1","Choise2","Choise3","Choise4","Choise5"};
int x = 0;
while (true){
Console.Clear();
Console.WriteLine("welcome to menu");
Console.WriteLine();
Console.CursorVisible = false;
if(x == 0) {
Console.WriteLine(" " + Menuchoises[0] + " {");
Console.WriteLine(Menuchoises[1]);
Console.WriteLine(Menuchoises[2]);
Console.WriteLine(Menuchoises[3]);
Console.WriteLine(Menuchoises[4]);
}
else if(x == 1) {
Console.WriteLine(Menuchoises[0]);
Console.WriteLine(" " + Menuchoises[1] + " {");
Console.WriteLine(Menuchoises[2]);
Console.WriteLine(Menuchoises[3]);
Console.WriteLine(Menuchoises[4]);
}
else if(x == 2) {
Console.WriteLine(Menuchoises[0]);
Console.WriteLine(Menuchoises[1]);
Console.WriteLine(" " + Menuchoises[2] + " {");
Console.WriteLine(Menuchoises[3]);
Console.WriteLine(Menuchoises[4]);
}
else if(x == 3) {
Console.WriteLine(Menuchoises[0]);
Console.WriteLine(Menuchoises[1]);
Console.WriteLine(Menuchoises[2]);
Console.WriteLine(" " + Menuchoises[3] + " {");
Console.WriteLine(Menuchoises[4]);
}
else if(x == 4) {
Console.WriteLine(Menuchoises[0]);
Console.WriteLine(Menuchoises[1]);
Console.WriteLine(Menuchoises[2]);
Console.WriteLine(Menuchoises[3]);
Console.WriteLine("\t" + Menuchoises[4] + " {");
}
var key = Console.ReadKey();
if (key.Key == ConsoleKey.DownArrow && x != Menuchoises.Length -1) {
x++;
}
else if (key.Key == ConsoleKey.UpArrow && x>=1) {
x--;
} else if (key.Key == ConsoleKey.Enter) {
switch (x) {
case 0:
Menuchoise1();
break;
case 1:
Menuchoise2();
break;
case 2:
Menuchoise3();
break;
case 3:
Menuchoise4();
break;
case 4:
Menuchoise5();
break;
}
}
}
}
public static void Menuchoise1() {
// Class2.second is the name of the second class which will be the method that will appear when you choose the 1st option in the menu.
// The second class is in the second file which you`ll see below the main file
// The CS 7036 error seems to be appearing here
Class2.second();
Console.Clear();
Console.ReadKey();
}
public static void Menuchoise2() {
Console.Clear();
Console.ReadKey();
}
public static void Menuchoise3() {
Console.Clear();
Console.ReadKey();
}
public static void Menuchoise4() {
Console.Clear();
Console.ReadKey();
}
public static void Menuchoise5() {
Console.Clear();
Console.WriteLine("press enter to exit the menu");
Console.ReadKey();
Console.Clear();
Environment.Exit(1);
}
}
}
// SECOND replit FILE
//this is the second file where i have the random value generator.
using System;
using System.Collections.Generic;
namespace Namespace1 {
// class name of the second file
public class Class2 {
// the string[]args function that will later be put in the main file in order to use this method in the menu
public static string second(string[] Random) {
string[] RandomChoises = new string [4];
// list on options which will be randomly generated
RandomChoises[0] = "C1";
RandomChoises[1] = "C2";
RandomChoises[2] = "C3";
RandomChoises[3] = "C4";
RandomChoises[4] = "C5";
for (int i = 0; i < RandomChoises.Length; i++)
{
Console.WriteLine(RandomChoises[i]);
}
// the choises are randomly generated here
Random rnd = new Random();
int Randomanswer = rnd.Next(1,RandomChoises.Length);
Console.WriteLine("You got the answer: " + RandomChoises[Randomanswer]);
return Convert.ToString(Randomanswer);
}
}
}
As mentioned in the comments, the problem is that the second method takes a parameter, but is not called with one. Since the parameter is not used it should be removed. Cleaning up the class a bit should give you something like:
public static class RandomHelpers{
public static string GetRandomValue() {
// use collection initializer
string[] choices= new []{"C1","C2","C3","C4","C5"}
// use foreach loop
foreach(var choice in choices){
Console.WriteLine(choice );
}
// You should probably not recreate the random object for each method call
// But this should work fine for demonstration purposes
Random rnd = new Random();
// start from zero
int randomIndex = rnd.Next(0,RandomChoises.Length);
var randomValue = choices[randomIndex];
// You should probably just return the random value,
// and let the caller print it to console.
Console.WriteLine("You got the answer: " + randomValue );
// Either return the index as an int, or the value as a string
// Do not convert numbers to strings unless you are writing to the console/file
return randomValue ;
}
}
This should work better. As you get more experience you should find better ways to split functionality into reusable methods.
You have an issue with the way you are defining the array in second.cs. You either need explicitly say how many elements your array will have, like this:
string[] RandomChoice = new string[5];
Or you can leave the number out and let the compiler infer it from the number of elements you put in the {}, like this:
string[] RandomChoises = new string[] { "C1", "C2", "C3", "C4", "C5" };
You can read more details about declaring arrays in C# here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/
After you fix that see JonasH answer about the method parameters in second().

Multiple errors in c# having trouble resolving

using System;
namespace VSCode
{
class Program
{
static void Main()
{
//Terminal Settings
Console.Title = "Dungeon Crawler";
Console.WindowHeight = 40;
Console.WindowWidth = 150;
//vars
int playerHP = 10;
string armorType = "Leather Tunic";
int armorValue = 1;
string weaponType = "Wooden sword";
int weaponDMG = 2;
int gold = 100;
string enemyType;
int enemyHP;
int enemyArmor;
int enemyDMG;
Console.WriteLine("Type 'start' to start the game");
if(Console.ReadLine() == "start")
{
DungeonCrawlersIntro();
}
void DungeonCrawlersIntro()
{
//intro
Console.WriteLine("---Welcome To Dungeon Crawler!");
Console.WriteLine("---Press Any Key to get the next line---");
Console.ReadKey(true);
Console.WriteLine("---Dungeon Crawler is a game made by YaLocalJesterBoi AKA Addi-O---");
Console.ReadKey(true);
Console.WriteLine("---It is a simple pure text RPG that I am working on alone with minimal yt help and the like. its just me making this thing for fun---");
Console.ReadKey(true);
Console.WriteLine("---Anyways, enjoy!");
Console.ReadKey(true);
Console.WriteLine("---You are an adventurer who has come from far away in order defeat the dungeon of the gods, 'Malakeith'---");
Console.ReadKey(true);
Console.WriteLine("--Like most other adventurers, all you want is money and loot. To be the strongest of them all---");
Console.ReadKey(true);
Console.WriteLine("---Currently you have " + playerHP + " HP " + armorType + " armor type that gives " + armorValue + " armor and " + gold + " Gold along with a " + weaponType + " that deals " + weaponDMG + " Attack damage---");
Console.ReadKey(true);
Console.WriteLine("---The dungeon Malakeith is quite famous and has a dfficulty all the from 'F' rank adventurers adventuring, to S class adventurers comeing to beat the dungeon entirely---");
Console.ReadKey(true);
Console.WriteLine("---You, just like many other ambitious adventurers just want some money and loot to live your life lavishly---");
Console.ReadKey(true);
Console.WriteLine("---The Dungeon itself is extremely popular, garnering people from all pver the world to explore it, but the selling point isn't just the dungeon itself, but the city that has been created around it. Malakeith city is well known as the best place to buy and sell anything obtained, or used in adventuring, all the way from a godly sword, to a simple health potion sold by every peddler---");
Console.ReadKey(true);
Console.WriteLine("---Type '/dungeon' to go to the dungeon---");
Console.WriteLine("---If you dont comply the game will simply shut down---");
if(Console.ReadLine() == "/dungeon")
{
Dungeon();
}
else
{
Console.WriteLine("---Since you were messing around, you got mugged and killed---");
Console.ReadKey();
playerHP = playerHP - 10;
if(playerHP < 1)
{
return;
}
}
}
void Dungeon()
{
Console.WriteLine("---You have entered the very first floor of the Malakeith dungeon!---");
Console.ReadKey(true);
Console.WriteLine("As you enter, you get transported into an iteration of the dungeon, totally randomized each time for every adventurer or party---");
Console.ReadKey(true);
Console.WriteLine("---The inside seem to be meadows, stretching on beyond the horizon---");
Console.ReadKey(true);
Console.WriteLine("---The only residents of this area are slimes and some other petty creatures such as goblins and the occasional goblin leader---");
Console.ReadKey(true);
Console.WriteLine("---One such resident of this area has decided to have a shit at killing you---");
Console.ReadKey(true);
enemyRoll();
}
void enemyRoll()
{
Random enemyRollValue = new Random();
int roll = 0;
roll = enemyRollValue.Next(1,7);
while(roll > 3)
{
goblinFight();
}
else
{
slimeFight();
}
}
void goblinFight()
{
enemyType = "goblin";
enemyHP = 5;
enemyArmor = 0;
enemyDMG = 4;
Console.WriteLine("---This resident that has come to fight is a " + enemyType + "---");
Console.ReadKey(true);
Console.WriteLine("It has " + enemyHP + " HP");
Console.ReadKey(true);
Attack();
}
void slimeFight()
{
enemyType = "slime";
enemyHP = 3;
enemyArmor = 0;
enemyDMG = 2;
Console.WriteLine("---This resident that has come to fight is a " + enemyType + "---");
Console.ReadKey(true);
Console.WriteLine("It has " + enemyHP + " HP");
Console.ReadKey(true);
}
void Attack()
{
enemyHP = (enemyHP + armorValue) - (weaponDMG + extraATK);
}
void AddAttack()
{
Random addAttack = new Random();
int extraATKRoll = 0;
extraATKRoll = addAttack.Next(1,10);
while(extraATKRoll >= 5)
{
public static int extraATK = 1;
}
}
}
}
}
it's a hundred something line of code that i've written for my pet project, dungeon crawlers. It's just a simple pure text RPG game made in VSCode alone that i've been making to brush up my skills and typing speed and to make me just more comfortable with VSCode.
there's a couple errors that i'm having that i cant seem to find the answers to. I have tried the stuff i found online, but to no avail.
the error messages are as follows:
} expected [VSCode]
} expected [VSCode, VSCode, VSCode]
Type or namespace definition, or end-of-file expected [VSCode]
Type or namespace definition, or end-of-file expected [VSCode]
Type or namespace definition, or end-of-file expected [VSCode]
The variable 'enemyArmor' is assigned but its value is never used [VSCode]
The variable 'enemyDMG' is assigned but its value is never used [VSCode]
The local function 'AddAttack' is declared but never used [VSCode]
The strange thing with enemy armor is that there are other ints and and strings that are declared and used in the exact same place with no difference(that i see) in use or writing. the main issue is with the '}' because previously the only problem was that there was 1 where it required 1 extra '}' because i messed up, but after that as i wrote more and more code, there were more of these popping up. i tried whatever i could find and havent been able to get further ahead. i have copy pasted some of my code from a previous iteration of the game that i scrapped for too much sphaghetti.
Do keep in mind that i'm pretty new to coding and not very good at it, so please put your answers in terms a new coder would understand
Let's go through this one at a time:
void enemyRoll()
{
Random enemyRollValue = new Random();
int roll = 0;
roll = enemyRollValue.Next(1,7);
while(roll > 3)
{
goblinFight();
}
else
{
slimeFight();
}
}
There's an else that isn't prefixed with an if block. Change the while to an if block to resolve the issue
void enemyRoll()
{
Random enemyRollValue = new Random();
int roll = 0;
roll = enemyRollValue.Next(1,7);
if(roll > 3)
{
goblinFight();
}
else
{
slimeFight();
}
}
Next error:
void AddAttack()
{
Random addAttack = new Random();
int extraATKRoll = 0;
extraATKRoll = addAttack.Next(1,10);
while(extraATKRoll >= 5)
{
public static int extraATK = 1;
}
}
You cannot create a global variable (i.e. extraATK) inside a method. Define extraATK below int enemyDMG like int extraATK = 0;
After converting the while to if, the function should look like:
New function should look like:
void AddAttack()
{
Random addAttack = new Random();
int extraATKRoll = 0;
extraATKRoll = addAttack.Next(1,10);
if(extraATKRoll >= 5)
{
extraATK = 1;
}
}
This should resolve the issues.
Firstly, you have the following; you can't else a while statement
while(roll > 3)
{
goblinFight();
}
//Comment out this mess, or do something else with it
//else
//{
// slimeFight();
//}
Secondly, you are trying to declare a static member inside a while statement.. Once again it doesn't make sense:
while(extraATKRoll >= 5)
{
// this doesn't make sense, comment it out
//public static int extraATK = 1;
}
You need to put it directly in the class (at least):
class Program
{
public static int extraATK = 1;
Things go pear-shaped at that enemyRoll method. You have a while statement followed by an else statement. You seem to be missing an if somewhere but it's impossible to know for sure what you intended there.
Changing the while to an if fixed that issue but you still have another problem. In the AddAttack method you have another while loop and inside that you try to declare a static field, which makes no sense at all.

Learning by doing a project

I have typed up some code to try and practice what I have learned in my programming course. Something is wrong with my logic as I am not getting the answer I am supposed to get.
I have searched and google and rewatched the training videos but nothing seems to help.
namespace TenPinBowling
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.Write("Would you like to bowl, Y or N: ");
var answer = Console.ReadLine();
if (answer == "n")
{
Console.WriteLine("Thanks for playing, press any to exit :)");
Console.ReadKey();
break;
}
Score();
}
}
static void Score()
{
{
Random pins = new Random();
var pinsKnockedDown = pins.Next(0, 10);
//var totalScore = 0;
Console.WriteLine("You bowled a: " + pinsKnockedDown);
//var result = totalScore + pinsKnockedDown;
Console.WriteLine("You're total score is: " + Tally(pinsKnockedDown));
}
}
static int Tally(int score)
{
{
int result = 0;
result = result + score;
return result;
}
}
}
}
I was hoping my second method would keep a running total of my score but it resets to the individual score every time.
In
static int Tally(int score)
{
{
int result = 0;
result = result + score;
return result;
}
}
you create a new local variable result each time you invoke the method, so the record of past scores is lost. Making result a field of the class would allow it to persist for the duration of the game. A minimal code change might be:
private static int result = 0;
static int Tally(int score)
{
result = result + score;
return result;
}
I would guess you always need to keep track of your total score, if it should not reset. Right now you always add the current score to zero (in Tally). If you put int result outside of tally it should keep track accordingly.

C# I'm having trouble with a dice game where I need to increment a value every time a user plays a game and then print it back to them

I have a dice game which holds two dice and what happens is that one game will go through and then the user will be asked if they want to play again. If, for example, they said yes three times then when they say no at the end to exit the game, they'll get an output telling them how many times they played the game. I'm having trouble coming up with the code for it.
I don't have much experience using parameters and return types(this is a beginner assignment) but I currently have a counter which adds 1. The problem is that it starts at 0 and goes to 1, and then stays there.
Here's the code I have that runs through the game:
namespace MajorAssignment1
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hey! Welcome to Ray's Dice Game! Let's Start");
Console.WriteLine();
EvenOrOdds();
}
public static void EvenOrOdds()
{
Random rnd = new Random();
int die1 = rnd.Next(1, 10);
int die2 = rnd.Next(1, 10);
Console.WriteLine("Die 1 = {0} and Die 2 = {1}", die1, die2);
Console.WriteLine();
Console.WriteLine("You Rolled {0} and {1}", die1, die2);
Console.WriteLine();
if ((die1 + die2) % 2 == 0)
{
Console.WriteLine("Evens are better than odd.");
Console.WriteLine();
}
if ((die1 + die2) % 2 > 0 )
{
Console.WriteLine("Odds are still cool.");
Console.WriteLine();
}
Console.WriteLine("Do you want to play again? Please enter in all caps YES or NO");
String UserInput = Console.ReadLine();
var Counter = 0;
if (UserInput == "YES")
{
EvenOrOdds();
Counter = Counter + 1;
}
else
{
Console.WriteLine("The number of times the dice was thrown is:" + Counter);
Console.WriteLine();
}
}
public static void Outro()
{
Console.WriteLine("Thanks for playing! Come again!");
Console.WriteLine();
}
}
}
By calling EvenOrOdds() from within itself in order to "play again", you are effectively creating a recursive call to the function.
You are re-defining Counter within the scope of each instance of EvenOrOdds() you are calling, resulting in Counter always ending up as 1.
One easy option is to move the definition of Counter out into a class-level variable, which then means it will be shared between all your calls to EvenOrOdds()
class MainClass
{
//class-level static variable
private static int Counter;
public static void Main(string[] args)
{
Console.WriteLine("Hey! Welcome to Ray's Dice Game! Let's Start");
Console.WriteLine();
EvenOrOdds();
}
// rest of code here
Which then means you can remove the definition of Counter within your EvenOrOdds() code. Now when you increment Counter it is updating the class-level variable, which will result in your expected Counter behaviour.
Console.WriteLine("Do you want to play again? Please enter in all caps YES or NO");
String UserInput = Console.ReadLine();
if (UserInput == "YES")
{
//increment the counter first
Counter = Counter + 1;
//then call the method again for a new game
EvenOrOdds();
}
Also you could change "Counter = Counter + 1;" line you use the inline ++ increment operator: "Counter++ ;" which will do the same thing.
Note: There are other ways to implement this type of "play again" functionality which would be better, such as using loops etc, but without rewriting what you have already done significantly my advice above will suffice as a minor change that achieves what you want to do. Good luck!
Edit: Updated to increment Counter first, before calling EventOrOdds() again - which results in Counter being correctly incremented for each game played.
Problem with your code is that you are calling EvenOrOdds() recursively, and counter never increments. Moreover, you are doing simple things in a complicated way, I have simplified few things.
Working code:
using System;
public class diceCounter
{
public static void Main(string[] args)
{
String UserInput;
int Counter =1;
Console.WriteLine("Hey! Welcome to Ray's Dice Game! Let's Start");
Console.WriteLine();
do
{
EvenOrOdds();
Console.WriteLine("Do you want to play again? Please enter in all caps YES or NO");
UserInput = Console.ReadLine();
if (UserInput.Equals("YES"))
{
Counter++;
EvenOrOdds();
}
}while(!(UserInput.Equals("NO")));
Console.WriteLine("The number of times the dice was thrown is: " + Counter);
Outro();
}
public static void EvenOrOdds()
{
Random rnd = new Random();
int die1 = rnd.Next(1, 10);
int die2 = rnd.Next(1, 10);
Console.WriteLine("Die 1 = {0} and Die 2 = {1}", die1, die2);
Console.WriteLine();
Console.WriteLine("You Rolled {0} and {1}", die1, die2);
Console.WriteLine();
if ((die1 + die2) % 2 == 0)
{
Console.WriteLine("Evens are better than odd.");
Console.WriteLine();
}
if ((die1 + die2) % 2 > 0 )
{
Console.WriteLine("Odds are still cool.");
Console.WriteLine();
}
}
public static void Outro()
{
Console.WriteLine("\nThanks for playing! Come again!\n");
}
}
I can come up with two solutions
1) use a private variable at class level. Remember to remove the definition for counter at your method
class MainClass {
private static int Counter = 0;
...
}
2) send a ref parameter to your method
public static void EvenOrOdds(ref int counter)
and in main
EventOrOdds(counter). the same goes for your recursion

How do I get a local variable from one function and use it for a different function in my code?

I am making a slot machine, and I want the var 'bet' in betValidation() to be used in the result() function. My goal is if two of the random number generated in firstRandomNumberGenerator() are the same, the bet that the player bets will be tripled and will be added back to his current amount of chips. ): But in order to do that, I'll need to get bet (a local variable) and place it in result() but I don't know how.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace randomProjectTAKE3
{
class Program
{
static void Main()
{
float playerChips = 1000;
Console.Write("Player's Chips: ");
Console.WriteLine(playerChips);
Console.Write("1. Play Slot ");
Console.WriteLine("2. Exit");
choice();
result();
Console.ReadKey();
}
static void Update()
{
}
static void choice()
{
float choice = float.Parse(Console.ReadLine());
if (choice == 1)
{
firstRandomNumberGenerator();
}
else if (choice == 2)
{
return;
}
}
static void betValidation()
{
float playerChips = 1000;
float currentPlayerChips;
Console.WriteLine("Enter your bet: ");
**var bet = float.Parse(Console.ReadLine());**
if ((bet <= 0) || (bet > playerChips))
{
Console.WriteLine("You did not enter a valid bet.\n");
Main();
}
}
static void firstRandomNumberGenerator()
{
betValidation();
Random r = new Random();
int firstNumber = r.Next(2, 8);
int secondNumber = r.Next(2, 8);
int thirdNumber = r.Next(2, 8);
Console.Write(firstNumber);
Console.Write(secondNumber);
Console.Write(thirdNumber);
Console.Write("\n");
}
**static void result()**
{
}
}
}
There is a few ways to make this happen, one way is to move the bet into the scope of the program as a field (the name _currentBet would be useful), rather than declared in the function so it can be referenced as many times as needed.
Then when the player places the bet, you can parse and assign to the variable. This would also be ideal with your player's chips.
class Program
{
private float _playersChips = 1000;
private float _currentBet;
static void Main()
{
//So on and so forth.
}
}
The only idea I have is to pass the variable By Reference from a method to another,
check this link
Wow, ok... so are you familiar with Global Variables?
Looking at your code, you're writing a console application in a procedural (rather than object-oriented) style... Whilst this can be done in C#, for larger applications, it can make code maintenance a big headache.
Regardless, I'll try and help you out...
Miles's answer is essentially using a Global Variable instead of a local one, which is a good suggestion when programming in a procedural style, however, another option for you is to make playerChips a reference method parameter (as suggested by Hussein) which can be passed (and modified) between methods... so (using both of their suggestions) your code would change to work as follows:
class Program
{
public static float _playerChips = 1000;
private static void Main()
{
Console.Write("Player's Chips: ");
Console.WriteLine(_playerChips);
Console.Write("1. Play Slot ");
Console.WriteLine("2. Exit");
choice(ref _playerChips);
result(_playerChips);
Console.ReadKey();
}
private static void choice(ref float playerChips)
{
int choice = int.Parse(Console.ReadLine());
if (choice == 1)
{
firstRandomNumberGenerator(ref playerChips);
}
if (choice == 2)
Environment.Exit(0);
}
private static void betValidation(ref float playerChips, ref float bet)
{
Console.WriteLine("Enter your bet: ");
bet = float.Parse(Console.ReadLine());
if ((bet <= 0) || (bet > playerChips))
{
Console.WriteLine("You did not enter a valid bet.\n");
Main();
}
}
private static void firstRandomNumberGenerator(ref float playerChips)
{
float bet = 0;
betValidation(ref playerChips, ref bet);
System.Random r = new System.Random();
int firstNumber = r.Next(2, 8);
int secondNumber = r.Next(2, 8);
int thirdNumber = r.Next(2, 8);
if (firstNumber == secondNumber || firstNumber == thirdNumber || thirdNumber == secondNumber)
playerChips = playerChips + (bet * 3);
Console.Write(firstNumber);
Console.Write(secondNumber);
Console.Write(thirdNumber);
Console.Write("\n");
}
private static void Update()
{
return;
}
private static void result(float playerChips)
{
return;
}
}
Now, I've also changed the choice() method you wrote to call Environment.Exit() and exit the program - the reason for this is, by executing Main() you're essentially calling methods within methods within methods and increasing your stack which will eventually lead to a Stack Overflow... I would consider changing your Main() method to use a loop based on choice() returning a result rather than just calling Main() from the betValidation method again (however I have not done this for you).

Categories

Resources