| | |
Just began c#, Comment Please ?
Please support our C# advertiser: Intel Parallel Studio Home
![]() |
I just started a few days ago. I am troubled with the input
in c#, even though I got it to work. Any comment would be
helpful. Its a Number Guessing game and a tic-tac-toe game.
in c#, even though I got it to work. Any comment would be
helpful. Its a Number Guessing game and a tic-tac-toe game.
C# Syntax (Toggle Plain Text)
using System; namespace GAME { #region NUMBER GUESSING GAME public class Number_Guess { public static void HiLow() { int guessNum = -1; string gNum; Random rand = new Random(); int minRan = rand.Next(10); int maxRan = rand.Next(50,150); int goal = rand.Next(minRan, maxRan); int numOfGuess = 0; Console.WriteLine("Your object it to guess the random number from {0} to {1}\n\n",minRan,maxRan); do { Console.WriteLine("What will you guess : "); gNum = Console.ReadLine(); guessNum = int.Parse(gNum); if (guessNum == goal) { Console.WriteLine("You guessed correct!\n\n Press a key to continue ..."); string x = Console.ReadLine(); break; } else if (guessNum > goal) { Console.WriteLine("You guessed too high\n"); ++numOfGuess; } else { Console.WriteLine("You guessed too low\n\n"); ++numOfGuess; } } while (guessNum != goal); } } #endregion #region TIC-TAC-TOE public class BOARD_GAME { const int GAME_STRT = 0; const int GAME_OVER = 1; const int RESET = 2; public static void Tic_Tac_toe() { Console.Title = "Tic-Tac-Toe"; //Create a The main GameBoard 3x3 char[] GameBoard = new char[9] { '1','2','3', '4','5','6', '7','8','9' }; //Initialize char P1_ID = 'X'; char Comp_ID = 'O'; int GameState = GAME_STRT; int choice = -1; Random rand = new Random(); Console.WriteLine("Would you like to be X or O : "); P1_ID = (char)Console.Read(); //Dummy reader Console.ReadLine(); if (P1_ID == 'O' || P1_ID == 'o' || P1_ID == '0') { Comp_ID = 'X'; P1_ID = 'O'; } else P1_ID = 'X'; PrintBrd(GameBoard, -1, P1_ID); choice = GetInput(choice); Console.Clear(); do { PrintBrd(GameBoard, choice, P1_ID); //Comp Turn choice = rand.Next(1, 9); //Check if Valid while (!(ValidMove(P1_ID, Comp_ID, GameBoard, choice))) choice = rand.Next(1, 9); PrintBrd(GameBoard, choice, Comp_ID); //Check winner, if any switch (CheckWinner(GameBoard, P1_ID, Comp_ID)) { case 'P': Console.WriteLine("\nCongrats, You beat the stupid computer\n"); GameState = GAME_OVER; goto case '-'; case 'C': Console.WriteLine("\nHahaha, how the Hell did you loose???\n"); GameState = GAME_OVER; goto case '-'; case 'D': Console.WriteLine("\nIts a Draw Game!\n\n"); GameState = GAME_OVER; goto case '-'; case '-': char op = 'y'; Console.WriteLine("\nPlaye Again? (y/n) : "); op = (char)Console.Read(); if (op == 'y' || op == 'Y') { GameState = RESET; break; } else GameState = GAME_OVER; break; default: break; } if (GameState == GAME_STRT) { //Get user Input choice = GetInput(choice); //Check for valid move while (!(ValidMove(P1_ID, Comp_ID, GameBoard, choice))) choice = GetInput(choice); PrintBrd(GameBoard, choice, P1_ID); //Check winner, if any switch (CheckWinner(GameBoard, P1_ID, Comp_ID)) { case 'P': Console.WriteLine("\n\nCongrats, You beat the stupid computer\n"); GameState = GAME_OVER; goto case '-'; case 'C': Console.WriteLine("\n\nHahaha, how the Hell did you loose???\n"); GameState = GAME_OVER; goto case '-'; case 'D': Console.WriteLine("\n\nIts a Draw Game!\n\n"); GameState = GAME_OVER; goto case '-'; case '-': char op = 'y'; Console.WriteLine("\nPlaye Again? (y/n) : "); op = (char)Console.Read(); if (op == 'y' || op == 'Y') { GameState = RESET; break; } else GameState = GAME_OVER; break; default: break; } } if (GameState == RESET) { GameState = resetFunc(GameBoard, GameState); PrintBrd(GameBoard, -1, Comp_ID); Console.ReadLine(); choice = GetInput(choice); } } while (GameState != GAME_OVER); } #region void PrintBrdPrint(char[],int,char) //Prints Board static public void PrintBrd(char[] Brd, int ElemChoice, char Obj_ID) { Console.Clear(); //Check for validity if ((ElemChoice < 1 || ElemChoice > 9) && ElemChoice != -1) { Console.WriteLine("INVALID ROW CHOICE! ITS BEGIN IGNORED THIS TIME\n\n"); return; } else { if (ElemChoice != -1) Brd[ElemChoice - 1] = Obj_ID; } //Print board for (int i = 0; i < 9; i += 3) { if (i != 0 && (i % 3 == 0)) Console.WriteLine('\n'); Console.WriteLine("{0} | {1} | {2}", Brd[i], Brd[i + 1], Brd[i + 2]); } } #endregion #region ValidMove(char,char,char[],int) : Check For Valid Move public static bool ValidMove(char ID, char ID2, char[] GameBrd, int choice) { if (choice < 1 || choice > 9) { Console.WriteLine("\nInvalid Dimension\n"); return false; } if (GameBrd[choice - 1] == ID || GameBrd[choice - 1] == ID2) { Console.WriteLine("\nInvalid Dimension\n"); return false; } return true; } #endregion #region GetInput(int) // Gets user Input static public int GetInput(int ch) { Console.WriteLine("\n\nWhere do you want to place your Move : "); ch = Console.Read(); ch -= '0'; //Dummy read Console.ReadLine(); return ch; } #endregion #region CheckWinner(char [] GameBrd, char Obj_ID,char Obj2_ID) // checks for winner static public char CheckWinner(char[] Gbrd, char P_ID, char C_ID) { char winner = '*'; // represent neither for (int i = 0; i < 9; i++) { if (i % 3 == 0) //check horizontal win { if (Gbrd[i] == P_ID && Gbrd[i + 1] == P_ID && Gbrd[i + 2] == P_ID) { winner = 'P'; return winner; } else if (Gbrd[i] == C_ID && Gbrd[i + 1] == C_ID && Gbrd[i + 2] == C_ID) { winner = 'C'; return winner; } } if (i < 3) //check vertical win { if (Gbrd[i] == P_ID && Gbrd[i + 3] == P_ID && Gbrd[i + 6] == P_ID) { winner = 'P'; return winner; } else if (Gbrd[i] == C_ID && Gbrd[i + 3] == C_ID && Gbrd[i + 6] == C_ID) { winner = 'C'; return winner; } } if (i == 0 ) //check diagnol win { if (Gbrd[i] == P_ID && Gbrd[i + 4] == P_ID && Gbrd[i + 8] == P_ID) { winner = 'P'; return winner; } else if (Gbrd[i] == C_ID && Gbrd[i + 4] == C_ID && Gbrd[i + 8] == C_ID) { winner = 'C'; return winner; } } else if (i == 2) { if (Gbrd[i] == P_ID && Gbrd[i + 2] == P_ID && Gbrd[i + 4] == P_ID) { winner = 'P'; return winner; } else if (Gbrd[i] == C_ID && Gbrd[i + 2] == C_ID && Gbrd[i + 4] == C_ID) { winner = 'C'; return winner; } } } //Check for draw game int cnt = 0; for (int i = 0; i < 9; i++) { if (Gbrd[i] == P_ID || Gbrd[i] == C_ID) ++cnt; else break; } if (cnt == 9) { winner = 'D'; return winner; } //no winner if reached return winner; } #endregion #region Reset Game static int resetFunc(char[] brd,int state) { for (char i = '1'; i <= '9'; i++) brd[i-'1'] = i; return (state = GAME_STRT); } #endregion } #endregion } class mainProg { static void Main() { char p = 'y'; string whichGame = "1"; do { Console.Clear(); Console.WriteLine("Which Game do you want to play : \n"); Console.WriteLine("1) Number Guessing game\n"); Console.WriteLine("2) Tic-tac-toe Game\n"); whichGame = Console.ReadLine(); Console.Clear(); switch (int.Parse(whichGame)) { case 1: GAME.Number_Guess.HiLow(); break; case 2: GAME.BOARD_GAME.Tic_Tac_toe(); break; } //Dummy read Console.ReadLine(); } while (p == 'y'); } }
•
•
Join Date: Nov 2007
Posts: 390
Reputation:
Solved Threads: 39
I am not too sure what the actual question is, nor do I have time to look through all that code and decide what you may be having problems with. I'm not too sure what you are confused with regarding input, as there are a vast amount of different input types in c# and in the .Net framework. Please post more specific problems and more relevant code.
What is your "trouble" with the input?
gNum = Console.ReadLine();
guessNum = int.Parse(gNum);
can be written as
guessNum = int.Parse(Console.ReadLine());
-----------------------------------------------------------------
string x = Console.ReadLine();
can be written as
Console.ReadKey();
Is it this you want?
P.S. In the future use code tags, and don't post 1000 lines of code saying I'm in trouble.
gNum = Console.ReadLine();
guessNum = int.Parse(gNum);
can be written as
guessNum = int.Parse(Console.ReadLine());
-----------------------------------------------------------------
string x = Console.ReadLine();
can be written as
Console.ReadKey();
Is it this you want?
P.S. In the future use code tags, and don't post 1000 lines of code saying I'm in trouble.
Last edited by ddanbe; Jun 9th, 2009 at 2:56 pm.
Today is a gift, that's why it is called "The Present".
Make love, no war. Cave ab homine unius libri.
Danny
Make love, no war. Cave ab homine unius libri.
Danny
I'm sorry, there is no "real " error. I am just query about c#
inputs, because I've been use to c++.
I see that they differ in return value, c++ returns both char or
numbers, while c# returns chars. I also realize that sometimes
the stream contains more junk, so I had to use a dummy readline().
Like this snippet :
Notice the Dummy reader. Is there a way to get around this.
I mean even in the simplest case, say where in a while loop
I ask the use to input a value, the loops reads the value and skips
a few iterations because of the junk in the stream.
So for example, if I do this :
The stream returns more than one value?
inputs, because I've been use to c++.
I see that they differ in return value, c++ returns both char or
numbers, while c# returns chars. I also realize that sometimes
the stream contains more junk, so I had to use a dummy readline().
Like this snippet :
C# Syntax (Toggle Plain Text)
Console.WriteLine("Would you like to be X or O : "); P1_ID = (char)Console.Read(); //Dummy reader Console.ReadLine();
I mean even in the simplest case, say where in a while loop
I ask the use to input a value, the loops reads the value and skips
a few iterations because of the junk in the stream.
So for example, if I do this :
C# Syntax (Toggle Plain Text)
while(true) { Console.WriteLine("Enter something : "); int in = Console.Read(); Console.WriteLine("you entered {0}",in); }
The stream returns more than one value?
•
•
Join Date: Nov 2007
Posts: 390
Reputation:
Solved Threads: 39
I'm not too sure about the C# console as I only use C# for windows apps and as code-behind in an ASP web apps. But perhaps it is returning a character array, which when cast to an int causes some issues. It could also be returning a string containing a null terminator at the end. I would read in all values as a string, then cast to an int using int.parse(string), a nifty little feature built into c#. I'm pretty sure that it throws an exception if the value isn't parseable, so you can just build a try/catch block around it for some easy input validation.
Unless this is for a class, I would recommend using C++ for console apps as it seems to have, from my experience, much more direct, unfluffy classes that use pointers rather than object references and therefore run much more quickly. C# is a more user-friendly environment that allows you to build very complex apps more quickly, but for the simpler apps like the ones you mentioned, it is definately an inferior language.
Unless this is for a class, I would recommend using C++ for console apps as it seems to have, from my experience, much more direct, unfluffy classes that use pointers rather than object references and therefore run much more quickly. C# is a more user-friendly environment that allows you to build very complex apps more quickly, but for the simpler apps like the ones you mentioned, it is definately an inferior language.
Last edited by skatamatic; Jun 9th, 2009 at 4:06 pm.
The Console.Read method always returns an int. C# is very picky about those things! Try while(1) for instance, will work in C++, won't work in C#! Because 1 is an integer NOT a boolean expression! That is why you have to typecast the Read method to a char else you get an int which is equal to the ASCII code of the char you typed. Also when you press the return key, windows appends a CR(=13) and a LF(=10) character to the inputstream. This is not junk, as you may think.
Last edited by ddanbe; Jun 9th, 2009 at 4:39 pm. Reason: typo
Today is a gift, that's why it is called "The Present".
Make love, no war. Cave ab homine unius libri.
Danny
Make love, no war. Cave ab homine unius libri.
Danny
•
•
•
•
Originally Posted by skatamatic
I'm not too sure about the C# console
> It could also be returning a string containing a null terminator at the end
Ho boy, ho boy, please don't answer a question if you are not sure yourself!
Last edited by ddanbe; Jun 9th, 2009 at 4:50 pm.
Today is a gift, that's why it is called "The Present".
Make love, no war. Cave ab homine unius libri.
Danny
Make love, no war. Cave ab homine unius libri.
Danny
![]() |
Similar Threads
- suddenly mouse and/or keyboard dead! (USB Devices and other Peripherals)
- I NEED HELP PLEASE:Warning: mysql_num_rows(): (PHP)
- I NEED HELP PLEASE:Warning: mysql_num_rows(): (MySQL)
- Warning: mysql_num_rows(): (PHP)
- Man arrested for paying with $2 bills at Best Buy (Geeks' Lounge)
- To charge $ or not to charge $.....Everyone comment (Promotion and Marketing Plans)
- C# XML Comment Problems (C#)
- RE: Leaked Windows Source Code (IT Professionals' Lounge)
Other Threads in the C# Forum
- Previous Thread: running bcp queryout through C# program
- Next Thread: string
| Thread Tools | Search this Thread |
.net access ado.net algorithm array barchart bitmap box broadcast buttons c# check checkbox client combobox connection console control conversion csharp custom database datagrid datagridview dataset datetime degrees deployment developer development draganddrop drawing editing encryption enum event excel file form format forms function gdi+ hospitalmanagementinformationsystem httpwebrequest image imageprocessing index input install java label list listbox mandelbrot math mouseclick mysql operator oracle path photoshop picturebox pixelinversion post priviallages. programming radians regex remote remoting richtextbox rows serialization server sleep socket sql statistics stream string table temperature text textbox thread time timer txt update uploadatextfile usercontrol validation visualstudio webbrowser windows windowsformsapplication winforms wpf xml






