i was trying to make a guessing game and I got all the code in but it gave me an error error: expected initializer before 'if'
exit status 1
void loop()
You might be missing a semicolon somewhere, but without seeing more of the code it'll be hard to pinpoint the error.
Try looking at the error message for a line indicator (something like programName:x:y: error: ..., then go to line x and look around for missing punctuation or other synthax errors.
after adding the { i got more errors
In function 'void loop()':
27:21: error: 'high' was not declared in this scope
27:21: note: suggested alternative: 'sinh'
35:21: error: 'high' was not declared in this scope
35:21: note: suggested alternative: 'sinh'
42:20: error: 'high' was not declared in this scope
42:20: note: suggested alternative: 'sinh'
47:2: error: expected '}' at end of input
exit status 1
This gives you a value from 0 to 8. The high limit is not included. Since you don't give the random number generator a new seed, it will always produce the same sequence of numbers.
Here is a version that only allows 4 guesses and starts a new game when the game ends. (Hint: If you do a binary search you will always win in 4 moves or fewer.)
int SecretNumber = random(0, 10);
const byte TooHighLEDPin = 13;
const byte TooLowLEDPin = 11;
const byte CorrectLEDPin = 9;
void setup()
{
Serial.begin(9600);
pinMode(TooHighLEDPin, OUTPUT);
pinMode(TooLowLEDPin, OUTPUT);
pinMode(CorrectLEDPin, OUTPUT);
Serial.println("Instructions: Guess numbers form 0 to 9");
Serial.println();
}
void loop()
{
static int errorCount = 0;
if (Serial.available() > 0)
{
int guess = Serial.read() - '0';
Serial.print("Your guess ");
Serial.println(guess);
if (guess > SecretNumber)
{
errorCount++;
Serial.println("too high!");
digitalWrite(TooHighLEDPin, HIGH);
Serial.println("Guess again:");
delay(300);
digitalWrite(TooHighLEDPin, LOW);
}
else if (guess < SecretNumber)
{
errorCount++;
Serial.println("Too low!");
digitalWrite(TooLowLEDPin, HIGH);
Serial.println("Guess again:");
delay(300);
digitalWrite(TooLowLEDPin, LOW);
}
else
{
Serial.println("Correct!");
digitalWrite(CorrectLEDPin, HIGH);
delay(300);
digitalWrite(CorrectLEDPin, LOW);
// Start a new game
Serial.println();
Serial.println("Instructions: Guess numbers form 0 to 9");
Serial.println();
errorCount = 0;
SecretNumber = random(0, 10);
}
if (errorCount > 4)
{
Serial.println("Too many guesses. You lose.");
digitalWrite(TooHighLEDPin, HIGH);
digitalWrite(TooLowLEDPin, HIGH);
delay(300);
digitalWrite(TooHighLEDPin, LOW);
digitalWrite(TooLowLEDPin, LOW);
// Start a new game
Serial.println();
Serial.println("Instructions: Guess numbers form 0 to 9");
Serial.println();
errorCount = 0;
SecretNumber = random(0, 10);
}
}
}