Thursday, July 6, 2017

7/6

Something I like programming in different languages is a number guessing game, so I'll try to do that in Pyret as well. The program will do the following things:
Generate a random target number from 1-100.
Give the player 5 guesses to guess said number.
Have a function to allow to player to input a guess.
After each guess, inform the player if the guess was too high or too low.

Thanks to Pyret's simplicity, this shouldn't be too hard.
A quick search gives me the function to generate a random number, so setting variables for the target and number of guesses is the first thing I do.

var target=num-random(100)
var guesses=5

Then I wrote the function that allows the player to guess:

fun guess(x):
if 0 < guesses:   
    if x < target:
      "Too low. Guesses left: " + tostring(guesses)   
    else if target < x:
      "Too high. Guesses left: " + tostring(guesses)
    else if target == x:
      "You guessed it!"
    end
  else:
    "You're out of guesses! The number was: " + tostring(target)
end
end

It works fine, but there's a problem. The function doesn't actually decrease the number of guesses after a guess, allowing the player to guess an infinite amount of times. If I try to add a command to do so before the last 'end', Pyret gives me an error message: "This expression contains a block that contains multiple expressions," which is something that I've not had to deal with in other languages, so I'm thinking of a solution for it.

The solution is fairly simple. All I have to do is insert the "block:" command if I want to have an if statement then change the value of 'guesses' in succession. I'll admit that it took me far longer than it probably should have, but 'block:' seems to be unique to Pyret.

Here's the link to the finished game:
https://code.pyret.org/editor#share=0BzaGqkxKdpk4NUFhcjlYNUxBblE&v=06c8b98

No comments:

Post a Comment