I'm trying to create a simple console game where you take care of yourself by feeding yourself.
using System;
namespace Project1
{
static class Program
{
static void Main(string[] args)
{
int hunger = 100;
Console.WriteLine("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Good choice, " + name);
Console.WriteLine("Press SPACE to continue");
while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Spacebar))
{
// do something
int h = hunger - 2;
}
Console.WriteLine("You are hungry," + name);
Console.WriteLine("Press F to feed");
while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.F))
{
// do something
int food = hunger;
}
}
}
}
How can I display the current hunger after a change is made too it? I want to display the food level so the player knows to feed it and does not accidentally over feed it. By any chance is there a way to go back to a earlier line so I don't need to copy and paste the thing forever and ever? Thanks.
It looks like this will be very broad to answer properly, so I'm going to leave it pretty abstract. You need to put reusable logic in methods. You need a "game loop" or "input loop". You need to learn about variables and passing them into methods.
You also may want to introduce a Player class as opposed to various variables to hold separate values.
Your game loop may look like this:
ConsoleKey input = null;
do
{
var player = DoGameLogic(input, player);
PrintGameInfo(player);
input = ReadInput(player);
}
while (input != ConsoleKey.Q)
When you got all this in order and you want to make the output look nice, take a look at Writing string at the same position using Console.Write in C# 2.0, Advanced Console IO in .NET.
You can modify the position of the cursor with Console.CursorLeft and Console.CursorTop and overwrite previous values.
Cursor.Left = 0;
Console.Write("Hunger: {0:0.00}", hunger);
EDIT: AS mentioned by "CodeMaster", you can do:
Console.Write("Test {0:0.0}".PadRight(20), hunger);
To make sure you have overwritten the previous data if it differs in length.
is this something you wanted to achieve:-
static void Main(string[] args)
{
const int MAX_FEED_LEVEL = 3; //configure it as per your need
const int HIGHEST_HUNGER_LEVEL = 0; //0 indicates the Extreme hunger
int hunger = MAX_FEED_LEVEL, foodLevel = HIGHEST_HUNGER_LEVEL;
string name = string.Empty;
char finalChoice = 'N', feedChoice = 'N';
Console.Write("Enter your name: ");
name = Console.ReadLine();
Console.Write("Good choice, {0}!", name);
Console.WriteLine();
do
{
Console.WriteLine();
Console.WriteLine("current hunger level : {0}", hunger);
if (hunger > 0)
Console.WriteLine("You are hungry, {0}", name);
Console.Write("Press F to feed : ");
feedChoice = (char)Console.ReadKey(true).Key;
if (feedChoice == 'F' || feedChoice == 'f')
{
if (foodLevel <= MAX_FEED_LEVEL && hunger > HIGHEST_HUNGER_LEVEL)
{
hunger = hunger - 1; //decrementing hunger by 1 units
foodLevel += 1; //incrementing food level
Console.WriteLine();
Console.WriteLine("Feeded!");
Console.WriteLine("Current Food Level : {0}", foodLevel);
}
else
{
Console.WriteLine();
Console.WriteLine("Well Done! {0} you're no more hungry!", name);
goto END_OF_PLAY;
}
}
else
{
Console.Clear();
Console.WriteLine();
Console.Write("You chose not to feed !");
}
Console.WriteLine();
Console.Write("want to continue the game ? (Y(YES) N(NO))");
finalChoice = (char)Console.ReadKey(true).Key;
} while (finalChoice == 'Y' || finalChoice == 'y');
END_OF_PLAY:
Console.WriteLine();
Console.Write("===GAME OVER===");
Console.ReadKey();
}
Related
sorry if this is a repeat question or sounds pretty stupid, but I'm really new to c# and looked throughout the forum and couldn't find anything that I could actually understand.
So I'm trying to write a simple program where the user tries to guess a number between 1 and 25. Everything works except that each run of the loop instead of updating the score from the last run of the loop, like 0+1=1, 1+1=2, 2+1=3, each time it adds 1 to 0. Here is my code. How do I fix this? Thank you!
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = Console.ReadLine();
if (input == "18")
{
Console.WriteLine("You Did It!");
Console.WriteLine("Not Bad! Your Score was " + score + add);
break;
}
else
{
Console.WriteLine("Try Again. Score: " + score + add);
}
}
You need to actually add add to score. Try something like this:
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = Console.ReadLine();
score += add; // add `add` to `score`. This is the same as `score = score + add;`
if (input == "18")
{
Console.WriteLine("You Did It!");
Console.WriteLine("Not Bad! Your Score was " + score);
break;
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
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 2 years ago.
Improve this question
I am using C#.
I am getting the error of:
the name 'inventory' does not exist in the current context.
I am new at programming, and am creating this game for my final project at the university I go to. It's due in a few weeks, so I am not rushed but I like coding so I would love to figure out how to change this. My professor said I need to do my code in blocks, instead of it all being in one flowing way... this makes the local variables have problems, so I need a global of some type. I would love any help and tips.
using System;
using System.ComponentModel.Design;
namespace newGameFinal
{
class Program
{
static void Main(string[] args)
{
string[] inventory = new string[20];
intro();
gamebegin();
gamebegin2();
}
public static void invalid()
{
Console.WriteLine("Invalid Input");
}
public static void death()
{
Console.WriteLine("Would you like to play again? 1 for yes, 2 for no");
string choice6 = Console.ReadLine();
if (choice6 == "1")
{
Console.Clear();
intro();
}
if (choice6 == "2")
{
Environment.Exit(0);
}
}
public static void gamebegin()
{
{
bool roomchoice = true;
while (roomchoice == true)
{
string room = "0";
if (room == "0")
{
Console.WriteLine("Your goal is to survive in this dungeon....");
Console.WriteLine("");
Console.WriteLine("which room would you like to visit? (1, 2, 3, 4) 1 = South, 2 = East, 3 = West, 4 = North");
room = Console.ReadLine();
}
if (room == "1")
{
Console.WriteLine("You went South, you ran right into a wall. Please choose something else. (2, 3, or 4) ");
Console.WriteLine("-----------------------------------------------");
room = Console.ReadLine();
}
else if (room == "2")
{
Console.WriteLine("You went East, you went right into a Goblin... You died ");
Console.WriteLine("-----------------------------------------------");
death();
}
else if (room == "3")
{
Console.WriteLine("You went West, you saw a blinding light that shot a light spear through your chest, and you slowly bleed to death, while agonizing in pain!");
Console.WriteLine("");
Console.WriteLine("I wonder what did that. Maybe a diety of some kind?");
death();
}
else if (room == "4")
{
Console.WriteLine("You went North, you walked into a room with many monsters...");
Console.WriteLine("");
Console.WriteLine("You can bow down to them and beg to not be killed, or quickly look for a weapon. Please type 'beg' or 'look'");
gamebegin2();
}
else
{
invalid();
Console.WriteLine("Plesae choose 1, 2, 3 or 4.");
room = Console.ReadLine();
}
}
}
}
//******************
public static void intro()
{
player newplayer = new player();
Console.WriteLine("What is your name...?");
Console.WriteLine("");
newplayer.name = Console.ReadLine();
Console.Clear();
Console.WriteLine("Its dark " + newplayer.name + " I cant see anything but a dim light...");
Console.WriteLine("");
Console.WriteLine("You have one mission, and one mission alone " + newplayer.name + "...." + " To survive!");
Console.WriteLine("");
newplayer.health = 100;
Console.WriteLine("Your health is " + newplayer.health);
Console.WriteLine("");
Console.WriteLine("Would you like to begin?");
Console.WriteLine("");
string newgame = "no";
while (newgame == "no")
{
Console.WriteLine("Press 1 for Yes, or 2 for No");
Console.WriteLine("");
string choice = Console.ReadLine();
if (choice == "1")
{
Console.Clear();
break;
}
if (choice == "2")
{
Console.WriteLine("Okay I will wait till you are");
newgame = "no";
}
else
{
invalid();
newgame = "no";
}
}
}
public static void gamebegin2()
{
string choice = Console.ReadLine().ToUpper();
if (choice == "BEG")
{
Console.WriteLine("They kill you. Should have looked...");
death();
}
else if (choice == "LOOK")
{
}
}
public static void looking()
{
Console.WriteLine("You found a dagger, do you choose to fight, or to run? Please type 'run' or 'fight'");
string choice = Console.ReadLine().ToUpper();
if (choice == "RUN")
{
inventory[0] = "Dagger";
}
}
}
class player { public string name { get; set; } public int health { get; set; } }
}
The reason you are seeing this error is that your inventory[] is local to the Main() method.
You should move it to the class level and make it a modular variable.
class Program
{
static string[] inventory = new string[20]; //Move it here and along with anything else you need to access all methods in this class
static void Main(string[] args)
{
intro();
gamebegin();
gamebegin2();
}
//And the rest of your methods...
So I made a "game" in a c# console app project which is basically a hero who must kill a monster and both the hero and the monster have HP and a random amount of damage given and taken (as it should be).
I have a couple tiny problems which don't make sense to me. There is a Regeneration Potion that I have added to the game which obviously adds a random amount of hp between 10-30 to the player.
//Regenerating or not
if (isRegen == false) //if it doesn't
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("You've failed to regenerate!");
Console.WriteLine("Enemy: " + monster.name);
Console.WriteLine("Enemy's hp: " + monster.hp);
GetDamage();
}
else //if it does
{
if (myHP + regenAmount > 100 || myHP == 100)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("You can't regenerate above 100 hp.");
Game();
}
else
{
if (potionCounter == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("You are out of health potions. Cannot regenerate!");
Game();
}
potionCounter--;
myHP += regenAmount;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("You consumed a Health Potion!");
Console.WriteLine("Your hp was regenerated successfully! HP is raised by " + regenAmount);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Enemy: " + monster.name);
Game();
}
}
Now, as you can see in the code above, I have made an if statement that checks whether the sum of myHP and the regenAmount is higher than 100, a message that says "You can't regenerate above 100 hp" is displayed. Thing is, when I try this, sometimes it does display the message
as presented here,
but eventually it decides to display "You've failed to regenerate!" in here and well the game just goes on and the player gets hit. (which obviously shouldn't happen).
There is even another similar problem with the potionCounter. As presented in the code:
if (potionCounter == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("You are out of health potions. Cannot regenerate!");
Game();
}
Whenever the potion counter reaches 0, it should display a message that says that the user is out of potions. It happens and works, but similarly to the previous problem, it sometimes ignore the if statement and allows the user to either heal and continue on decrementing the potionCounter variable or fail to regenerate and get hit by the monster.
I know some of this code is kinda bad and well that's because im kinda new to programming but im trying my best to develop myself and learn as much as I can, which is why I decided to share it here.
Thank you for reading it and I hope you find the solution :)
Edit: The code for Game():
static void Game()
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(monster.name + "'s hp: " + monster.hp);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Your hp: " + myHP + "\n");
Console.ForegroundColor = ConsoleColor.White;
while(monster.hp > 0 && myHP > 0) //Running until the enemy or the player dies.
{
Console.Write("A - ATTACK (Give damage but always get hit)\nD - DEFEND (50% chance of not getting hit)\nR - REGENERATE (Regenerates HP, but if it fails you get hit) - ");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(potionCounter + " POTIONS LEFT\n");
string input = Console.ReadLine();
//ATTACK
if (input == "a" || input == "A")
{
Console.Clear();
Attack();
}
else if (input == "d" || input == "D")
{
Console.Clear();
Defend();
}
else if (input == "r" || input == "R")
{
Console.Clear();
Regenerate();
}
else
{
Console.Clear();
Game();
}
}
}
This is how I'd structure a simple game like this.
You already seem to have a "Monster" class – good! – but it's elided from this example for simplicity. Similarly, you would probably encapsulate Player as a class to keep track of each player's potions and HP individually.
Either way, the idea is that there's
an infinite loop governed by the "game over" flag
a function to run a single turn – checking whether the game is over, printing the game state, waiting for input, processing it, running AI actions (which, given our monster is a simple ogre of some ilk, is just it bashing your head in)
separate functions for the different events that occur in the game
... and a helper function that lets you change the console color and print a line of text in a single invocation ;-)
I hope this helps! It's not exactly a laser-focused pin-point answer, I know...
class Game
{
private int playerHp = 100;
private int monsterHp = 100;
private int nPotions = 3;
private readonly Random random = new Random();
private bool gameOver = false;
static void ColorPrint(string message, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.WriteLine(message);
}
public void Play()
{
while (!gameOver)
{
RunTurn();
}
}
void RunTurn()
{
CheckGameOver();
if (gameOver) {
return;
}
ColorPrint(String.Format("Monster HP: {0}", monsterHp), ConsoleColor.Red);
ColorPrint(String.Format(" Your HP: {0}", playerHp), ConsoleColor.Green);
ColorPrint(String.Format(" Potions: {0}", nPotions), ConsoleColor.Yellow);
ColorPrint("(A)ttack / (P)otion / anything else to skip your turn?", ConsoleColor.White);
var command = Console.ReadLine().Trim().ToLower();
switch (command)
{
case "a":
DoPlayerAttack();
break;
case "p":
DoPlayerPotion();
break;
default:
ColorPrint("You decide to loiter around.", ConsoleColor.White);
break;
}
DoEnemyAttack();
}
void CheckGameOver() {
if (monsterHp <= 0)
{
gameOver = true;
ColorPrint("The monster is slain!", ConsoleColor.White);
}
if (playerHp <= 0)
{
gameOver = true;
ColorPrint("You are dead. :(", ConsoleColor.White);
}
}
void DoPlayerAttack()
{
var damage = random.Next(1, 10);
ColorPrint(String.Format("You strike the monster for {0} damage.", damage), ConsoleColor.White);
monsterHp -= damage;
}
void DoPlayerPotion()
{
if (nPotions > 0)
{
var heal = random.NextDouble() < 0.7 ? random.Next(5, 15) : 0;
if (heal > 0)
{
ColorPrint(String.Format("You heal for {0} HP.", heal), ConsoleColor.Gray);
}
else
{
ColorPrint("That potion was a dud.", ConsoleColor.Gray);
}
playerHp = Math.Min(100, playerHp + heal);
nPotions--;
}
else
{
ColorPrint("You rummage through your belongings to find no potions.", ConsoleColor.Gray);
}
}
void DoEnemyAttack()
{
var damage = random.Next(1, 10);
ColorPrint(String.Format("The monster nibbles on you for {0} damage.", damage), ConsoleColor.White);
playerHp -= damage;
}
}
Just focusing on this bit of your code for a moment:
if (potionCounter == 0)
{
// ...
}
potionCounter--;
myHP += regenAmount;
Think about what will happen when the potionCounter is zero:
- It will then set potionCounter to -1
- It will give you the HP
You probably meant to put this code inside an else statement.
Additionally, checking if (potionCounter <= 0) would be more robust than testing for zero exactly.
I made a program that calculates the temperature in different ways.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Excercise_7
{
class Program
{
static void Main(string[] args)
{
showBegin();
decide();
secondPlay();
showEnd();
}
// Decide code
static void decide() {
int choice;
string input;
input = Console.ReadLine();
int.TryParse(input, out choice);
if (choice == 1)
{
Console.WriteLine("");
celciusSystem();
}
else if (choice == 2)
{
Console.WriteLine("");
farenheitSystem();
}
else if (choice == 3)
{
Console.WriteLine("");
kelvinSystem();
}
else {
Console.WriteLine("");
Console.WriteLine("Make sure u write a number between 1 and 3! No text!");
Console.WriteLine("");
showBegin();
decide();
}
}
static void secondPlay()
{
int choice2;
string input;
Console.WriteLine("");
Console.WriteLine("Type 1 to play again, type 2 to close the application");
input = Console.ReadLine();
int.TryParse(input, out choice2);
}
// Begin code
static void showBegin()
{
Console.WriteLine("Welcom at the temperature calculator, pick the mode u prefer!");
Console.WriteLine("Press 1 for Celcius mode");
Console.WriteLine("Press 2 for Fahrenheit mode");
Console.WriteLine("Press 3 for Kelvin mode");
Console.WriteLine("Press the correct number and then hit the enter button!");
Console.WriteLine("");
}
// Temperature Calculators
static void celciusSystem()
{
Console.WriteLine("This is the Celsius calculator");
Console.Write("Enter the amount of celsius: ");
int celsius = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Kelvin = {0}", celsius + 273);
Console.WriteLine("The temperature in Fahrenheit = {0}", celsius * 18 / 10 + 32);
}
static void farenheitSystem()
{
Console.WriteLine("This is the Fahrenheit calculator");
Console.Write("Enter the amount of Fahrenheit: ");
int Fahrenheit = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Kelvin = {0}", (Fahrenheit + 459.67) / 1.8);
Console.WriteLine("The temperature in Celsius = {0}", (Fahrenheit - 32) / 1.8);
}
static void kelvinSystem()
{
Console.WriteLine("This is the Kelvin calculator");
Console.Write("Enter the amount of Kelvin: ");
int Kelvin = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Fahrenheit = {0}", Kelvin * 1.8 - 459.67);
Console.WriteLine("The temperature in Celsius = {0}", Kelvin - 273.15);
}
// End code
static void showEnd()
{
Console.WriteLine("");
Console.WriteLine("We hoped u enjoyed our application!");
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
}
}
So now my question, I made a class called second play. Within that class i tried to make a kind a statement that would ask the user if he or she wanted to "play" again. So if they write 1 he should loop the game again.
I have tried it with this
if (choice2 == 1)
{
while (choice2 == 1) {
Console.WriteLine("");
showBegin();
decide();
}
}
else {
Console.WriteLine("");
Console.WriteLine("Cheers!!");
}
}
then he actually worked but not the way I wanted to because if the user writes 1 it will loop the first thing all over again. So the user can't quit the game any more.
I want the application to ask after every trail if he or she wants to play again by typing 1 or 2.
You already know how to read lines from the console, you also know how to use if to compare booleans, so why don't you just apply this and check if they wrote a 1 or 2?
private bool playAgain()
{
int number = 2; //Invalid option: close game
Int32.TryParse(Console.ReadLine(), out number);
if (number == 1)
{
return true;
}
else if (number == 2)
{
return false;
}
else
{
Console.WriteLine("Unknown option, quitting!");
return false;
}
}
Then you just have to use that function to determine if they want to play again in a do-loop.
static void Main(string[] args)
{
showBegin(); //Show begin sequence
do
{
decide();
secondPlay();
} while(playAgain()); //Play again if they want to
showEnd(); //Show end sequence when they decided not to play
}
Pro tip: use a switch-case statement instead of multiple if-else statements.
You can use a do while loop, which serves you well in cases like yours, when you want to execute your loop at least once:
do {
Console.WriteLine("");
showBegin();
decide();
//Ask for choice2 here
}
while(choice2 == 1);
Console.WriteLine("");
Console.WriteLine("Cheers!!");
To enter game loop, it is most useful to start with simple while or do-while.
while( conditionToRun )
{
//run the program
if( userWantToExit )
conditionToRun = false;
}
Or
do
{
// run the program
} while ( !userWantToExit )
This code shows the most basic stuff to handle this.
To apply on Your game/program, use:
static void Main(string[] args)
{
bool userWantToEnd = false;
showBegin();
while( !userWantToEnd)
{
decide();
userWantToEnd = IsUserWillingToContinue();
}
showEnd();
}
And adjust the SecondPlay() method into something like IsUserWillingToContinue():
public bool IsUserWillingToContinue()
{
int choice2;
string input;
Console.WriteLine("");
Console.WriteLine("Type 1 to play again, type 2 to close the application");
input = Console.ReadLine();
int.TryParse(input, out choice2);
return choice2 == 1;
}
Adding more info based on comment of #devRicher - You should split up a bit the code so it work in this way
bool runAgain = true;
Console.WriteLine("Begin info: (Hello this is XY game.)");
while(runAgain)
{
Console.WriteLine("You have 3 options: 1, 2, 3");
PickOptionAndRunTheCode();
bool runAgain = DoYouWantToContinue();
Console.Clear(); // clear the Console screen (next time You will see only options, not the text on first run).
}
I would recommend to get more knowledge about games to go to this page -> http://gameprogrammingpatterns.com/ (and read the book)
Check this pattern: Game Loop
I made a program which has 5 questions, it reads the users answer and lets them know if they were correct or not, if they were incorrect the user is forced to begin the 5 questions again. I added a count increment so that the program can tell the user the number of times it took to complete the quiz and i also added a "questions left" left feature which will tell you how many questions were left. as of now the code is all in one class and not separated into methods and uses the old "go to" loops. How would I go about changing the loops to a more modern code and how would I program it to use more methods for organising it, also the questions left feature works if the user gets every question correct but when the user gets a question wrong and restarts the questions left feature doesn't output the correct number.
here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace practicePro
{
class Program
{
public static void Main(string[] args)
{
/*----------------------------------------Declaration----------------------------------------- */
string q1, q2, q3, q4, q5;
int questionsLeft;
questionsLeft = 5;
/*----------------------------------------TITLE----------------------------------------- */
Console.WriteLine("Welcome to the Ultimate quiz!");
Console.WriteLine();
/*----------------------------------------QUESTION 1----------------------------------------- */
int count = 0;
start:
count++;
Console.WriteLine("What programming language has a snake as its name" + " questions left: " + questionsLeft );
Console.WriteLine();
q1 = Console.ReadLine();
q1 = q1.ToUpper();
if (q1 == "PYTHON")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
}
Console.WriteLine();
/*----------------------------------------QUESTION 2----------------------------------------- */
Console.WriteLine("What is the age range to qualify for an apprenticeship in the uk? Please type in the following format xx-yy" + " questions left: " + questionsLeft);
Console.WriteLine();
q2 = Console.ReadLine();
if (q2 == "16-24")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
count++;
}
Console.WriteLine();
/*----------------------------------------QUESTION 3----------------------------------------- */
Console.WriteLine("Is HTML a programming language (Yes or No)" + " questions left: " + questionsLeft);
Console.WriteLine();
q3 = Console.ReadLine();
q3 = q3.ToUpper();
if (q3 == "NO")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
count++;
}
Console.WriteLine();
/*----------------------------------------QUESTION 4----------------------------------------- */
Console.WriteLine("In JavaScript, What are the 2 charecters used to symbolise a single line comment?" + " questions left: " + questionsLeft);
Console.WriteLine();
q4 = Console.ReadLine();
if (q4 == "//")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
count++;
}
Console.WriteLine();
/*----------------------------------------QUESTION 5----------------------------------------- */
Console.WriteLine("500 < 600 && 700 < 600");
Console.WriteLine();
Console.WriteLine("Is the above statement true or false ?" + " questions left: " + questionsLeft);
Console.WriteLine();
q5 = Console.ReadLine();
q5 = q5.ToUpper();
if (q5 == "FALSE")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
Console.WriteLine();
Console.WriteLine("Congratulations You have passed the quiz!");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
}
Console.WriteLine();
Console.WriteLine("you took " + count + " time(s) to complete the quiz");
}
}
}
You can create a Question class, which will contain a text (question), and the right answer.
In your Main method, you can create and initialize the list of questions :
List<Question> questions = new List<Question>() {
new Question("What programming language has a snake as its name ?", "PYTHON"),
new Question(...),
...
}
Then you can create your workflow algorithm. Example :
Console.WriteLine("Welcome to the Ultimate quiz!");
Console.WriteLine();
int count = 0;
while(questions.Count > 0) {
Console.WriteLine(question.First().Text + " (question left: " + questions.Count + ")");
string answer = Console.ReadLine();
if (answer == questions.First().Answer)
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questions.RemoveAt(0);
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
count++;
}
}
Console.WriteLine();
Console.WriteLine("you took " + count + " time(s) to complete the quiz");
You can even create a Ask() method in the Question class, which will ask the question and analyze the answer (this method must take in parameter the number of question left, to display it).
Writing methods that contain logic is easy:
// Without extra method
class Program
{
static void Main(string[] args)
{
int a = 1;
int b = 2;
int c = a + b;
}
}
would turn into
// With extra method
class Program
{
static void Main(string[] args)
{
int a = 1;
int b = 2;
int c = Add(a, b);
}
static int Add(int num1, num2)
{
return num1 + num2;
}
}
Basics about methods:
They always have an access modifier (public or private, if none is given, it's private in C#
They always have a return type (in this case: int)
They always have a name (in this case: Add)
They can take parameters (in this case: num1 and num2)
If the return type is not void they always need a return statement in every code path
In order to loop until the player has answered every question correctly, you could make the asking method a bool type and as long as it returns false (which should happen every time the player answers wrong), a Player class calls the asking method.
// Quiz being the asking method
while(!Quiz())
{
// wrongAnswers being the counter for failed attempts
wrongAnswers++;
}
Console.WriteLine("Success!");
This will call the Quiz() method, which will then ask the player its 5 questions (which can, as Paul DS stated, be stored in a seperate class) and if it returns false (which means the player has answered one question wrong), it adds 1 to wrongAttempts, before calling it again. If it returns true, wrongAnswers is not incremented by 1 and "Success!" is shown.