Public Group

# Basic Programming Knowledge Need Some Advice

This topic is 1138 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi I am currently in school right now as a senior in college with a major of Electrical Enginnering getting ready to graduate in Dec. I know some programming but it comes more on the hardware side like microcontrollers interatcing with sensors and things like that with GPIO pins etc.. so nothing too crazy. But I have always liked games and like coding classes I have taken. Dont get me wrong I love my major but I also like the progamming aspect. The only class I have taken was a class in C and then another class of continuation into C++. So I have started small and made a basic text based guess the number game with different functions such as saving scores to a file with a name, an exiting function, display all the scores and delete all the score. What I am looking for is some advice on structure and good coding pratices thing that I should do better on and some basic advice. Any advice would be greatly appericated.

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int play();				// play the game
void save(int score);	// save score in a file
void deleteData();		// delete the high scores
void displayScores();	// display the scores

int main()
{
int status;			// returned from function
int score = 0;		// how many times you have won
bool game;			// game state of game

cout << "Get a score of 5 and win but three wrong guesses in a row and you lose\n";

{
game = true;
{
while(game == true)
{
status = play();
if (status == 1)
{
score += status;
cout << "Score: " << score << "\n\n";

}
if (status == -1)
{
cout << "Sorry you are a loser!!!\n";
cout << "Your final score was: " << score << " points\n";
save(score);
score = 0;
game = false;

}
if (score == 5)
{
cout << "Congrats you have won the Game!!\n";
cout << "Your final score was: " << score << " points\n";
save(score);
score = 0;
game = false;
}
}
}
{
displayScores();
}
{
deleteData();
}

}

cout << "Exiting Game....\n";
system("PAUSE");

return 0;
}

int play()
{
int randomNumber = rand() % 100 + 1;
int tries = 0;
int guess;

while (tries < 3)
{
cout << "Guess a number between 1 and 100: ";
cin >> guess;
if (guess == randomNumber)
{
cout << "Congrats you guessed correctly\n";
return 1;
}
else if (guess < randomNumber)
{
cout << "You guessed too low try again\n";
tries++;
}
else if (guess > randomNumber)
{
cout << "You guessed too high try again\n";
tries++;
}
}
cout << "The number was " << randomNumber << "\n";
return -1;
}

void save(int score)
{
string name;
cout << "Please enter you name: ";
cin >> name;

ofstream file;
file.open("scores.txt",ios::app);
if(file.is_open())
{
file << name << " " << score << "\n";
}
else
{
cout << "Unable to open file!!\n";
}

file.close();
}

{
int selection = -1;
while(selection < 1 || selection > 3)
{
cout << "Make a selection\n";
cout << "1 - Play Game\n";
cout << "2 - Exit Game\n";
cout << "3 - Display High Scores\n";
cout << "4 - Erase High Scores\n";
cout << "Input: ";
cin >> selection;
if(selection == 1)
return 1;
else if(selection == 2)
return 2;
else if(selection == 3)
return 3;
else if(selection == 4)
return 4;
else
cout << "Please enter a valid selection!\n";
}

}

void deleteData()
{
ofstream file;

file.open("scores.txt",ios::out | ios::trunc);
file.close();
}

void displayScores()
{
string name;
int score;
ifstream file;

file.open("scores.txt");
if(file.is_open())
{
while(true)
{
if(!(file >> name)) break;
cout << name << "\t";
if(!(file >> score)) break;
cout << score << "\n";
}
}
else
{
cout << "File could not be opened..\n";
}

file.close();
}


##### Share on other sites

You should read up on how to structure a game loop.
You can then restructure and simplify your code, removing those inner loops and instead remember in which state you are.
Its roughly that:

enum State state=start;
string inputdata;
while(state!=stop) {
draw(&state,inputdata);
inputdata=input(&state);
}
Edited by wintertime

##### Share on other sites

the longest program i've written was 50k lines

programming style... i much prefer single character variables whenever possible, usually make it to 2 and 3 character variable names after a few thousand lines.

i consider my code to be concise and readable. other people hate it.

i do occasionally use a long variable name if it is only going to be used once or twice for an obscure function, but the meat and potatoes is all single or double character names.

never let anyone rate you. you'll see that people have so many ways to write code that aspiring for a unified convention is best done if you source from your own individual preferences.

and there are still some grown-ups in the world who think it's alright if you have those.

people may slag my unabashed advocacy of doing things the way that makes the most sense to you, but they're probably not typing by hanging over the end of a bed because they can't bend their legs. i've been typing on computer keyboards since 1981 and i've got no time to type out longvariablenameseventeen all day.

Edited by Josh Petrie

##### Share on other sites

1. As a general guideline you want to separate your code into more discreet pieces so a function does one thing only. Code is cleaner, easier to maintain/understand and opens the door to unit testing.
2. You are returning integers to represent states and it was suggested to use enumerations which is great. However, for error conditions I would suggest exploring exceptions instead.
3. Read up on classes (OOP) at some point. Nibble on it in small pieces. I would start with data hiding (private, public and protected variables and functions). This will keep you from stepping over yourself when you get more ambitious. It seems simple now but if you hit a time crunch at 2am you are more likely to experience less pain and frustration.

##### Share on other sites

notice that i posted my opinion instead of rating your post down. the mistake so many people make that is the REASON I POST OPINION CONTRARY TO POPULAR is that many people seem to feel that there is only ONE envaluation in productivity, the "apparent commercial standard".

YES it is necessary to standardise when working on a team, but this is not everyone's objective. if someone wants to get hired straight out of school, then kowtow.

if on the other hand someone engages in a rich and varied set of activities during their adult/professional life, more "localised" methods are more appropriate, with a lower need for standardisation and readability.

the point you should understand is that short variable names are not a function of skill or duration of experience, it is a function of not being part of a standardised procedure.

if you think someone who is used to conventions established with c is a bad or inexperienced programmer, you're "self-inflated" and "other depreciating". the reason why you find it "ironic" is because you need to feel as if you have outwirtted me, instead of simply acknowledging that the methods of others may also be entirely valid.

if i'm writing a game, it's likely to be under 2000 lines total. for the scope of such a project, there is absolutely no need for it.

and, so you know, i don't have time to type out superfluous appellations,but i have all the time in the world to explain myself and encourage you to be less depreciative toward others. i am not bad, nor am i new. it's that simple.

i am not bad, nor am i new.

and, i do not use long variable names.

and that is really all that needs to be said, or considered.

now go ahead and nuke me for asserting that you shouldn't depreciate this expression.

##### Share on other sites

Thanks guy I appericate all the feedback and input. I think ill keep this program and try to make those modifications to it before I go one then I will try to do something like tic-tac-toe in console then move onto trying to replicate in in a graphics format since the logic should still stay the same then go from there.

1. 1
2. 2
3. 3
Rutin
19
4. 4
JoeJ
14
5. 5

• 14
• 10
• 23
• 9
• 32
• ### Forum Statistics

• Total Topics
632628
• Total Posts
3007518
• ### Who's Online (See full list)

There are no registered users currently online

×