-
Notifications
You must be signed in to change notification settings - Fork 1
/
number.py
87 lines (58 loc) · 2.24 KB
/
number.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# --
# Copyright (c) 2008-2017 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
# --
import random
from nagare import component, util, state
from nagare.continuation import has_continuation
# ---------------------------------------------------------------------------
examples = ()
class Number(component.Task):
"""A little game to guess a number
"""
def __init__(self, final_text):
self.final_text = final_text
def go(self, comp):
"""The game algorithm, using continuation for a pure linear Python code
In:
- ``comp`` -- this component
"""
self.attempt = 1
number = random.randint(1, 20)
comp.call(util.Confirm('I choose a number between 1 and 20. Try to guess it'))
while True:
x = comp.call(util.Ask('Try #%d: ' % self.attempt))
if not x.isdigit():
continue
x = int(x)
if x > number:
comp.call(util.Confirm('Choose a lower number'))
if x < number:
comp.call(util.Confirm('Choose a greater number'))
if x == number:
comp.call(util.Confirm(self.final_text % self.attempt))
break
self.attempt += 1
# ---------------------------------------------------------------------------
# This example shows that, by default, the objects are statefull
def example1():
# By default, an object is statefull
number = Number('''You found the secret number in %d tries.
Now use the 'back' button to cheat : go back to the first attempt and enter the correct number''')
return number
if has_continuation:
examples = ('A statefull component', example1)
# ---------------------------------------------------------------------------
# This example shows how to create stateless objects
def example2():
number = Number('''You found the secret number in %d tries.
Now use the 'back' button to cheat : you CAN'T''')
# The object is made stateless
number = state.stateless(number)
return number
if has_continuation:
examples += ('A stateless component', example2)