Number Guessing Game

Here is a Number Guessing Game I copied from a Youtube video especially made for Anvil. I made it as a tutorial and to add on if you would like. Credit goes to the video.

Two issues I have is:
ValueError: invalid literal for int() with base 10: ‘’ when no number is typed.
And I do not know how to restart the game when it’s done.

This function should restart any Anvil app:

from anvil.js import window

def reload_current_tab():
    window.location.reload()
1 Like

Hi @rcrodney34,

For your ValueError just make sure you test the input of the user before trying to do anything with it.

if guess == "":
        Notification("You forgot to fill in a number. Try again.", "Error", style="danger").show()
    else:
        try:
            guess = int(guess)
            self.counter += 1
            self.label_4.text = f"You guessed {self.counter} time(s)."
            
            if guess == self.number:
                self.label_1.text = f"{guess} is the correct number!"
            elif guess < self.number:
                self.label_1.text = f"{guess} is lower than the correct number."
            else:
                self.label_1.text = f"{guess} is higher than the correct number."
        except ValueError:
            Notification(f"{guess} is not a valid number. Try again.", "Error",  style="danger").show()

Then for restarting the game. That’s a matter of changing your App’s structure and creating a function start_game

You should choose Standard Page just for one of your Forms. Then any other subsequent Form should be Blank Panel. This allows you to change the content_panel of your Standard Page Form to load other forms.

See more info here:

The start_game function can be called from within the Game Form. We are calling this each time the form is loaded as well.

  def start_game (self):
    self.lower_treshold = 1
    self.higher_treshold = 10
    self.number = random.randint(self.lower_treshold, self.higher_treshold)
    #displays answer in code
    print(self.number)
    #creates a counter
    self.counter = 0
    self.label_1.text = ""
    self.label_4.text = ""
    Notification("A new random number has been generated.", "Welcome", style="success").show()

You can find all the code here:

Bonus
If your form has variables defined as for example self.lower_treshold, then you can use them in your components as well. Just make sure you have assigned those variables before you try to self.init_components(**properties)

1 Like