1
$\begingroup$

My code is

DynamicModule[{n, guess = 0}, 
    {
     InputField[Dynamic[guess], Number], 
     Dynamic[If[n == guess, "You won", "Try again"]],
     Dynamic[n] (* for debugging *)
    }, 
 Initialization :> (n = RandomInteger[{1, 99}])]

but there are some problems. The number changes every time and doesn't refer to "you came close" or "decrease" or "increase".

I want to write code that directs me with hints. How do I do this?

$\endgroup$

1 Answer 1

1
$\begingroup$

How about something like this, with tolerance plus minus 5 and a SeedRandom to control the random numbers?

DynamicModule[{n, guess = 0}, {InputField[Dynamic[guess], Number], 
  Dynamic[Which[n == guess, "You won", guess < n - 5, 
    "Increase try again", guess > n + 5, "Decrease try again", 
    n - 5 <= guess <= n + 5, "you came close"]], Dynamic[n]}, 
 Initialization :> (SeedRandom[32]; n = RandomInteger[{1, 99}])]

@Hazal: In your initial question you didn't say that you also want the inputs to be refreshed. For this requirement, I have used Manipulate and added a "New Game" button in order the user to be able to start a new game even in the middle of their current game

Manipulate[SeedRandom[36 + sr]; n = RandomInteger[{1, 99}]; 
 Which[n == Guess, "You won", Guess < n - 5, 
  "Increase try again\nInput:" <> ToString[n], Guess > n + 5, 
  "Decrease try again\nInput:" <> ToString[n], 
  n - 5 <= Guess <= n + 5, 
  "you came close\nInput:" <> ToString[n]], {Guess, 0},
 {sr, 0, ControlType -> None},
 Button["New Game", sr = RandomInteger[{0, 10000000}]], 
 ControlType -> InputField]
$\endgroup$
1
  • $\begingroup$ Thank you very much I ran the code. but but the number is not refreshed after reaching the correct guess. how can i fix this $\endgroup$
    – hazal
    May 8, 2021 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.