I've only been learning C# for a couple days and I was wondering how I would call Main to restart the program when the player says 'yes' during the switch statement (when he is asked to play again)
public static void Main(string[] args)
{
Console.WriteLine("Choose a gun to shoot at Toaster... ");
Console.Write("rocket/sniper/rifle/pistol: ");
string playersGunChoice = Console.ReadLine();
Random randomweapondmg = new Random();
int weapondmg = 0;
switch (playersGunChoice.ToLower())
{
case "rocket":
Console.WriteLine("You chose a rocket.");
weapondmg = randomweapondmg.Next(75, 200);
Console.WriteLine("Your rocket does " + weapondmg + " to Toaster.");
break;
case "sniper":
Console.WriteLine("You chose a sniper.");
weapondmg = randomweapondmg.Next(50, 150);
Console.WriteLine("Your sniper does " + weapondmg + " to Toaster.");
break;
}
int ToasterHealth = 500;
int ToastersLeftHp = ToasterHealth - weapondmg;
Console.WriteLine("Toaster has " + ToastersLeftHp + " healthpoints left.");
if (ToastersLeftHp != 0)
Console.WriteLine("Shoot at Toaster again?");
Console.Write("yes/no: ");
string PlayAgain = Console.ReadLine();
switch(PlayAgain.ToLower())
{
case "yes": //I want to call main here somehow
break;
case "no":
break;
default:
Console.WriteLine("That wasn't a yes or no.");
break;
}
if (ToastersLeftHp == 0)
Console.WriteLine("You killed Toaster!");
else if (ToastersLeftHp < 100)
Console.WriteLine("Toaster is almost dead! He has " + ToastersLeftHp + " healthpoints left.");
}
}
}
You call it the same way you call any other method. You write the name and pass it the arguments it expects:
Main(string[]{});
If you don't want the program to continue doing what it was doing after it finishes calling Main, you'd want to make sure that it stops executing gracefully after that point.
Having said all of that, making Main recursive isn't exactly a solution to that problem that I would advise. I'd strongly suggest simply applying a loop in your main method that continually performs the logic that you have until you want it to stop, and have each iteration of the loop finish when you either need to restart, or are completely done.
As a guideline you should try some online tutorials to help you write proper code.
Try avoiding calling the main method as it is the starting point for your program, instead use a different function or even better a different class to represent the game. this function\class can call it self or add an inner loop that runs until the game is 'done'.
Also consider dividing the code into smaller functions, it would be more maintainable and readable.
Related
I'm pretty new to C#, and programming overall. I'm doing a homework assignment right now and I'm losing my mind because I can't wrap my head around what my error here is. I feel like it's got to be something so obvious but I just can't see it. The errors are "ProgramBase.Menu()", "The name 'Console'does not exist in the current context", "QuestionRectangle does not exist in the current context".
using System;
namespace ProgLab3
{
class Program
{
static void Main(string[] args)
{
bool displayMenu = true;
while (displayMenu)
{
displayMenu = Menu();
}
}
private static bool Menu()
{
Console.Clear();
Console.WriteLine("Welcome to the menu! Below are your choices of options.");
Console.WriteLine("Type 1 to open Areas of Rectangles\n");
Console.WriteLine("Type 2 to open Biggest Number\n");
Console.WriteLine("Type 3 to open Valid Points\n");
Console.WriteLine("Type 4 to open Dollar Game\n");
Console.WriteLine("Type 5 to open Oldest Person\n");
Console.WriteLine("Type 6 to open Hi Lo Game\n");
Console.WriteLine("Type 7 to quit\n");
switch (Console.ReadLine())
{
case "1":
QuestionRectangle();
return true;
case "2":
return true;
case "3":
return false;
default:
return true;
}
}
private static void QuestionRectangle()
{
{
double width1, length1, area1;
double width2, length2, area2;
// Asking the user for measurements and then saving those numbers onto variables for the FIRST rectangle
Console.WriteLine("Welcome to the Areas of Rectangles choice.\nPlease start off by inputting the width of your first rectangle, do not include the metric unit of measurement.");
width1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Now please input the length of the first rectangle.");
length1 = Convert.ToDouble(Console.ReadLine());
//Calculating the area of the FIRST rectangle
area1 = width1 * length1;
// Asking the user for measurements and then saving those numbers onto variables for the SECOND rectangle
Console.WriteLine("Alright great, now please input the width of your second rectangle.");
width2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Now what is the length of your second rectangle?");
length2 = Convert.ToDouble(Console.ReadLine());
//Calculating the area of the SECOND rectangle
area2 = width2 * length2;
// Checks if area 1 is greater than area 2
if (area1 > area2)
{
Console.WriteLine("Your first rectangle has a greater area, that area being " + area1);
}
// Checks if area 2 is greater than area 1
if (area1 < area2)
{
Console.WriteLine("Your second rectangle has a greater area, that area being " + area2);
}
// Checks if the areas are equal to each other
if (area1 == area2)
{
Console.WriteLine("Your rectangles have the same area, that area being " + area1);
}
}
}
}
}
The error is telling you that Console/QuestionRectangle is not reachable in the current context. This can mean one or more of the following:
you have a typo
the resource is not defined in the current namespace
the resource exists in another namespace which is not included using the using keyword
So, you will need to check your namespaces and fix the problems you have accordingly. I can see that QuestionRectangle is defined in your code, so I suppose that the actual code you have is either different, or has the problem at a place which was not shared.
EDIT
It turns out that in this particular case the copied content was corrupted along the way. carsonSgit looked into the issue and was able to localize what was missing. From then point on it was easier for him/her to find the path to the solution, by ensuring that the source and the target is identical.
I'm making a text based adventure game in the command prompt, and I need to add in a way to keep track of any coins they collect by entering a certain room, and if they pick up the one and only weapon in the maze.
If they have enough coins or the weapon then they can complete the game. If they don't they die.
I have almost finished the game I just don't know the best way to add in a way of tracking the amount of coins they have or if they have been in the weapon room.
static void Main(string[] args)
{
GameTitle();
Start();
}
public static void GameTitle()
{
Console.WriteLine("Welcome to The Maze.");
Console.WriteLine("Press 'Enter' to start.");
Console.ReadLine();
Console.Clear();
Start();
}
public int coins = 0; // Keeps track of coins
public bool weapon = false;
public static void Start()
{
string choice;
Console.WriteLine("You slowly wake up in an old, decrepit abandoned building. You get the immediate sense you're in an insane asylum.");
Console.WriteLine("You look around and there are three doors directly in front of you in the eerily silent room.");
Console.WriteLine("A sign on the wall reads:");
Console.WriteLine("Choose carefully, once a door is opened, it will never open again.");
Console.WriteLine("Which door do you choose");
Console.WriteLine("1. The door to the left.");
Console.WriteLine("2. The door to the right.");
Console.WriteLine("3. The door in front of you.");
Console.Write("Choice: ");
choice = Console.ReadLine().ToLower();
Console.Clear();
switch (choice)
{
case "1":
case "left":
{
A();
break;
}
case "2":
case "right":
{
C();
break;
}
case "3":
case "front":
{
B();
break;
}
}
}
Just if they find a coin:
coins++;
And if they enter the room:
weapon = true;
You could just store the coins in the coins variable and use the weapons Boolean to know whether or not they have been in that room.
Or you could use a JSON file if you like, that would look a bit more professional but also edit-able on the user's end.
So i am trying to create a simple text adventure in unity and i have written a script the changes the state of the text depending on key presses. To try and add a bit of complexity i have attempted to add a system where when in one state it is displayed that an item is picked up and the variable for that item has been set to true which is stated at the top of the script. Then, when the user next enters a different state it is checked to see if the variable is true or false in which if the variable is true different text will be displayed to if it where false. My issue is that every time i enter the state withe the IF statements the variable is automatically set to false no matter what. An answer would be more than appreciated :).
Engine:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class TextController : MonoBehaviour {
public Text text;
private enum states {cell, floor, CellDoor, mirror, bed, rock, shard};
private states myState;
bool rock;
bool shard;
// Use this for initialization
void Start () {
rock = false;
shard = false;
myState = states.cell;
}
// Update is called once per frame
void Update () {
print (myState);
if (myState == states.cell){
state_cell ();
}else if (myState == states.floor){
state_floor ();
}else if (myState == states.CellDoor){
state_CellDoor ();
}else if (myState == states.mirror){
state_mirror ();
}else if (myState == states.bed){
state_bed ();
}else if (myState == states.rock){
state_rock ();
}else if (myState == states.shard){
state_shard ();
}
}
Variable change:
void state_rock (){
rock = true;
text.text = "You conjure what strength you have and eagerly pry at a slightly loose looking part of the concrete " +
"with your blistered hands. Finally a piece breaks free, you drop it into one of your pockets.\n\n" +
"You have obtained a rock! \n\n" +
"Press R to return to the cell.";
if (Input.GetKeyDown(KeyCode.R)){
myState = states.cell;
}
print(rock);
Statements that don't work:
void state_mirror (){
print (rock);
if (rock = true);{
text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
"wielding a shard could prove useful. You remember the hefty chunk of concrete in your pocket. \n\n" +
"Press T if you would like to throw the rock at the mirror or R if you would like to return to the cell";
}
if (rock = false);{
text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
"wielding a shard could prove useful. You are unable to think of any way of shattering the mirror " +
"as it is rigidly screwed into the wall, perhaps a blunt object would do the trick?. \n\n" +
"Press R to return to the cell.";
}
if (Input.GetKeyDown(KeyCode.R)){
myState = states.cell;
}
if (Input.GetKeyDown(KeyCode.T)){
myState = states.shard;
}
}
Console saying item is obtained, 'true'
Console saying that the item has not been obtained for some reason, 'false'
Well, there are several problems in your script.
Lets start with this :
if (rock = true);{...
You need to realize that you are assign rock = true, you need to use double equals to compare. Even more, is advisable to use if(boolVar) , because automatically will execute if it's true.
if(rock){ do something }
//is the same that
if(rock == true){}
Also, another important thing, is that you should not put a ; after the if, because when you do that the code inside the brackets will not be related to the conditional.
There are some obvious problems with these statements.
if (rock = true);{
text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
"wielding a shard could prove useful. You remember the hefty chunk of concrete in your pocket. \n\n" +
"Press T if you would like to throw the rock at the mirror or R if you would like to return to the cell";
}
if (rock = false);{
text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
"wielding a shard could prove useful. You are unable to think of any way of shattering the mirror " +
"as it is rigidly screwed into the wall, perhaps a blunt object would do the trick?. \n\n" +
"Press R to return to the cell.";
}
You don't put a semicolon at the end of an if, and the = sign by itself, asigns the value on the right to the variable on the left before it is evaluated. So change the single = to a ==.
Your code becomes,
if (rock == true){
text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
"wielding a shard could prove useful. You remember the hefty chunk of concrete in your pocket. \n\n" +
"Press T if you would like to throw the rock at the mirror or R if you would like to return to the cell";
}
if (rock == false){
text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
"wielding a shard could prove useful. You are unable to think of any way of shattering the mirror " +
"as it is rigidly screwed into the wall, perhaps a blunt object would do the trick?. \n\n" +
"Press R to return to the cell.";
}
Though a better way to write this would be,
if (rock) // is the same as if rock == true
{
text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
"wielding a shard could prove useful. You remember the hefty chunk of concrete in your pocket. \n\n" +
"Press T if you would like to throw the rock at the mirror or R if you would like to return to the cell";
}
else // is the same as if rock == false (in this case)
{
text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
"wielding a shard could prove useful. You are unable to think of any way of shattering the mirror " +
"as it is rigidly screwed into the wall, perhaps a blunt object would do the trick?. \n\n" +
"Press R to return to the cell.";
}
I have problem with my C# Bowling game and I would appericate some help I'll try to explain the code as well as i can. I've been trying to solve this issue for a long time and no success yet.
The calculation works fine but the only problem is my strike, the strike should count 10 + the next 2 coming throws.
So what my program does:
if you get a strike the first value will be set to 10, then I enter another strike and value is set to 21 but should be 20. The second box should then have a value of 30.
So first I have 3 arrays to hold all the textboxes
summa = new TextBox[] { textBox14, textBox15, textBox16, textBox17, textBox18, textBox19 };
slag1 = new TextBox[] { textBox1, textBox3, textBox5, textBox7, textBox9, textBox11 };
slag2 = new TextBox[] { textBox2, textBox4, textBox6, textBox8, textBox10, textBox12 };
So I have 2 methods, Slag1() and Slag2() the strike runs in the Slag1() method.
This is the part i use for the calculation of the strike
if (strike == true)
{
GotStrike[omgang] = true;
}
//strike = false;
//Kollar ifall textbox är lika med 10
if (slag1[omgang].Text == "10")
{
//Om text box är lika med 10 ändra värdet till X
//Lägg till 10 poäng på total
//Skriv ut värdet på summa (textbox)
Arbetar = true;
slag1[omgang].Text = "X";
total += 9;
summa[omgang].Text = total.ToString();
omgang++;
if (omgang == 6)
{
omgang--;
}
strike = true;
}
else if (slag1[omgang].Text == "X")
{
return;
}
else
{
checkSlag1 = Convert.ToInt32(slag1[omgang].Text);
total += checkSlag1;
summa[omgang].Text = total.ToString();
if (strike == true)
{
if (omgang != 0)
{
total += 10;
slag1[omgang - 1].Text = total.ToString();
if (omgang != 1)
{
slag1[omgang - 2].Text = total.ToString();
}
else
{
}
}
else
{
}
}
}
}
It's kinda hard to explain but I hope you understand, please tell me if you don't understand so I'll write a better explanation.
I hope you know how a bowling game works, a strike = the first strike and the value of the next 2 coming strikes. So if i hit a strike i get the value of 10, strike 2 value of 10 and strike 3 value of 10. That's the total of index 0.
Since you are having trouble with calculating the correct score for the bowling game, I would suggest to take out the bowling game mechanics, write tests that check if the different throws work correctly (ie normal, spare and strike). Then you can tinker with the code and when all tests pass, your scoring works. After that you can create any UI that uses the bowling game.
Also check the link I provided in the comment. The code is in Java but it is similar enough to C# and gives an example for a bowling game API with reasoning how they got to their particular design.
Your bowling game could look like this:
(I don't really know the bowling rules)
public class Bowling
{
public void Throw(int count) // How do you call these things that you need to knock over...
{
Debug.Assert(count >= 0);
Debug.Assert(count <= 12);
// ... Lots of interesting code.
}
public int GetScore()
{
return 16;
}
}
This code obviously doesn't work. The trick is to write tests that run "red" (=fail) and then to write code until the tests run "green" (=pass).
For these tests you can use a framework such as NUnit, ...
[TestClass]
public class BowlingTests
{
[Test]
public void ThrowNormal_NormalScore()
{
var b = new Bowling();
b.Throw(5);
b.Throw(6);
Assert.That(b.GetScore(), Is.EqualTo(11));
}
public void ThrowSpare_SpecialScore()
{
var b = new Bowling();
b.Throw(1);
b.Throw(11); // = spare
b.Throw(5); // score counts for double?
b.Throw(3); // No double score
Assert.That(b.GetScore(), Is.EqualTo(1 + 11 + (5 * 2) + 3));
}
// More tests for all the edge cases (strike, special end of game rules etc)
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So, Im a beginning C# programmer. I know basic syntax and simple things like if statements and loops(methods and classes too). I've only used console apps right now havent bothered with windows forms yet.
So any simple app ideas that introduce new things important for C# programming.
Also, NO tutorials. I want to make all by myself.
I'm a big fan of Halo, and one of the first things I did with C# was write an application that downloaded and parsed my online gaming stats while playing Halo 2. From there, I loaded all of the information into a database and redisplayed it in ASP.NET. In retrospect, the code was horrendous, but it was a fun exercise.
Another exercise was to parse the XML file for my iTunes music library, load it into a database, and (of course) display bits of it in ASP.NET.
Anyway, find ways to work with things you enjoy, be it games, music, television, or whatever.
A simple game might be a good start but those code golf questions can be a bit more advanced.
Why not try to write a 'test your reflexes' game, where you output a letter and time how long it takes for that letter to be keyed in? Then display the response time taken and the best response time to date.
Once i had to learn bash scripting for linux by writing the hangman game, it should be a good example for a console app in c#.
Hint:
start with
while(true)
{
//Game code goes here, use "continue" or "break" according to game logic.
}
One fun way to develop your skills is through code katas and programming contests like Top Coder and Google Code Jam. There are tons of example problems that will make you think, and many come with solutions that you can compare against after you are finished.
Even when you've been a developer for a while, these kind of simple problems allow you to incorporate new practices in your programming style (for instance, a kata is a great way to start learning the principles of TDD). Plus, they make for fun distractions.
I think solving Top-Coder problems will be great practice! It's specially suited since all their problems are console based, and they will make you increase not only your knowledge of c#, but also your problem solving skills and your data structure/algorithms knowledge.
That said, you probably wont learn much about new or more platform specific stuff about C#, such as linq, event handlers, threading, parallel tasks library, etc etc. For that, the best would be to find a good C# book and go through it.
Another way could be making little games. I know its console, but you can actually make games like Snake, Pac-man, hangman, etc, of course, with a little extra imagination, but it still works and games are great learning exercises (and are fun to show to people)
Write something recursive, like a routine that calculates the value of a factorial.
I recently developed a sudoku solver and a 8Queens solver.
I made the sudoku solver in console where the puzzle itself was hard coded in the project. You could try to make it possible to use a textfile as an input. I implemented a brute force algorithm witch works with recursion. It's is nice to develop such a solver and once you're ready there probably will be lots of improvements possible.
The 8Queens solver learned me two things. First I had to made a chessboard, which I did with forms. Learned me about Pens, Brushes and drawing. Also it was a nice practice for recursion which you have to do a lot before you understand it...
I'd suggest writing a command-line tool that does something that maybe can't be done by anything else.
The one thing that springs to mind is something that applies XSL stylesheets to XML files and spits out the output. There's sample code everywhere but no straightforward Windows tool that I've seen.
Potential benefits of this approach are that you end up with a useful tool and you then have the option of making it open-source to get additional input/support.
Well they are all tough to do, so i suggest using the copy paste method with my Blackjack app
remember to reference add system speech synth
using System;
using System.Speech.Synthesis;
namespace Blackjack
{
class Blackjack
{
static string[] playerCards = new string[11];
static string hitOrStay = "";
static int total = 0, count = 1, dealerTotal = 0;
static Random cardRandomizer = new Random();
static void Main(string[] args)
{
using (SpeechSynthesizer synth = new System.Speech.Synthesis.SpeechSynthesizer())
{
Console.Title = "Blackjack";
synth.Speak("Please enter your blackjack table's name followed by a comma then the secondary name (AKA table number)");
string bjtn = Console.ReadLine();
Console.Clear();
Console.Title = bjtn;
}
Start();
}
static void Start()
{
dealerTotal = cardRandomizer.Next(15, 22);
playerCards[0] = Deal();
playerCards[1] = Deal();
do
{
Console.WriteLine("Welcome to Blackjack! You were dealed " + playerCards[0] + " and " + playerCards[1] + ". \nYour total is " + total + ".\nWould you like to hit or stay? h for hit s for stay.");
hitOrStay = Console.ReadLine().ToLower();
}
while (!hitOrStay.Equals("h") && !hitOrStay.Equals("s"));
Game();
}
static void Game()
{
if (hitOrStay.Equals("h"))
{
Hit();
}
else if (hitOrStay.Equals("s"))
{
if (total > dealerTotal && total <= 21)
{
Console.WriteLine("\nCongrats! You won the game! The dealer's total was " + dealerTotal + ".\nWould you like to play again? y/n");
PlayAgain();
}
else if (total < dealerTotal)
{
Console.WriteLine("\nSorry, you lost! The dealer's total was " + dealerTotal + ".\nWould you like to play again? y/n");
PlayAgain();
}
}
Console.ReadLine();
}
static string Deal()
{
string Card = "";
int cards = cardRandomizer.Next(1, 14);
switch (cards)
{
case 1: Card = "Two"; total += 2;
break;
case 2: Card = "Three"; total += 3;
break;
case 3: Card = "Four"; total += 4;
break;
case 4: Card = "Five"; total += 5;
break;
case 5: Card = "Six"; total += 6;
break;
case 6: Card = "Seven"; total += 7;
break;
case 7: Card = "Eight"; total += 8;
break;
case 8: Card = "Nine"; total += 9;
break;
case 9: Card = "Ten"; total += 10;
break;
case 10: Card = "Jack"; total += 10;
break;
case 11: Card = "Queen"; total += 10;
break;
case 12: Card = "King"; total += 10;
break;
case 13: Card = "Ace"; total += 11;
break;
default: Card = "2"; total += 2;
break;
}
return Card;
}
static void Hit()
{
count += 1;
playerCards[count] = Deal();
Console.WriteLine("\nYou were dealed a(n) " + playerCards[count] + ".\nYour new total is " + total + ".");
if (total.Equals(21))
{
Console.WriteLine("\nYou got Blackjack! The dealer's total was " + dealerTotal + ".\nWould you like to play again?");
PlayAgain();
}
else if (total > 21)
{
Console.WriteLine("\nYou busted, therefore you lost. Sorry. The dealer's total was " + dealerTotal + ".\nWould you like to play again? y/n");
PlayAgain();
}
else if (total < 21)
{
do
{
Console.WriteLine("\nWould you like to hit or stay? h for hit s for stay");
hitOrStay = Console.ReadLine().ToLower();
}
while (!hitOrStay.Equals("h") && !hitOrStay.Equals("s"));
Game();
}
}
static void PlayAgain()
{
string playAgain = "";
do
{
playAgain = Console.ReadLine().ToLower();
}
while (!playAgain.Equals("y") && !playAgain.Equals("n"));
if (playAgain.Equals("y"))
{
Console.WriteLine("\nPress enter to restart the game!");
Console.ReadLine();
Console.Clear();
dealerTotal = 0;
count = 1;
total = 0;
Start();
}
else if (playAgain.Equals("n"))
{
using (SpeechSynthesizer synth = new System.Speech.Synthesis.SpeechSynthesizer())
{
synth.Speak("\nPress enter to close Black jack." + dealerTotal);
}
ConsoleKeyInfo info = Console.ReadKey();
if (info.Key == ConsoleKey.Enter)
{
Environment.Exit(0);
}
else
{
Console.Read();
Environment.Exit(0);
}
}
}
}
}