ケースストラクチャ / ステートマシンを作る / 数当てゲーム

GuessingGame.vi - Google ドライブ
f:id:ti-nspire:20190417090921p:plain
f:id:ti-nspire:20190417090959p:plain:h400 f:id:ti-nspire:20190417091031p:plain:h400 f:id:ti-nspire:20190417091058p:plain:h400 f:id:ti-nspire:20190417091125p:plain:h400 f:id:ti-nspire:20190417091148p:plain:h400

――――――――――――――――――――――――――
Pythonで同じことをしてみる。

import random

GenerateInteger, EnterGuess, CheckGuess, GiveHint, ReportSuccess = range(5)
answer, guess, state = None, None, None

def handle_GenerateInteger_state():
    global answer, state
    answer = random.randint(1,10)
    state = EnterGuess

def handle_EnterGuess_state():
    global state, guess
    guess = int(input("Guess an integer in range from 1 to 10.\n"))
    state = CheckGuess

def handle_CheckGuess_state():
    global state
    if answer == guess:
        state = ReportSuccess
    else:
        state = GiveHint

def handle_GiveHint_state():
    global state
    if answer>guess:
        print("Your guess is too low, try again.")
    elif answer<guess:
        print("Your guess is too high, try again.")

    state = EnterGuess

def handle_ReportSuccess_state():
    print("Congratulations! You guessed it.\n")

state = GenerateInteger
while True:
    if state == GenerateInteger:
        handle_GenerateInteger_state()
    elif state == EnterGuess:
        handle_EnterGuess_state()
    elif state == CheckGuess:
        handle_CheckGuess_state()
    elif state == GiveHint:
        handle_GiveHint_state()
    elif state == ReportSuccess:
        handle_ReportSuccess_state()
        break