As I’m learning how to write codes in AppleScript, I’ve created this simple game to put my still-not-very-big knowledge into practice.
My code displays a message asking the user/player to guess a number between 1 and 20 and compares their input with the randomly chosen one. When the player's guess = randomly chosen number, the game ends. Until that, it keeps asking the player to guess lower or higher.
I’m struggling to display a message (“Guess a number!!!”) whenever the user/player doesn’t type a number, but a letter or any other symbol other than a number.
I’ve realized that if I don’t get the user/player’s input “as integer”, the compiler won’t compare it in order to check if it’s inside or outside the given range (1 to 20).
But as I do this, whenever the user/player doesn’t type a number (but a letter or any other symbol other than a number), the compiler will display an error that says it can’t transform this character into an integer.
Thus, I can’t even use an if statement to make the compiler display my message (“Guess a number!!!”) whenever the user/player doesn’t type a number!
It would be something like: If playersGuess ≠ integer then display dialog "Guess a number!!!" end if
How do I go about solving this issue? Thanks in advance!
set RandomNumber to (random number from 1 to 20) as integer
display dialog RandomNumber
set EndOfGame to false
set NoOfTries to 0
repeat until EndOfGame is true
set Playersguess to the text returned of (display dialog "I'm thinking on a number between 1 and 20. Guess which one it is!" default answer "" buttons {"Ok"} default button 1) as integer
if Playersguess = RandomNumber then
set NoOfTries to NoOfTries + 1
if NoOfTries > 1 then
display dialog "Very well! It took you " & NoOfTries & " tries to guess the number I was thinking."
set EndOfGame to true
else
display dialog "Very well! It took you " & NoOfTries & " try to guess the number I was thinking."
set EndOfGame to true
end if
else if (Playersguess > RandomNumber) and (Playersguess < 21) and (Playersguess ≠ RandomNumber) then
display dialog "Wrong guess! Guess lower!"
set NoOfTries to NoOfTries + 1
else if (Playersguess < RandomNumber) and (Playersguess > 0) and (Playersguess ≠ RandomNumber) then
display dialog "Wrong guess! Guess higher!"
set NoOfTries to NoOfTries + 1
else if Playersguess > 20 then
display dialog "Guess a number up to 20!!!"
else if Playersguess < 1 then
display dialog "Guess a number starting at 1!!!"
end if
end repeat