To make this work: we need to know
h or s to
hop or skip. Here is the code:
current_position = 1
field_length = 10
bad_position = 5
print 'Position', bad_position, 'is bad, avoid it!'
while True:
print 'You are at position', current_position
action = raw_input('Next? h to hop 1, s to skip 2: ')
if action == 'h':
current_position += 1
else:
current_position += 2
if current_position == bad_position:
print 'You lost!'
break
elif current_position == field_length:
print 'You won!'
break
Let's make the game more interesting, by adding two variations:
import
the random library. It has many functions, but
will only use these:
random.random() returns a
random float from 0.0 (inclusive) to 1.0 (not
inclusive).
random.randrange(x) returns a random value
from 0 (inclusive) to x (not inclusive). The
value x must be an int. For
example, random.randrange(5) may return 0, 1, 2,
3, or 4, at random, but will never return 5.
import random
field_length = 10
current_position = 1
slip_probability = 0.3
bad_position = random.randrange(field_length - 1) + 1
print 'Position', bad_position, 'is bad, avoid it!'
while True:
print 'You are at position', current_position
action = raw_input('Next? h to hop 1, s to skip 2: ')
if action == 'h':
current_position += 1
else:
current_position += 2
if random.random() < slip_probability:
print 'You slipped! Back to the beginning!'
current_position = 1
if current_position == bad_position:
print 'You lost!'
break
elif current_position == field_length:
print 'You won!'
break
Notice line 6: bad_position = random.randrange(field_length - 2) + 2.
What's going on here? Well, I don't want the "bad" position to
ever be 1 or 10 (otherwise you can't win the game), so:
field_length is 10,
field_length-2 is 8,
random.randrange(field_length-2) is a number
from 0 to 7, and so
random.randrange(field_length-2)+2 is a number
from 2 to 9.
if random.random() <
slip_probability: . What's going on here?
Well, slip_probability is 0.3,
and random.random() can return anywhere between 0.0 and
0.9999..., so the probability that it returns a number less than 0.3
is 30%, as desired.