Добавление функции в эту игру Hangman - PullRequest
0 голосов
/ 27 марта 2019

У меня игра палач, и у меня возникают проблемы с добавлением функции.Я хочу сделать это, если все слово угадано, на нем будет отображаться «Вы угадали слово !!!», но я не могу найти место, чтобы поставить его.Это код инициализации hangman ()

свойство сценария hangman stdin: свойство отсутствующего значения stdout: свойство отсутствующего значения dict: отсутствующее значение

on init()
    --starting up the game
    set stdin to parent's hangmanStdin's alloc()'s init()
    set stdout to parent's hangmanStdout's alloc()'s init()
    set dict to parent's hangmanDictionary's alloc()'s init()
    my mainLoop()
end init

on mainLoop()
    repeat --endless
        set option to stdin's getOptions("Lobby", "What would you like to do?", {"New Game", "Quit"})
        if option is "New Game" then
            set difficulty to stdin's getOptions("New Game", "Choose your difficulty", {"Normal", "Easy", "Hard"})
            --replace this line with an automatic word generator
            set x to parent's hangmanGame's alloc()'s initWithWordAndDifficulty(dict's getWord(), difficulty)

            if x's startgame() is false then
                return
            else
                stdout's printf("You've scored " & x's score & " points.")
            end if
            --game is over so clear it
            set x to missing value
        else
            exit repeat
        end if
    end repeat
end mainLoop

on shouldTerminate()
    return true
end shouldTerminate


on alloc()
    copy me to x
    return x
end alloc

end script

script hangmanGameродительское свойство: hangman

property wordToGuess : missing value
property maxFaults : missing value
property usedChars : missing value
property faults : missing value
property score : 0

on initWithWordAndDifficulty(theWord, theDifficulty)
    if theDifficulty = "Hard" then
        set my maxFaults to 5
    else if theDifficulty = "Normal" then
        set my maxFaults to 8
    else --easy or any other value will be handled as easy
        set my maxFaults to 10
    end if
    set my wordToGuess to theWord
    set my usedChars to {}
    set my faults to 0
    set my score to 0
    return me
end initWithWordAndDifficulty

on startgame()
    repeat --endless
        set __prompt to "Faults Left: " & maxFaults - faults & return & "The Word: " & my makeHiddenField()
        set c to parent's stdin's getChar(__prompt)
        if c = false then
            return false
        end if
        --first check if getChar did give us any result
        if length of c is not 0 then
            --check if teh character is valid
            if c is in "abcdefghijklmnopqrstuvwxyz" then
                --check if we already checked this before
                if c is not in my usedChars then
                    set end of my usedChars to c
                    --check if player guessed wrong character
                    if c is not in wordToGuess then
                        set faults to faults + 1
                    end if
                end if
            end if
        end if
        --check if player guessed all characters of word
        if my wordGuessed() then
            set my score to ((25 * (26 / (length of my usedChars))) as integer)
            return true
        end if
        --check if player reached the max faults he's allowed to make
        if my faults = my maxFaults then
            display dialog "The word was " & quoted form of wordToGuess
            return 0
        end if
    end repeat
end startgame

on wordGuessed()
    repeat with aChar in every text item of my wordToGuess
        if aChar is not in my usedChars then
            return false
        end if
    end repeat
    return true
end wordGuessed

on makeHiddenField()
    set characterArray to {}
    repeat with aChar in every text item of my wordToGuess
        if aChar is in my usedChars then
            set end of characterArray to aChar as string
        else
            set end of characterArray to "_"
        end if
    end repeat
    set AppleScript's text item delimiters to space
    set hiddenField to characterArray as string
    set AppleScript's text item delimiters to ""
    return hiddenField
end makeHiddenField

конечный сценарий

сценарий свойство hangmanDictionary родительского объекта: свойство hangman wordsPlayed: свойство отсутствующего значения allWords: отсутствующее значение

on init()
    set wordsPlayed to {}
    --try to get more words from a file for example
    set allWords to {"Hangman", "Police", "Officer", "Desktop", "Pencil", "Window", "Language", "Wealthy", "Trauma", "Spell", "Rival", "Tactical", "Thin", "Salty", "Bluish", "Falcon", "Distilery", "Ballistics", "Fumbling", "Limitless", "South", "Humble", "Foreign", "Affliction", "Retreat", "Agreeable", "Poisoner", "Flirt", "Fearsome", "Deepwater", "Bottom", "Twisted", "Morsel", "Filament", "Winter", "Contempt", "Drimys", "Grease", "Awesome", "Compulsive", "Crayon", "Prayer", "Blonde", "Backbone", "Dreamland", "Ballet", "Continuous", "Aerobatic", "Hideous", "Harmonic", "Lottery", "Encrypt", "Cable", "Aluminium", "Hunter", "National", "Hunter", "Mechanical", "Deadbeat", "Opposition", "Threat", "Decadent", "Gazelle", "Guild", "Authoritive", "Deliverance", "Severe", "Jerid", "Alarm", "Monochrome", "Cyanide", "External", "Potential", "Section", "Innocent", "Drifting", "Amnesia", "Domino", "Flimsy", "Flamethrowing", "Advocate", "Hirsute", "Brother", "Ephemeral", "Brutal", "Decade", "Drauma", "Dilemma", "Exquisite", "Glimmer", "Fugitive", "Digital", "Associate", "Ambivalent", "Ambulatory", "Apology", "Brawler", "Molecular", "Insurance", "Contractual", "Initial", "Calibration", "Heretical", "Disclosure", "Guerilla", "Dismember", "Minimal", "Altercation", "Eastern", "Integrate", "Femur", "Metallic", "Ambition", "Auxiliary", "Esoteric", "Converse", "Accepting", "Juvenile", "Efficacious", "Complex", "Imperil", "Division", "Onerous", "Astonish", "Scandalous", "Quaint", "Dominate", "Contrary", "Conspiracy", "Earthquake", "Embarrassment", "Exclude", "Ambiguous", "Captivate", "Compliance", "Migration", "Embryo", "Abandon", "Conservation", "Appreciate", "Applaud", "Pension", "Voyage", "Influence", "Consensus", "Incapable", "Economy", "Parameter", "Contrast", "Sensitive", "Meadow", "Chimney", "Familiar", "Serious", "Credibility", "Infrastructure", "Museum", "Relinquish", "Merit", "Coalition", "Retirement", "Transaction", "Official", "Composer", "Magnitude", "Committee", "Privilege", "Diamond", "Obligation", "Transition", "Jockey", "Reinforce", "Conflict", "Offensive", "Detective", "Effective", "Detector", "Abhorrent", "Fragile", "Feigned", "Addition", "Jealous", "Irritating", "Grotesque", "Hesitant", "Adaptable", "Highfalutin", "Defiant", "Ceaseless", "Aquatic", "Voracious", "Separate", "Phobic", "Scientific", "Cluttered", "Intelligent", "Garrulous", "Rhetorical", "Obtainable", "Bawdy", "Outstanding", "Synonymous", "Gleaming", "Ambitious", "Agonizing", "Fallacious", "Lamister", "Fugitive", "Individualism", "Archaic", "Paramount", "Pannose", "Pretermit", "Retorse", "Versability", "Demonomancy", "Vagile", "Reflation", "Foliate", "Guignol", "Agacerie", "Theopneustic", "Glumiferous", "Optative", "Scrivello", "Unifarious", "Ordonnance", "Dithyrambic", "Locative", "Locomotive", "Mirabilia", "Keyline", "Mellification", "Theomicrist", "Ireless", "Commonition", "Dragoon", "Webster", "Utinam", "Obumbrate", "Inceptive"}
    return me
end init

on getWord()
    set randomNr to (random number from 1 to (length of (my allWords))) as integer
    --you could do somethinh here when a word is used again
    return item randomNr of my allWords as string
end getWord

конечный сценарий

родительское свойство сценария hangmanStdin: hangman

on init()
    return me
end init

on getChar(__prompt)
    set x to display dialog __prompt buttons {"Go", "Quit"} default button "Go" default answer ""
    if button returned of x = "Quit" then
        return false
    end if

    if length of x's text returned = 0 then
        return ""
    end if

    return character 1 of x's text returned
end getChar

on getOptions(__title, __message, __options)
    return button returned of (display alert __title message __message buttons __options default button 1)
end getOptions

конечный сценарий

родительское свойство сценария hangmanStdout: hangman

on init()
    return me
end init

on printf(__message)
    display dialog __message buttons {"OK"} default button 1
end printf

конечный сценарий

1 Ответ

0 голосов
/ 27 марта 2019

Это похоже на вашу другую тему , вам просто нужно следить за ходом вашего сценария.

В обработчике startGame() сценария hangmanGame вы используете *Обработчик 1007 * для определения того, было ли слово угадано, поэтому диалог может перейти туда, где вы получаете этот результат, например:

if my wordGuessed() then
  display dialog "You guessed the word!!!"
  set my score to ((25 * (26 / (length of my usedChars))) as integer)
  return true
end if
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...