Hey everyone! I'm relatively new to C++, and I've been working on a simple Rock Paper Scissors program. I'm looking for some feedback on how to improve my code. Here's what I have so far:
```cpp
#include
#include
int choice = 4;
void choosewinner();
int main(){
while (choice > 3) {
std::cout << "What option would you like to pick n";
std::cout << "1. Rock n";
std::cout << "2. Paper n";
std::cout <> choice;
choosewinner();
}
}
void choosewinner(){
srand(time(NULL));
int AI = (rand() % 3) + 1;
std::cout << "You have picked option: " << choice << 'n';
std::cout << "Your opponent has picked option: " << AI << 'n';
switch (AI) {
case 1: // AI has chosen rock
if (choice == 1) {
std::cout << "You have tied!";
}
else if (choice == 2) {
std::cout << "You have Won!";
}
else if (choice == 3) {
std::cout << "You have lost!";
}
break;
case 2: // AI has chosen paper
if (choice == 1) {
std::cout << "You have lost!";
}
else if (choice == 2) {
std::cout << "You have tied!";
}
else if (choice == 3) {
std::cout << "You have won!";
}
break;
case 3:
if (choice == 1) {
std::cout << "You have Won!";
}
else if (choice == 2) {
std::cout << "You have Lost!";
}
else if (choice == 3) {
std::cout << "You have Tied!";
}
break;
default:
break;
}
}
```
How can I make this better?
3 Answers
Another point is about user experience; instead of just repeating the prompt when an invalid option is selected, you should let the user know their choice was invalid. Also, it's a good idea to track scores over several rounds. Lastly, the way you're seeding the random number generator is repeated every time a turn is played. You should seed it only once at the start of your program.
You could really simplify the win-condition logic into just a handful of lines, since it's essentially just checking different combinations. Think about using a 'victory table' to track the winning conditions instead of a long series of if/else statements. Also, if you encounter an invalid choice, give the user feedback instead of just looping again. And for readability, showing the actual choices instead of just numbers would definitely help.
First off, try to avoid using global variables like 'choice'. It's generally better to limit the scope of your variables to make debugging easier later on. Also, for random number generation, use C++'s library for better performance instead of C's srand and rand functions. Your method can introduce a slight bias in the randomness. Separating your main logic from display logic is also a good idea so that you can easily update or test different parts independently. Plus, consider using `std::flush` or `std::endl` in places to ensure the output is seen immediately.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically