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.
Related
Im making a game for school and Im trying to get this data from the switch:
public void planets()
{
switch(PlanetType)
{
case planetType.Desert:
Debug.Log("Desert");
maxFuel = 500;
break;
case planetType.Ruined:
Debug.Log("Ruined");
maxFuel = 1500;
break;
case planetType.Lush:
Debug.Log("Lush");
maxFuel = 3000;
break;
}
}
per scene for that specific planet as the maxFuel in the slider in that scene
I have the enum and that stuff, but for some reason in Unity, it only takes the input max fuel in unity and doesnt want to take the max fuel from the switchcase. Any quick fixes?
Background; I'm trying to create a dice game for multi-players where you can choose how many players, sides on the die and dice's themselves you want in the game. And players each take a turn rolling n amount of dices and per each roll the score gets appended to the player classes playerScore property. Once a player reaches X amount of points, player is declared a winner.
Problem; The below code is part of the "Game" class. When I compile the code, the game does what I expect for the most part; it rolls 5 dices each turn per player and appends the points to said player, but once the player reaches 100 points, the player is declared a winner, but the die's are rolled again for another player, despite the fact that the while loop is invalidated. The way i see it, the problem is with the for loop, but I have no idea how to fix this, i tried "break" but it only breaks from the if statement.
My program has 3 classes; Die, Player, Game. If you need more information or screen shots. I can provide them.
P.S. If you think this code could be improved, please comment, I'd be glad to hear it out.
The if statements are messing with your flow. Why?
if (gameEnded || playerArray[i].PlayerScore >= maxPoints)
{
Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.",playerArray[i].PlayerName, playerArray[i].PlayerScore);
gameEnded = true;
break;
}
else if (!gameEnded )
{
playerArray[i].PlayerScore += rollAllDice();
Console.WriteLine("'{0}': {1}", playerArray[i].PlayerName, playerArray[i].PlayerScore);
}
Here, you're checking if the current player has reached the final score. If so, you break you for loop and set gameEnded = true, breaking the while loop as well. But this checks the score of the current player; it doesn't check if the current player has reached the score. This way, you will only discover if Player A won the game on the next round, not the current.
This way, as soon as a player reaches the score, the game ends:
public void StartGame(int maxPoints)
{
playerArray[0].PlayerTurn = true; // Not sure why you're doing this, so I'm gonna leave this here
Player winner = null;
while (!gameEnded)
{
for (int i = 0; i < playerArray.Length; i++)
{
Player currentPlayer = playerArray[i];
currentPlayer.PlayerScore += rollAllDice();
Console.WriteLine("'{0}': {1}", currentPlayer.PlayerName, currentPlayer.PlayerScore);
if (currentPlayer.PlayerScore >= maxPoints)
{
winner = currentPlayer;
gameEnded = true;
break;
}
}
}
Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.", winner.PlayerName, winner.PlayerScore);
}
There is only one "problem" within this code: as soon as a player reaches the number of points, it ends the game. It doesn't wait for the round to end..
You could do like this:
public void StartGame(int maxPoints)
{
//playerArray[0].PlayerTurn = true; // Is it necessary?
while (true)
{
for (int i = 0; i < playerArray.Length; i++)
{
Player currentPlayer = playerArray[i];
currentPlayer.PlayerScore += rollAllDice();
Console.WriteLine("'{0}': {1}", currentPlayer.PlayerName, currentPlayer.PlayerScore);
if (currentPlayer.PlayerScore >= maxPoints)
{
Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.", currentPlayer.PlayerName, currentPlayer.PlayerScore);
return;
}
}
}
}
I think your flow was just a little off, this may work better. To me the real issue was you should have rolled the dice first, then checked if it was a win. This would make your WHILE work properly.
public void StartGame(int maxPoints)
{
while (!gameEnded)
{
for (int i = 0; i < playerArray.Length; i++)
{
playerArray[i].PlayerScore += rollAllDice();
Console.WriteLine("'{0}': {1}", playerArray[i].PlayerName, playerArray[i].PlayerScore);
if(playerArray[i].PlayerScore >= maxPoints){
Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.",playerArray[i].PlayerName, playerArray[i].PlayerScore);
gameEnded = true;
break;
}
}
}
}
This is being programmed in c# as a console application.
In my program, i intend to ask a user whether they want to find the area and voolume of a cuboid, the area and circumference of a circle or the area and volume of a sphere. I have the algorithms for the areas, volumes and circumference all set out, the only problem is that i do not know how to ask the user which one (the cuboid, circle and sphere) they want to do and then run only that specific algorithm.
Try asking the user like
...cuboid
...circle
...sphere
then read the char from the keyboard
char ch = (char)Console.Read();
and use the switch statement like this
switch(ch)
{
case '1': { /* insert cuboid algorhytm here */ break;}
case '2': { /* insert circle algorhytm here */ break;}
case '3': { /* insert sphere algorhytm here */ break;}
default : { /* insert invalid selection message */ break;}
}
You will typically use the Console class to write to the console and read input from the console. Here's a sample program that will get you started:
class Program
{
enum Choice { Volume, Area}
static void Main(string[] args)
{
string input;
Choice choice;
do
{
Console.WriteLine("1. Volume");
Console.WriteLine("2. Area");
Console.Write("Please make your choice: ");
input = Console.ReadLine();
} while (!Enum.TryParse(input, out choice));
Console.WriteLine(choice);
switch (choice)
{
case Choice.Volume:
// calculate volume
break;
case Choice.Area:
// calculate area
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
It`s may be not best solution, but you simply can write "Pls input c - circle, v - volume, and then check what user was writed,
if (input.ToLower().Contains("circle")
{
//do what you wont to do.
}
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.
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);
}
}
}
}
}