Meeting20130226: guessing.py

File guessing.py, 1.1 KB (added by Simon Cross, 8 years ago)

Simple guessing game (module).

Line 
1"""A guessing game
2
3   Pick a random number between 1 and 10
4   and ask someone to guess what it is.
5   """
6
7import random
8
9
10class GuessingGame:
11    """A simple guessing game."""
12
13    def __init__(self, start=1, end=10):
14        self._start = start
15        self._end = end
16        self._secret_number = self.pick()
17
18    def pick(self):
19        """Pick a random numner."""
20        i = random.randint(self._start, self._end)
21        return i
22
23    def ask(self):
24        """Ask the user to guess a number.
25
26           May raise a ValueError on invalid input.
27           """
28        answer = input("Pick a number from %d to %d: "
29                       % (self._start, self._end))
30        i = int(answer)
31        return i
32
33    def play(self):
34        """Play the game."""
35        while True:
36            try:
37                answer = self.ask()
38            except ValueError:
39                print("You gave up in frustration!")
40                break
41            if answer == self._secret_number:
42                print("Awesome!")
43                break
44            else:
45                print("Wrong, guess again.")
46
47