C#- Console Program Ideas for Noob [closed] - c#

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);
}
}
}
}
}

Related

Can't get switch function to work to get into a different static class

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.

How does the DoWork method work in C# for Async Communication (ELI5)

I am using Visual Studio C# 2010 on Windows 10.
EDIT: My objective is to create an abort button which allows me to use the UI to cancel a loop.
I'm using an example I found online which is similar to this:
Here is the code:
public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = "";
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(50); //do some intense task here.
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
}
}
(There was a bit of code sharing the date/time but I removed it since it was superfluous to the basic example).
How I'm understanding this code is that, 100 times, the code pauses the main thread and works on "some intense task" for 50ms. Is this the case?
If so, I think I've ran into a problem. I have this code I want to run:
private void btn_runtest_Click(object sender, EventArgs e)
{
// Exterior Platform Loop
Output.AppendText("Starting Test \n");
for (int i = 0; i <= 3200; i += 178)
{
// Interior Platform Loop
for (int ii = 0; i <= 6400; ii += 178)
{
comport7_interior.Write("#1N178\r"); //change to have actual length?
comport7_interior.Write("#1G\r");
Output.AppendText("Interior shift 5 degrees \n");
Thread.Sleep(4000);
// ***********************************************************************************
// Read data from comport2_lightsensor, Parse byte, store Lux value, store angle (i,ii)
// ***********************************************************************************
}
comport8_exterior.Write("#0N178\r");
comport8_exterior.Write("#0G\r");
Output.AppendText("Exterior shift 5 degrees \n");
Thread.Sleep(4000);
//flip direction for internal
if (IsOdd(jjj))
{
//
comport7_interior.Write("#1-\r");
Output.AppendText("Interior switching direction to counter clockwise \n");
}
else
{
comport7_interior.Write("#1+\r");
Output.AppendText("Interior switching direction to clockwise \n");
}
jjj = jjj + 1;
// ***********************************************************************************
// Read data from compart2_lightsensor, Parse byte, store Lux value, store angle (i,ii)
// ***********************************************************************************
}
Output.AppendText("Loop Ended");
// manually reverse mount direction
// repeat the whole double for loop
}
This is pretty "fatty" code, so to summarize, it controls two stepper motors, rotates them to follow the desired path, pauses for 4 seconds, and will eventually log data. We could do the exact math but simply estimating we can realize this code will take 1-2 hours. With all of this pausing, it does not seem conducive to being split into 100 little chunks on worked on separately (if my understanding of the previously stated code is correct). Correct me I'm wrong but I don't think this code would fit in the above code.
Does this mean I'm looking at the wrong approach?
Thank you all in advance.

c# Math game win counter

So I created a game where player one and player two can play a game where they answer math questions, basically they go one after another for 5 rounds, so if one player answers the question right first they "Win" and if they both answer it right it is a "tie". Kind of a weird way to explain a weird game, but that's not my issue. I already finished the game inside of a class and it is functional and fine, my problem is that I need the players to play 5 games, and for it to tell who won the game the most, ex: "Player 1( or player 2, or draw) has won {0} times!" I have tried a lot of different things, but its all not working. Here is my code:
static void Main(string[] args)
{
string ID = "";
bool gOver = false;
Console.WriteLine("ID 1 ");
ID = Console.ReadLine();
MathGame p1 = new MathGame(1, ID);
Console.WriteLine();
Console.WriteLine("ID 2");
ID = Console.ReadLine();
MathGame p2 = new MathGame(2, ID);
Console.WriteLine();
while (!gOver)
{
MathGame.prblm();
while (!p1.Game() && !p2.Game())
gOver = true;
}
}
To reiterate; I'd like to make the game loop 5 times and tell me who won the most. I feel like my mistake is simple, make its just where I'm tired. Thanks for any and all help, this website is very helpful.
You need to wrap your game in a for loop, not a while. Then when the while loop (of your game) ends you should check who won and tally it. After the for loop you should have counters to display then.
There are many ways to "tally" but the easiest would be to add a variable for each player and increment when they win.
const in GAME_COUNT_TO_PLAY = 5;
for(int i = 0; i < GAME_COUNT_TO_PLAY; i++)
{
MathGame.prblm();
while (!p1.Game() && !p2.Game())
{
//Keep track of score here, incriment some counter for winner
//e.g. if(p1.Win) p1Count++;
}
}
After the for loop you can check for who won.
if(p1Count > p2Count)
Display("Player 1 Wins!");
else if(p1Count < p2Count)
Display("Player 2 Wins!")
else
Display("Draw!");

How to call main

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.

C# Bowling Game Calculation Issue

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)
}

Categories

Resources