Пытается отобразить сообщение («Угадай число !!!»), когда пользователь / игрок не набирает номер - PullRequest
2 голосов
/ 29 февраля 2020

Поскольку я учусь писать коды на AppleScript, я создал эту простую игру, чтобы применить на практике свои еще не очень большие знания.

В моем коде отображается сообщение с вопросом о пользователе / игрок угадывает число от 1 до 20 и сравнивает свои данные со случайно выбранным. Когда предположение игрока = случайно выбранное число, игра заканчивается. До этого он продолжает просить игрока угадать, ниже или выше.

Я изо всех сил пытаюсь отобразить сообщение («Угадай число !!!») всякий раз, когда пользователь / игрок не набирает число, но буква или любой другой символ, кроме числа.

Я понял, что если я не получу ввод от пользователя / игрока «как целое число», компилятор не будет сравнивать его, чтобы проверить если он находится внутри или за пределами заданного диапазона (от 1 до 20).

Но, как я это делаю, всякий раз, когда пользователь / игрок не вводит число (кроме буквы или любого другого символа, кроме числа) , компилятор отобразит ошибку, которая говорит, что он не может преобразовать этот символ в целое число.

Таким образом, я даже не могу использовать оператор if, чтобы компилятор отображал мое сообщение («Угадай число! !! ») всякий раз, когда пользователь / игрок не вводит число!

Это будет выглядеть примерно так: если PlayersGuess ≠ integer, то отобразится диалоговое окно« Угадай число !!! » end if

Как мне go решить эту проблему? Заранее спасибо!

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

1 Ответ

0 голосов
/ 29 февраля 2020

Я добавил два свойства в начало вашего скрипта. Я также добавил этот повтор l oop repeat while {Playersguess} is not in validNumbers в ваш код, который является примером того, как вы можете адресовать событие, когда кто-то ввел целое число больше 20, или любое другое значение ключа, которое я не определил в свойстве validNumbers ... Перенос этой части вашего кода ... set Playersguess to the text returned of внутри блока try позволяет продолжить выполнение кода, если он обнаружит ошибку.

Есть несколько других проблем с вашим кодом, которые необходимо решить, но на данный момент внесенные мной изменения могут вернуть вас на правильный путь.

property validNumbers : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
property Playersguess : missing value

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

    repeat while {Playersguess} is not in validNumbers
        try
            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
        end try
        if {Playersguess} is not in validNumbers then
            display dialog "Please Only Enter Numerals From 1 to 20" buttons {"Cancel", "OK"} default button "OK"
        end if
    end repeat

    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
            set Playersguess to missing value
        else
            display dialog "Very well! It took you " & NoOfTries & " try to guess the number I was thinking."
            set EndOfGame to true
            set Playersguess to missing value
        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
...